diff --git a/.github/workflows/pr-test-ppu.yml b/.github/workflows/pr-test-ppu.yml index b1f5c19f54..bcf89929eb 100644 --- a/.github/workflows/pr-test-ppu.yml +++ b/.github/workflows/pr-test-ppu.yml @@ -9,14 +9,14 @@ on: workflow_dispatch: inputs: run_all_tests: - description: "Run the preflight even if the last commit touched no PPU path" + description: "Build and run both sanity files even without PPU path changes" required: false type: boolean default: true workflow_call: inputs: ref: - description: 'Git ref (branch, tag, or SHA) to test. If not provided, uses the default branch.' + description: "Git ref to test; defaults to the triggering event SHA" required: false type: string default: '' @@ -27,8 +27,7 @@ on: default: false concurrency: - # Newer runs cancel older runs for the same ref; unrelated label events - # use isolated groups to avoid interfering with active runs. + # Unrelated label events must not cancel or replace the active PPU checks. group: >- pr-test-ppu-${{ (github.event_name == 'pull_request' && @@ -40,11 +39,15 @@ concurrency: }} cancel-in-progress: true +defaults: + run: + shell: bash + +env: + GIT_CONFIG_NOSYSTEM: "1" + jobs: - # ==================== Check Changes ==================== # check-changes: - # Give skipped checks from unrelated labels distinct names so they cannot - # replace the corresponding checks from an active run. name: >- ${{ (github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'run-ci' && github.event.label.name != 'run-ci-ppu') && @@ -59,25 +62,28 @@ jobs: contents: read pull-requests: read outputs: - # Scope only; the shared pr-gate checks both required labels. ppu: ${{ steps.filter.outputs.ppu == 'true' || steps.run-mode.outputs.run_all_tests == 'true' }} + source-sha: ${{ steps.source.outputs.sha }} steps: - name: Checkout code uses: actions/checkout@v4 with: - # github.sha (not github.ref) so a runner that dequeues after main - # advances still validates the SHA that triggered the run. ref: ${{ inputs.ref || github.sha }} + persist-credentials: false + + - name: Pin the source revision for every job + id: source + run: printf 'sha=%s\n' "$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Determine run mode id: run-mode + env: + RUN_ALL_TESTS: ${{ inputs.run_all_tests }} run: | - if [[ "${{ inputs.run_all_tests }}" == "true" ]]; then + if [[ "$RUN_ALL_TESTS" == "true" ]]; then echo "run_all_tests=true" >> "$GITHUB_OUTPUT" - echo "Run mode: ALL TESTS" else echo "run_all_tests=false" >> "$GITHUB_OUTPUT" - echo "Run mode: FILTERED (triggered by ${{ github.event_name }})" fi - name: Detect file changes @@ -85,16 +91,18 @@ jobs: uses: dorny/paths-filter@v3 if: steps.run-mode.outputs.run_all_tests != 'true' with: - # PPU-specific paths only. filters: | ppu: - ".github/workflows/pr-test-ppu.yml" - "scripts/ci/ppu/**" - - "python/sglang/srt/platforms/ppu.py" - - "python/sglang/srt/hardware_backend/ppu/**" - - "python/sglang/kernels/aot/csrc/ppu/**" + - "python/sglang/srt/platforms/sail.py" + - "python/sglang/kernels/aot/setup_sail.py" + - "python/sglang/kernels/aot/pyproject_sail.toml" + - "python/sglang/kernels/aot/csrc/common_extension_sail.cc" + - "python/sglang/kernels/jit/utils/compile/sailify.py" + - "test/registered/core/test_basic_sanity_eagle3.py" + - "test/registered/core/test_basic_sanity_dflash.py" - # ==================== PR Gate ==================== # pr-gate: name: >- ${{ (github.event_name == 'pull_request' && github.event.action == 'labeled' && @@ -108,62 +116,168 @@ jobs: require-label: run-ci-ppu secrets: inherit - # ==================== PPU Runner Preflight ==================== # - # Validates the runner contract only; the SRT platform and AOT kernels land - # in later PRs and build their first real test on top of this job. - ppu-preflight: + ppu-build: name: >- ${{ (github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'run-ci' && github.event.label.name != 'run-ci-ppu') && - 'ignored-label-ppu-preflight' || 'ppu-preflight' }} + 'ignored-label-ppu-build' || 'ppu-build' }} needs: [check-changes, pr-gate] if: needs.check-changes.outputs.ppu == 'true' - runs-on: 1-ppu-m890p - timeout-minutes: 60 + runs-on: ubuntu-24.04 + timeout-minutes: 120 + permissions: + contents: read + container: + image: download.t-head.cn/docker_release/pytorch:sdk2.2.0-2.13.0-ubuntu24.04-hggcrt3-py312-20261005 env: - SGLANG_IS_IN_CI: true + PPU_CI_SOURCE_SHA: ${{ needs.check-changes.outputs.source-sha }} + MAX_JOBS: "2" + SGL_KERNEL_COMPILE_THREADS: "2" + outputs: + wheel-artifact-id: ${{ steps.wheels.outputs.artifact-id }} steps: - - name: Checkout code + - name: Initialize private build directories and Git configuration + run: | + work="$(mktemp -d "${RUNNER_TEMP}/ppu-build.XXXXXX")" + touch "$work/gitconfig" + mkdir "$work/wheels" "$work/artifacts" + { + printf 'GIT_CONFIG_GLOBAL=%s\n' "$work/gitconfig" + printf 'PPU_CI_WHEEL_DIR=%s\n' "$work/wheels" + printf 'PPU_CI_ARTIFACT_DIR=%s\n' "$work/artifacts" + } >> "$GITHUB_ENV" + + # Same ref as check-changes. build_and_test.sh rejects any HEAD other than + # PPU_CI_SOURCE_SHA, so a workflow_call branch that moves after + # check-changes fails the run instead of building different code. + - name: Checkout the triggering source revision + uses: actions/checkout@v4 + with: + ref: ${{ inputs.ref || github.sha }} + persist-credentials: false + + - name: Build native SAIL wheels + run: | + mkdir -p "$PPU_CI_WHEEL_DIR" + bash scripts/ci/ppu/build_and_test.sh build + + - name: Upload PPU wheels + id: wheels + uses: actions/upload-artifact@v4 + with: + name: ppu-wheels-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.PPU_CI_WHEEL_DIR }} + if-no-files-found: error + + - name: Upload build diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: ppu-build-logs-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.PPU_CI_ARTIFACT_DIR }} + if-no-files-found: warn + + ppu-sanity: + name: >- + ${{ (github.event_name == 'pull_request' && github.event.action == 'labeled' && + github.event.label.name != 'run-ci' && github.event.label.name != 'run-ci-ppu') && + format('ignored-label-ppu-sanity ({0})', matrix.runner) || + format('ppu-sanity ({0})', matrix.runner) }} + needs: [check-changes, pr-gate, ppu-build] + if: needs.check-changes.outputs.ppu == 'true' + # Both PPU generations reuse the same wheels; each host supplies its own + # runtime image and device, while checkpoints come from the shared NAS. + strategy: + # A failure on one generation must not hide the other generation's result. + fail-fast: false + matrix: + runner: [8-ppu-m890p, 16-ppu-zw810e] + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + permissions: + contents: read + actions: read + env: + PPU_CI_SOURCE_SHA: ${{ needs.check-changes.outputs.source-sha }} + steps: + - name: Initialize private runtime directories and Git configuration + run: | + work="$(mktemp -d "${RUNNER_TEMP}/ppu-runtime.XXXXXX")" + touch "$work/gitconfig" + mkdir "$work/wheels" "$work/artifacts" + { + printf 'GIT_CONFIG_GLOBAL=%s\n' "$work/gitconfig" + printf 'PPU_CI_WHEEL_DIR=%s\n' "$work/wheels" + printf 'PPU_CI_ARTIFACT_DIR=%s\n' "$work/artifacts" + } >> "$GITHUB_ENV" + + # Same ref as check-changes; run_test.sh rejects any HEAD other than + # PPU_CI_SOURCE_SHA. + - name: Checkout the triggering source revision timeout-minutes: 10 uses: actions/checkout@v4 with: ref: ${{ inputs.ref || github.sha }} + persist-credentials: false - - name: Validate PPU runner contract - timeout-minutes: 10 - run: python3 scripts/ci/ppu/check_ppu_environment.py + - name: Download the matching PPU wheel artifact + uses: actions/download-artifact@v4 + with: + artifact-ids: ${{ needs.ppu-build.outputs.wheel-artifact-id }} + merge-multiple: true + path: ${{ env.PPU_CI_WHEEL_DIR }} + + - name: Run both speculative sanity files in isolated Docker + env: + CONFIG_PPU_CI_DEVICE: ${{ vars.PPU_CI_DEVICE }} + CONFIG_PPU_CI_TARGET_MODEL_PATH: ${{ vars.PPU_CI_TARGET_MODEL_PATH }} + CONFIG_PPU_CI_EAGLE3_MODEL_PATH: ${{ vars.PPU_CI_EAGLE3_MODEL_PATH }} + CONFIG_PPU_CI_DFLASH_MODEL_PATH: ${{ vars.PPU_CI_DFLASH_MODEL_PATH }} + CONFIG_PPU_CI_EVAL_CACHE: ${{ vars.PPU_CI_EVAL_CACHE }} + run: | + for key in PPU_CI_DEVICE PPU_CI_TARGET_MODEL_PATH PPU_CI_EAGLE3_MODEL_PATH PPU_CI_DFLASH_MODEL_PATH PPU_CI_EVAL_CACHE; do + override="CONFIG_$key" + if [[ -n "${!override}" ]]; then + export "$key=${!override}" + fi + done + exec bash scripts/ci/ppu/run_test.sh + + - name: Upload runtime diagnostics + if: always() + uses: actions/upload-artifact@v4 + with: + name: ppu-runtime-logs-${{ matrix.runner }}-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ env.PPU_CI_ARTIFACT_DIR }} + if-no-files-found: warn - # ==================== Finish ==================== # pr-test-ppu-finish: name: >- ${{ (github.event_name == 'pull_request' && github.event.action == 'labeled' && github.event.label.name != 'run-ci' && github.event.label.name != 'run-ci-ppu') && 'ignored-label-pr-test-ppu-finish' || 'pr-test-ppu-finish' }} - needs: [pr-gate, check-changes, ppu-preflight] + needs: [pr-gate, check-changes, ppu-build, ppu-sanity] if: always() && needs.check-changes.result != 'skipped' runs-on: ubuntu-latest + permissions: {} steps: - - name: Check all dependent job statuses + - name: Require successful native build and both PPU sanity files when requested + env: + NEEDS_JSON: ${{ toJson(needs) }} + PPU_IN_SCOPE: ${{ needs.check-changes.outputs.ppu }} + BUILD_RESULT: ${{ needs.ppu-build.result }} + SANITY_RESULT: ${{ needs.ppu-sanity.result }} run: | - json_needs='${{ toJson(needs) }}' - for job in $(echo "$json_needs" | jq -r 'keys_unsorted[]'); do - result=$(echo "$json_needs" | jq -r --arg j "$job" '.[$j].result') - echo "$job: $result" - if [[ "$result" == "failure" || "$result" == "cancelled" ]]; then - echo "The above jobs failed." - exit 1 - fi - done - echo "All jobs completed successfully" - - - name: Require the preflight when PPU is in scope - run: | - in_scope='${{ needs.check-changes.outputs.ppu }}' - preflight='${{ needs.ppu-preflight.result }}' - echo "PPU in scope: '$in_scope' / ppu-preflight: '$preflight'" - - if [[ "$in_scope" == "true" && "$preflight" != "success" ]]; then - echo "PPU was in scope but ppu-preflight did not succeed." + if jq -e 'any(.[]; .result == "failure" or .result == "cancelled")' <<< "$NEEDS_JSON" >/dev/null; then + printf '%s\n' '::error::A PPU CI dependency failed or was cancelled.' exit 1 fi - echo "Preflight status is consistent with the requested scope." + if [[ "$PPU_IN_SCOPE" == "true" ]]; then + if [[ "$BUILD_RESULT" != "success" || "$SANITY_RESULT" != "success" ]]; then + printf '%s\n' '::error::PPU scope requires a successful native build and both PPU sanity files.' + exit 1 + fi + printf '%s\n' 'Native build and both PPU sanity files passed.' + else + printf '%s\n' 'PPU is outside this run scope; no PPU tests were requested.' + fi diff --git a/docs/docs.json b/docs/docs.json index ac24019d9f..6f46f0cc51 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -1210,6 +1210,7 @@ ] }, "docs/hardware-platforms/mthreads_gpu", + "docs/hardware-platforms/sail", "docs/hardware-platforms/tpu", "docs/hardware-platforms/xpu", "docs/hardware-platforms/plugin" diff --git a/docs/docs/hardware-platforms/sail.mdx b/docs/docs/hardware-platforms/sail.mdx new file mode 100644 index 0000000000..35ee39065a --- /dev/null +++ b/docs/docs/hardware-platforms/sail.mdx @@ -0,0 +1,83 @@ +--- +title: "T-HEAD SAILs" +metatags: + description: "Run SGLang on T-HEAD SAILs." +--- + +This document describes how to run SGLang on T-HEAD SAILs. If you +encounter issues or have questions, please [open an issue](https://github.com/sgl-project/sglang/issues). + +## Prerequisites + +Install the T-HEAD SAIL driver and the PPU SDK before installing SGLang, and export +the `PPU_SDK` environment variable pointing at the SDK installation (for +example, `/usr/local/PPU_SDK`). The Triton SAIL backend requires this variable +when compiling kernels at runtime. + +Verify that the device is visible: + +```bash Command +python3 -c 'import torch; print(torch.cuda.get_device_name())' +# Expected: a ZW-series device, e.g. "ZW810E" +``` + +## Install SGLang + +### Install from Source + +Start from an environment with the prerequisites above installed. + +```bash Command +git clone https://github.com/sgl-project/sglang.git +cd sglang + +python -m pip install --upgrade pip wheel + +cp python/pyproject_other.toml python/pyproject.toml +python -m pip install -e "python[all_sail]" \ + --no-build-isolation + +# Install sailify +python -m pip install sailify==1.0.0 + +# Build sgl-kernel for SAIL from source +cd python/sglang/kernels/aot +python setup_sail.py install +``` + +Launch the server: + +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --host 0.0.0.0 \ + --port 30000 +``` + +When the server displays `The server is fired up and ready to roll!`, startup is +successful. + +## Verify + +You can send an OpenAI-compatible request to the engine: + +```bash Command +curl http://127.0.0.1:30000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "Qwen/Qwen3-8B", + "messages": [{"role": "user", "content": "Hello!"}], + "max_tokens": 32 + }' +``` + +Or run a benchmark: + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --dataset-name random \ + --num-prompts 4000 \ + --random-input 128 \ + --random-output 128 +``` diff --git a/python/pyproject_other.toml b/python/pyproject_other.toml index 5314a2eeb3..12056c516b 100755 --- a/python/pyproject_other.toml +++ b/python/pyproject_other.toml @@ -161,6 +161,14 @@ diffusion_hip = [ # https://docs.vllm.ai/en/latest/getting_started/gaudi-installation.html srt_hpu = ["sglang[runtime_common]"] +# https://docs.sglang.io/hardware-platforms/sail +srt_sail = [ + "sailify==1.0.0", + "sglang[runtime_common]", + "torch-for-sail", + "triton-for-sail", +] + # https://docs.sglang.io/platforms/mthreads_gpu.md srt_musa = [ "apache-tvm-ffi==0.1.11.post1+musa.1", @@ -235,6 +243,7 @@ all_hip = ["sglang[diffusion_hip]", "sglang[srt_hip]", "sglang[tracing]"] all_hip_rocm724 = ["sglang[diffusion_hip]", "sglang[srt_hip_rocm724]", "sglang[tracing]"] all_hip_rocm101 = ["sglang[diffusion_hip]", "sglang[srt_hip_rocm101]", "sglang[tracing]"] all_hpu = ["sglang[srt_hpu]"] +all_sail = ["sglang[srt_sail]"] all_musa = ["sglang[diffusion_musa]", "sglang[srt_musa]"] all_mps = ["sglang[diffusion_mps]", "sglang[srt_mps]"] @@ -242,6 +251,7 @@ dev_hip = ["sglang[all_hip]", "sglang[test]"] dev_hip_rocm724 = ["sglang[all_hip_rocm724]", "sglang[test]"] dev_hip_rocm101 = ["sglang[all_hip_rocm101]", "sglang[test]"] dev_hpu = ["sglang[all_hpu]", "sglang[test]"] +dev_sail = ["sglang[all_sail]", "sglang[test]"] dev_musa = ["sglang[all_musa]", "sglang[test]"] dev_mps = ["sglang[all_mps]", "sglang[test]"] diff --git a/python/sglang/kernels/aot/csrc/common_extension_sail.cc b/python/sglang/kernels/aot/csrc/common_extension_sail.cc new file mode 100644 index 0000000000..4f529a5c84 --- /dev/null +++ b/python/sglang/kernels/aot/csrc/common_extension_sail.cc @@ -0,0 +1,300 @@ +/* Copyright 2025 SGLang Team. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include +#include +#include + +#include "sgl_kernel_ops.h" + +TORCH_LIBRARY_FRAGMENT(sgl_kernel, m) { + /* + * From csrc/allreduce + */ + m.def("get_graph_buffer_ipc_meta", &get_graph_buffer_ipc_meta); + m.def("register_graph_buffers", ®ister_graph_buffers); + m.def("dispose", &dispose); + m.def("meta_size", &meta_size); + m.def("register_buffer", ®ister_buffer); + + m.def( + "init_custom_ar(int[] ipc_tensors, Tensor rank_data, " + "int rank, bool full_nvlink) -> int"); + m.impl("init_custom_ar", torch::kCUDA, &init_custom_ar); + + m.def( + "all_reduce(int fa, Tensor inp, Tensor! out, int reg_buffer, " + "int reg_buffer_sz_bytes) -> ()"); + m.impl("all_reduce", torch::kCUDA, &all_reduce); + + /* + * From csrc/attention + */ + m.def("merge_state_v2(Tensor v_a, Tensor s_a, Tensor v_b, Tensor s_b, Tensor! v_merged, Tensor! s_merged) -> ()"); + m.impl("merge_state_v2", torch::kCUDA, &merge_state_v2); + + /* + * From csrc/elementwise + */ + m.def("rmsnorm(Tensor! output, Tensor input, Tensor weight, float eps, bool enable_pdl) -> ()"); + m.impl("rmsnorm", torch::kCUDA, &rmsnorm); + + m.def("fused_add_rmsnorm(Tensor! input, Tensor! residual, Tensor weight, float eps, bool enable_pdl) -> ()"); + m.impl("fused_add_rmsnorm", torch::kCUDA, &sgl_fused_add_rmsnorm); + + m.def("gemma_rmsnorm(Tensor! output, Tensor input, Tensor weight, float eps, bool enable_pdl) -> ()"); + m.impl("gemma_rmsnorm", torch::kCUDA, &gemma_rmsnorm); + + m.def("gemma_fused_add_rmsnorm(Tensor! input, Tensor! residual, Tensor weight, float eps, bool enable_pdl) -> ()"); + m.impl("gemma_fused_add_rmsnorm", torch::kCUDA, &gemma_fused_add_rmsnorm); + + m.def("silu_and_mul(Tensor! out, Tensor input) -> ()"); + m.impl("silu_and_mul", torch::kCUDA, &silu_and_mul); + + m.def("gelu_tanh_and_mul(Tensor! out, Tensor input) -> ()"); + m.impl("gelu_tanh_and_mul", torch::kCUDA, &gelu_tanh_and_mul); + + m.def("gelu_and_mul(Tensor! out, Tensor input) -> ()"); + m.impl("gelu_and_mul", torch::kCUDA, &gelu_and_mul); + + m.def( + "rotary_embedding(Tensor positions, Tensor! query," + " Tensor!? key, int head_size," + " Tensor cos_sin_cache, bool is_neox) -> ()"); + m.impl("rotary_embedding", torch::kCUDA, &rotary_embedding); + + m.def("copy_to_gpu_no_ce(Tensor input, Tensor! output) -> ()"); + m.impl("copy_to_gpu_no_ce", torch::kCUDA, ©_to_gpu_no_ce); + m.def("concat_mla_k(Tensor! k, Tensor k_nope, Tensor k_rope) -> ()"); + m.impl("concat_mla_k", torch::kCUDA, &concat_mla_k); + + m.def("concat_mla_absorb_q(Tensor a, Tensor b, Tensor! out) -> ()"); + m.impl("concat_mla_absorb_q", torch::kCUDA, &concat_mla_absorb_q); + + m.def("fast_topk(Tensor score, Tensor indices, Tensor lengths, Tensor? row_starts) -> ()"); + m.impl("fast_topk", torch::kCUDA, &fast_topk_interface); + m.def( + "fast_topk_transform_fused(Tensor score, Tensor lengths, Tensor dst_page_table, Tensor src_page_table, Tensor " + "cu_seqlens_q, Tensor? row_starts) -> ()"); + m.impl("fast_topk_transform_fused", torch::kCUDA, &fast_topk_transform_interface); + m.def( + "fast_topk_transform_ragged_fused(Tensor score, Tensor lengths, Tensor topk_indices_ragged, Tensor " + "topk_indices_offset, Tensor ? row_starts) -> ()"); + m.impl("fast_topk_transform_ragged_fused", torch::kCUDA, &fast_topk_transform_ragged_interface); + + /* + * From csrc/gemm + */ + m.def( + "sgl_per_token_group_quant_8bit(Tensor input, Tensor! output_q, Tensor! output_s, int group_size," + " float eps, float fp8_min, float fp8_max, bool scale_ue8m0) -> ()"); + m.impl("sgl_per_token_group_quant_8bit", torch::kCUDA, &sgl_per_token_group_quant_8bit); + + m.def( + "sgl_per_token_group_quant_8bit_v2(Tensor input, Tensor! output_q, Tensor! output_s, int group_size," + " float eps, float fp8_min, float fp8_max, bool scale_ue8m0, bool fuse_silu_and_mul, Tensor? masked_m) -> ()"); + m.impl("sgl_per_token_group_quant_8bit_v2", torch::kCUDA, &sgl_per_token_group_quant_8bit_v2); + + m.def("sgl_per_token_quant_fp8(Tensor input, Tensor! output_q, Tensor! output_s) -> ()"); + m.impl("sgl_per_token_quant_fp8", torch::kCUDA, &sgl_per_token_quant_fp8); + + /* + * From csrc/moe + */ + m.def( + "moe_align_block_size(Tensor topk_ids, int num_experts, int block_size, Tensor! sorted_token_ids, Tensor! " + "experts_ids, Tensor! num_tokens_post_pad, Tensor! cumsum_buffer, bool " + "pad_sorted_token_ids, bool ignore_invalid_expert) -> ()"); + m.impl("moe_align_block_size", torch::kCUDA, &moe_align_block_size); + + m.def( + "topk_softmax(Tensor! topk_weights, Tensor! topk_indices, Tensor gating_output, bool renormalize, float " + "moe_softcapping, Tensor? correction_bias) -> ()"); + m.impl("topk_softmax", torch::kCUDA, &topk_softmax); + + m.def( + "topk_sigmoid(Tensor! topk_weights, Tensor! topk_indices, Tensor gating_output, bool renormalize, Tensor? " + "correction_bias) -> ()"); + m.impl("topk_sigmoid", torch::kCUDA, &topk_sigmoid); + + m.def("moe_sum_reduce(Tensor input, Tensor output, float routed_scaling_factor) -> ()"); + m.impl("moe_sum_reduce", torch::kCUDA, &moe_sum_reduce); + + m.def("moe_sum(Tensor input, Tensor! output) -> ()"); + m.impl("moe_sum", torch::kCUDA, &moe_sum); + + // moe_fused_gate / kimi_k2_moe_fused_gate (AOT) retired: the gate/topk path + // now routes through the unified Triton router + // (python/sglang/jit_kernel/moe_fused_gate.py). + + m.def( + "prepare_moe_input(Tensor topk_ids, Tensor expert_offsets, Tensor? blockscale_offsets, Tensor problem_sizes1," + " Tensor problem_sizes2, Tensor input_permutation, Tensor output_permutation, int num_experts, int n, int k) -> " + "()"); + m.impl("prepare_moe_input", torch::kCUDA, &prepare_moe_input); + + m.def("shuffle_rows(Tensor input, Tensor dst2src_map, Tensor output) -> ()"); + m.impl("shuffle_rows", torch::kCUDA, &shuffle_rows); + + m.def("apply_shuffle_mul_sum(Tensor input, Tensor output, Tensor permutation, Tensor? factors) -> ()"); + m.impl("apply_shuffle_mul_sum", torch::kCUDA, &apply_shuffle_mul_sum); + + m.def( + "fused_qk_norm_rope(Tensor! qkv, int num_heads_q, " + "int num_heads_k, int num_heads_v, int head_dim, float eps, " + "Tensor q_weight, Tensor k_weight, float base, " + "bool is_neox, Tensor position_ids, float factor, float low, float high, float attention_factor, int rotary_dim) " + "-> ()"); + m.impl("fused_qk_norm_rope", torch::kCUDA, &fused_qk_norm_rope); + + /* + * From csrc/kvcacheio + */ + m.def( + "transfer_kv_per_layer(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor " + "dst_indices, int item_size, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_per_layer", torch::kCUDA, &transfer_kv_per_layer); + m.def( + "transfer_kv_per_layer_pf_lf(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor " + "dst_indices, int layer_id, int item_size, int src_layout_dim, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_per_layer_pf_lf", torch::kCUDA, &transfer_kv_per_layer_pf_lf); + m.def( + "transfer_kv_per_layer_ph_lf(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor " + "dst_indices, int layer_id, int item_size, int src_layout_dim, int page_size, int head_num, int block_quota, int " + "num_warps_per_block) -> ()"); + m.impl("transfer_kv_per_layer_ph_lf", torch::kCUDA, &transfer_kv_per_layer_ph_lf); + m.def( + "transfer_kv_all_layer(Tensor src_k_layers, Tensor dst_k_layers, Tensor src_v_layers, Tensor dst_v_layers, " + "Tensor src_indices, Tensor dst_indices, int item_size, int num_layers, int block_quota, int " + "num_warps_per_block) -> ()"); + m.impl("transfer_kv_all_layer", torch::kCUDA, &transfer_kv_all_layer); + m.def( + "transfer_kv_all_layer_lf_pf(Tensor src_k_layers, Tensor dst_k, Tensor src_v_layers, Tensor dst_v, " + "Tensor src_indices, Tensor dst_indices, int item_size, int dst_layout_dim, int num_layers, int block_quota, int " + "num_warps_per_block) -> ()"); + m.impl("transfer_kv_all_layer_lf_pf", torch::kCUDA, &transfer_kv_all_layer_lf_pf); + m.def( + "transfer_kv_all_layer_lf_ph(Tensor src_k_layers, Tensor dst_k, Tensor src_v_layers, Tensor dst_v, " + "Tensor src_indices, Tensor dst_indices, int item_size, int dst_layout_dim, int num_layers, int page_size, int " + "head_num, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_all_layer_lf_ph", torch::kCUDA, &transfer_kv_all_layer_lf_ph); + m.def( + "transfer_kv_per_layer_mla(Tensor src, Tensor dst, Tensor src_indices, Tensor dst_indices, int item_size, int " + "block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_per_layer_mla", torch::kCUDA, &transfer_kv_per_layer_mla); + m.def( + "transfer_kv_per_layer_mla_pf_lf(Tensor src, Tensor dst, Tensor src_indices, Tensor dst_indices, int layer_id, " + "int item_size, int src_layout_dim, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_per_layer_mla_pf_lf", torch::kCUDA, &transfer_kv_per_layer_mla_pf_lf); + m.def( + "transfer_kv_all_layer_mla(Tensor src_layers, Tensor dst_layers, Tensor src_indices, Tensor dst_indices, int " + "item_size, int num_layers, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_all_layer_mla", torch::kCUDA, &transfer_kv_all_layer_mla); + m.def( + "transfer_kv_all_layer_mla_lf_pf(Tensor src_layers, Tensor dst, Tensor src_indices, Tensor dst_indices, " + "int item_size, int dst_layout_dim, int num_layers, int block_quota, int num_warps_per_block) -> ()"); + m.impl("transfer_kv_all_layer_mla_lf_pf", torch::kCUDA, &transfer_kv_all_layer_mla_lf_pf); + m.def( + "transfer_kv_direct(Tensor[] src_layers, Tensor[] dst_layers, Tensor src_indices, Tensor dst_indices, int " + "page_size) -> ()"); + m.impl("transfer_kv_direct", torch::kCUDA, &transfer_kv_direct); + m.def( + "transfer_kv_per_layer_direct_pf_lf(Tensor[] src_ptrs, Tensor[] dst_ptrs, Tensor src_indices, " + "Tensor dst_indices, int layer_id, int page_size)->() "); + m.impl("transfer_kv_per_layer_direct_pf_lf", torch::kCUDA, &transfer_kv_per_layer_direct_pf_lf); + m.def( + "transfer_kv_all_layer_direct_lf_pf(Tensor[] src_ptrs, Tensor[] dst_ptrs, Tensor src_indices, " + "Tensor dst_indices, int page_size) ->() "); + m.impl("transfer_kv_all_layer_direct_lf_pf", torch::kCUDA, &transfer_kv_all_layer_direct_lf_pf); + + /* + * From csrc/memory + */ + m.def("weak_ref_tensor(Tensor tensor) -> Tensor"); + m.impl("weak_ref_tensor", torch::kCUDA, &weak_ref_tensor); + + /* + * From FlashInfer + */ + m.def("top_k_renorm_probs(Tensor probs, Tensor! renorm_probs, Tensor? maybe_top_k_arr, int top_k_val) -> ()"); + m.impl("top_k_renorm_probs", torch::kCUDA, &top_k_renorm_probs); + + m.def("top_p_renorm_probs(Tensor probs, Tensor! renorm_probs, Tensor? maybe_top_p_arr, float top_p_val) -> ()"); + m.impl("top_p_renorm_probs", torch::kCUDA, &top_p_renorm_probs); + + /* + * From csrc/grammar + */ + m.def("apply_token_bitmask_inplace_cuda(Tensor logits, Tensor bitmask, Tensor? indices=None) -> ()"); + m.impl("apply_token_bitmask_inplace_cuda", &ApplyTokenBitmaskInplace); + + /* + * From csrc/quantization/gguf + */ + m.def( + "ggml_dequantize(Tensor W, int type, SymInt m, SymInt n, ScalarType? " + "dtype) -> Tensor"); + m.impl("ggml_dequantize", torch::kCUDA, &ggml_dequantize); + + m.def( + "ggml_mul_mat_vec_a8(Tensor W, Tensor X, int type, SymInt row) " + "-> Tensor"); + m.impl("ggml_mul_mat_vec_a8", torch::kCUDA, &ggml_mul_mat_vec_a8); + + m.def("ggml_mul_mat_a8(Tensor W, Tensor X, int type, SymInt row) -> Tensor"); + m.impl("ggml_mul_mat_a8", torch::kCUDA, &ggml_mul_mat_a8); + + m.def( + "ggml_moe_a8(Tensor X, Tensor W, " + "Tensor sorted_token_ids, Tensor expert_ids, Tensor " + "num_tokens_post_padded, " + "int type, SymInt row, SymInt top_k, SymInt tokens) -> Tensor"); + m.impl("ggml_moe_a8", torch::kCUDA, &ggml_moe_a8); + + m.def( + "ggml_moe_a8_vec(Tensor X, Tensor W, " + "Tensor topk_ids, int top_k, " + "int type, SymInt row, SymInt tokens) -> Tensor"); + m.impl("ggml_moe_a8_vec", torch::kCUDA, &ggml_moe_a8_vec); + + m.def("ggml_moe_get_block_size(int type) -> int"); + m.impl("ggml_moe_get_block_size", torch::kCUDA, &ggml_moe_get_block_size); + + /* + * From csrc/mamba + */ + m.def( + "causal_conv1d_update(Tensor! x," + "Tensor! conv_state," + "Tensor! weight," + "Tensor? bias_," + "bool silu_activation," + "Tensor? cache_seqlens_," + "Tensor? conv_state_indices," + "int pad_slot_id) -> ()"); + m.impl("causal_conv1d_update", torch::kCUDA, &causal_conv1d_update); + + m.def( + "causal_conv1d_fwd(Tensor! x, Tensor! weight," + "Tensor? bias_," + "Tensor!? conv_states," + "Tensor? query_start_loc," + "Tensor? cache_indices," + "Tensor? has_initial_state," + "bool silu_activation," + "int pad_slot_id) -> ()"); + m.impl("causal_conv1d_fwd", torch::kCUDA, &causal_conv1d_fwd); +} + +REGISTER_EXTENSION(common_ops) diff --git a/python/sglang/kernels/aot/pyproject_sail.toml b/python/sglang/kernels/aot/pyproject_sail.toml new file mode 100644 index 0000000000..9ad7b8fa03 --- /dev/null +++ b/python/sglang/kernels/aot/pyproject_sail.toml @@ -0,0 +1,32 @@ +[build-system] +requires = [ + "setuptools>=75.0", + "scikit-build-core>=0.10", + "torch>=2.8.0", + "wheel", +] +build-backend = "setuptools.build_meta" + +[project] +name = "sglang-kernel" +version = "0.4.9" +description = "Kernel Library for SGLang" +readme = "README.md" +requires-python = ">=3.10" +license = { file = "LICENSE" } +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Environment :: GPU :: T-HEAD SAIL" +] +dependencies = [] + +[project.urls] +"Homepage" = "https://github.com/sgl-project/sglang/tree/main/python/sglang/kernels/aot" +"Bug Tracker" = "https://github.com/sgl-project/sglang/issues" + +[tool.wheel] +exclude = [ + "dist*", + "tests*", +] diff --git a/python/sglang/kernels/aot/setup_sail.py b/python/sglang/kernels/aot/setup_sail.py new file mode 100644 index 0000000000..8989c820fa --- /dev/null +++ b/python/sglang/kernels/aot/setup_sail.py @@ -0,0 +1,545 @@ +# Copyright 2025 SGLang Team. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import atexit +import os +import platform +import shutil +import subprocess +from pathlib import Path + +import torch +from setuptools import find_namespace_packages, setup +from torch.utils.cpp_extension import BuildExtension, CUDAExtension + +root = Path(__file__).parent.resolve() +third_party = Path( + os.environ.get("SGL_KERNEL_THIRD_PARTY_DIR", root / "build" / "_deps") +) +arch = platform.machine().lower() + +# ======================= CUDA Version Detection ======================= # +cuda_version = torch.version.cuda +if cuda_version is None: + raise RuntimeError("CUDA is not available in the current PyTorch installation.") + +cuda_version_tuple = tuple(int(x) for x in cuda_version.split(".")[:2]) +print(f"Detected CUDA version: {cuda_version} ({cuda_version_tuple})") + + +# ======================= Third-Party Repository Info ======================= # +class _RepoInfo: + """Configuration for a third-party git repository.""" + + def __init__(self, name, git_repository, git_tag, git_shallow=False): + self.name = name + self.git_repository = git_repository + self.git_tag = git_tag + self.git_shallow = git_shallow + self.source_dir = third_party / name + + +_ACTLIZE_REPO = _RepoInfo( + name="actlize", + git_repository="https://github.com/t-head/actlize", + git_tag="129651181ed29ec3d3e61df786f610926b739a9b", + git_shallow=False, +) + +_ACTLIZE_DIR = Path(os.environ.get("SGL_KERNEL_ACTLIZE_DIR", _ACTLIZE_REPO.source_dir)) + +_FLASHINFER_REPO = _RepoInfo( + name="flashinfer", + git_repository="https://github.com/flashinfer-ai/flashinfer.git", + git_tag="bc29697ba20b7e6bdb728ded98f04788e16ee021", + git_shallow=False, +) + +_TRITON_REPO = _RepoInfo( + name="triton", + git_repository="https://github.com/triton-lang/triton", + git_tag="v3.7.0", + git_shallow=False, +) + +ALL_REPOS = [ + _ACTLIZE_REPO, + _FLASHINFER_REPO, + _TRITON_REPO, +] + + +# ======================= Version ======================= # +def _get_version(): + with open(root / "pyproject_sail.toml") as f: + for line in f: + if line.startswith("version"): + return line.split("=")[1].strip().strip('"') + return "0.0.0" + + +# ======================= Build Configuration ======================= # +operator_namespace = "sgl-kernel" + +# Determine CXX ABI compatibility with PyTorch +torch_cxx11_abi = int(torch._C._GLIBCXX_USE_CXX11_ABI) +abi_flag = f"-D_GLIBCXX_USE_CXX11_ABI={torch_cxx11_abi}" + +enable_bf16 = os.environ.get("SGL_KERNEL_ENABLE_BF16", "1").lower() in ( + "1", + "true", + "on", + "yes", +) +enable_fp8 = os.environ.get("SGL_KERNEL_ENABLE_FP8", "1").lower() in ( + "1", + "true", + "on", + "yes", +) +compile_threads = int(os.environ.get("SGL_KERNEL_COMPILE_THREADS", "32")) +if compile_threads < 1: + compile_threads = 1 + +# ======================= hgcc (device compiler) Flags ======================= # +# No `-gencode`: hgcc takes `--gpu-architecture=ppu_XX` instead, and SAIL torch +# emits that itself from the PYTORCH_SAIL_ARCH environment variable (see +# torch.utils.cpp_extension._get_cuda_arch_flags). Passing a CUDA `-gencode` here +# makes hgcc fail outright, so the arch selection is left entirely to +# PYTORCH_SAIL_ARCH (`ppu_10`, `ppu_15`, or a semicolon-separated list). +sgl_kernel_cuda_flags = [ + "-DNDEBUG", + f"-DOPERATOR_NAMESPACE={operator_namespace}", + "-O3", + "-Xcompiler", + "-fPIC", + "-std=c++17", + "-DFLASHINFER_ENABLE_F16", + "-DCUTE_USE_PACKED_TUPLE=1", + "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1", + "-DCUTLASS_VERSIONS_GENERATED", + "-DCUTLASS_TEST_LEVEL=0", + "-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1", + "-DCUTLASS_DEBUG_TRACE_LEVEL=0", + "--expt-relaxed-constexpr", + "--expt-extended-lambda", + "-U__HGGC_NO_HALF_OPERATORS__", + "-U__HGGC_NO_HALF_CONVERSIONS__", + "-U__HGGC_NO_HALF2_OPERATORS__", + "-U__HGGC_NO_BFLOAT16_CONVERSIONS__", + f"--threads={compile_threads}", + # Suppress warnings + "-Xcompiler=-Wno-clang-format-violations", + "-Xcompiler=-Wno-conversion", + "-Xcompiler=-Wno-deprecated-declarations", + "-Xcompiler=-Wno-terminate", + "-Xcompiler=-Wfatal-errors", + "-Xcompiler=-ftemplate-backtrace-limit=1", + # `-Xcudafe` is an nvcc-only hand-off to cudafe++, which hgcc has no + # counterpart for and rejects. The diagnostics it used to suppress (177 + # unused-variable, 2361) are nvcc frontend numbers with no hgcc analogue. + f"-Xcompiler={abi_flag}", + abi_flag, +] + +if enable_bf16: + sgl_kernel_cuda_flags.append("-DFLASHINFER_ENABLE_BF16") + +if enable_fp8: + sgl_kernel_cuda_flags.extend( + [ + "-DFLASHINFER_ENABLE_FP8", + "-DFLASHINFER_ENABLE_FP8_E4M3", + "-DFLASHINFER_ENABLE_FP8_E5M2", + ] + ) + +# ======================= Include Directories ======================= # +# Upstream (non-sailified) include directories. When sailify staging is +# active (see the "Sailify Source Staging" section below), the staged mirror +# directories are prepended so that converted headers shadow their upstream +# originals; the entries below then only act as a fallback for headers that +# were not part of the conversion closure. +base_include_dirs = [ + str(root / "include"), + str(root / "csrc"), + str(_ACTLIZE_DIR / "include"), + str(_ACTLIZE_DIR / "tools" / "util" / "include"), + str(_FLASHINFER_REPO.source_dir / "include"), + str(_FLASHINFER_REPO.source_dir / "csrc"), + str(_ACTLIZE_DIR / "examples" / "77_blackwell_fmha"), + str(_ACTLIZE_DIR / "examples" / "common"), +] + +# ======================= Source Files ======================= # +common_sources = [ + "csrc/allreduce/custom_all_reduce.cu", + "csrc/attention/merge_attn_states.cu", + "csrc/common_extension_sail.cc", + "csrc/elementwise/activation.cu", + "csrc/elementwise/concat_mla.cu", + "csrc/elementwise/copy.cu", + "csrc/elementwise/fused_add_rms_norm_kernel.cu", + "csrc/elementwise/pos_enc.cu", + "csrc/elementwise/topk.cu", + "csrc/gemm/per_token_group_quant_8bit.cu", + "csrc/gemm/per_token_group_quant_8bit_v2.cu", + "csrc/gemm/per_token_quant_fp8.cu", + "csrc/grammar/apply_token_bitmask_inplace_cuda.cu", + "csrc/kvcacheio/transfer.cu", + "csrc/mamba/causal_conv1d.cu", + "csrc/memory/weak_ref_tensor.cpp", + "csrc/moe/moe_align_kernel.cu", + "csrc/moe/fused_qknorm_rope_kernel.cu", + "csrc/moe/moe_sum.cu", + "csrc/moe/moe_sum_reduce.cu", + "csrc/moe/moe_topk_softmax_kernels.cu", + "csrc/moe/moe_topk_sigmoid_kernels.cu", + "csrc/moe/prepare_moe_input.cu", + "csrc/quantization/gguf/gguf_kernel.cu", +] + +# Third-party source files +flashinfer_sources = [ + str(_FLASHINFER_REPO.source_dir / "csrc" / "norm.cu"), + str(_FLASHINFER_REPO.source_dir / "csrc" / "renorm.cu"), +] + +all_common_sources = common_sources + flashinfer_sources + +# Libraries to link. +# +# The cuda_free PPU SDK ships no libcuda/libcublas/libcublasLt; the sailified +# sources call the native spellings instead, so link their PPU counterparts: +# cudart -> hggcrt1 (libhggcrt1.so -> libhggcrt.13.0.so; there is no +# unversioned libhggcrt.so to satisfy a plain -lhggcrt) +# cublas -> acblas (PPU counterpart of cublas) +# cublasLt-> acblasLt +# The CUDA driver API (libcuda) is dropped: no csrc translation unit calls it. +# `library_paths()` from SAIL torch already contributes $PPU_SDK/lib, so no +# explicit library_dirs is needed. +libraries = ["c10", "hggcrt1", "hggc", "acblas", "acblasLt"] +extra_link_args = ["-Wl,-rpath,$ORIGIN/../../torch/lib"] + + +# ======================= Extension Modules ======================= # +def _make_common_ops(): + """common_ops for SM80/SM89.""" + nvcc_flags = sgl_kernel_cuda_flags + ["-use_fast_math"] + return CUDAExtension( + name="sgl_kernel.common_ops", + sources=staged_common_sources, + include_dirs=include_dirs, + extra_compile_args={ + "nvcc": nvcc_flags, + "cxx": ["-O3", "-std=c++17", abi_flag], + }, + libraries=libraries, + extra_link_args=extra_link_args, + py_limited_api=False, + ) + + +# ======================= Clone Third-Party Repositories ======================= # +def _clone_and_checkout(repo_path, repo_url, git_tag, git_shallow): + """Clone a git repository and checkout a specific tag/commit.""" + repo_path = Path(repo_path) + repo_path.parent.mkdir(parents=True, exist_ok=True) + if not repo_path.exists(): + clone_cmd = ["git", "clone"] + if git_shallow: + clone_cmd += ["--depth", "1"] + clone_cmd += [repo_url, str(repo_path)] + print(f"Cloning {repo_url} -> {repo_path}") + subprocess.check_call(clone_cmd) + subprocess.check_call(["git", "checkout", git_tag], cwd=repo_path) + + +if os.environ.get("SGL_KERNEL_SKIP_THIRD_PARTY", "0") != "1": + for _repo in ALL_REPOS: + _clone_and_checkout( + _repo.source_dir, + _repo.git_repository, + _repo.git_tag, + _repo.git_shallow, + ) + + +# ======================= Sailify Source Staging ======================= # +# The upstream sources (sglang aot + flashinfer) target CUDA; the cuda_free +# PPU SDK needs their hggc equivalents. Rather than modifying the upstream +# trees, every compiled source file -- plus every header they recursively +# #include -- is converted by sailify into a mirror tree under +# build/sailified/, and the extensions compile exclusively from that tree: +# +# build/sailified/.ppu_compat/ compat layer (generated) +# build/sailified/csrc/... aot sources + headers +# build/sailified/include/... aot headers +# build/sailified/flashinfer/csrc/... flashinfer sources + headers +# build/sailified/flashinfer/include/... flashinfer headers +# +# The staging tree is wiped and rebuilt on every invocation so no stale +# output survives an upstream or sailify change. + +sailify_staging_dir = root / "build" / "sailified" + +# Sailify toggle. +# +# SGL_KERNEL_USE_SAILIFY (default "1") enables the automatic cuda->hggc +# staging conversion described below; "0" skips staging and compiles the +# upstream sources directly, which requires a pre-sailified tree +# (root/.ppu_compat, see the skip branch). The legacy +# SGL_KERNEL_SKIP_SAILIFY variable is kept for backwards compatibility and +# takes precedence when explicitly set. +if "SGL_KERNEL_SKIP_SAILIFY" in os.environ: + skip_sailify = os.environ["SGL_KERNEL_SKIP_SAILIFY"] == "1" +else: + skip_sailify = os.environ.get("SGL_KERNEL_USE_SAILIFY", "1") != "1" + +# Targeted fixes applied to the *staged* copies after the generic sailify +# pass, for CUDA constructs the identifier-level mapping cannot express. +# The -U__HGGC_NO_HALF* flags in sgl_kernel_cuda_flags disable +# constructor-style half/bfloat16 conversions, so numeric casts must use the +# functional __float2half / __float2bfloat16 API instead. +_SAILIFY_PATCHES = { + "csrc/moe/moe_sum_reduce.cu": [ + ("__half2float(__half(", "__half2float(__float2half("), + ("__bfloat162float(__ppu_bfloat16(", "__bfloat162float(__float2bfloat16("), + ], + "csrc/grammar/apply_token_bitmask_inplace_cuda.cu": [ + ("-CUDART_INF_FP16", "__float2half(-INFINITY)"), + ("-CUDART_INF_BF16", "__float2bfloat16(-INFINITY)"), + ("__ppu_bfloat16(-INFINITY)", "__float2bfloat16(-INFINITY)"), + ], +} + + +def _sailify_stage(tree_roots, source_files): + """Convert *source_files* and their #include closure into the staging tree. + + Args: + tree_roots: {upstream_root: staged_subdir} -- each file under an + upstream root is written to + sailified_dir/staged_subdir/. + source_files: absolute paths of the .cu/.cc/.cpp files to convert. + + Returns: + List of staged paths corresponding 1:1 to *source_files*. + """ + try: + from sailify.sailify_python import ( + _discover_includes, + _ensure_ppu_compat, + preprocessor, + ) + except ImportError as exc: + raise RuntimeError( + "sailify is required for SAIL builds (pip install -e /path/to/sailify)" + ) from exc + + staging = str(sailify_staging_dir) + if sailify_staging_dir.exists(): + shutil.rmtree(sailify_staging_dir) + sailify_staging_dir.mkdir(parents=True) + + # Longest root first so nested trees match the most specific entry. + roots = sorted( + ((os.path.realpath(r), sub) for r, sub in tree_roots.items()), + key=lambda kv: -len(kv[0]), + ) + + def _staged_path(src_path): + """Map an upstream file to (staged_path, project_directory anchor). + + The anchor is the directory that preprocessor must receive as + project_directory so that output_directory + relpath(file, anchor) + equals staged_path. + """ + src_path = os.path.realpath(src_path) + for base, sub in roots: + if src_path.startswith(base + os.sep): + rel = os.path.relpath(src_path, base) + staged_rel = os.path.join(sub, rel) if sub else rel + return os.path.join(staging, staged_rel), ( + os.path.dirname(base) if sub else base + ) + return None + + # Directories used to resolve #include targets while walking the + # dependency closure (mirrors the upstream -I layout). + header_include_dirs = [] + for base, _sub in roots: + for name in ("include", "csrc"): + d = os.path.join(base, name) + if os.path.isdir(d) and d not in header_include_dirs: + header_include_dirs.append(d) + + # BFS over the compiled sources and their #include closure. Headers + # outside the managed trees (system / torch / actlize SDK headers) are + # resolved by the discovery walk but intentionally left unconverted. + visited = {os.path.realpath(f) for f in source_files} + pending = list(visited) + stats = {} + failures = [] + while pending: + src_path = pending.pop(0) + _discover_includes(src_path, header_include_dirs, visited, pending) + mapped = _staged_path(src_path) + if mapped is None: + continue # header outside the managed trees: used as-is + staged_path, anchor = mapped + result = preprocessor( + output_directory=staging, + filepath=src_path, + all_files=[], + stats=stats, + clean_ctx=None, + show_progress=False, + project_directory=anchor, + ) + if result.status != "ok": + failures.append(f"{src_path}: {result.status}") + elif not os.path.isfile(staged_path): + failures.append(f"{src_path}: staged output {staged_path} missing") + + if failures: + raise RuntimeError("sailify staging failed:\n " + "\n ".join(failures)) + + # Regenerate the compat layer inside the staging tree. + _ensure_ppu_compat(staging) + + # Apply targeted post-sailify patches to the staged copies only; the + # upstream trees are never touched. + for rel_path, replacements in _SAILIFY_PATCHES.items(): + staged = sailify_staging_dir / rel_path + if not staged.is_file(): + print(f"sailify: patch target missing (skipped): {rel_path}") + continue + text = staged.read_text() + for old, new in replacements: + text = text.replace(old, new) + staged.write_text(text) + + n_headers = max(len(stats.get("ppuified", [])) - len(source_files), 0) + print( + f"sailify: staged {len(source_files)} sources (+{n_headers} discovered " + f"headers) into {sailify_staging_dir}" + ) + + return [_staged_path(f)[0] for f in source_files] + + +if skip_sailify: + # Compile the upstream sources as-is. The target toolchain is not + # necessarily the cuda_free PPU SDK (this may be a plain CUDA build), so + # no fail-fast on .ppu_compat: if it exists (pre-generated for the PPU + # cuda_free toolchain) it is prepended to shadow the CUDA headers, and + # otherwise the upstream include layout is used unchanged. + print("WARNING: sailify disabled, compiling upstream sources directly") + staged_common_sources = [str(root / s) for s in common_sources] + flashinfer_sources + ppu_compat_dir = root / ".ppu_compat" + if ppu_compat_dir.is_dir(): + print(f"note: using existing compat layer {ppu_compat_dir}") + include_dirs = [str(ppu_compat_dir)] + base_include_dirs + else: + include_dirs = list(base_include_dirs) +else: + _staged = _sailify_stage( + { + root: "", # aot tree mirrors directly onto the staging root + _FLASHINFER_REPO.source_dir: "flashinfer", + }, + [str(root / s) for s in common_sources] + flashinfer_sources, + ) + staged_common_sources = _staged + # Staged directories shadow their upstream originals. .ppu_compat MUST + # stay first: SAIL torch injects its own (possibly older) `.ppu_compat` + # through torch.utils.cpp_extension.include_paths(), which lands after + # the user include_dirs. Both copies contain compatible_wrapper.h, and + # SAIL torch also passes `-include compatible_wrapper.h` on the hgcc + # command line -- the compiler resolves that through -I order, so a + # stale compat layer shadowing ours breaks the build with e.g. + # "no template named 'maximum' in namespace 'hggc'". + include_dirs = [ + str(sailify_staging_dir / ".ppu_compat"), + str(sailify_staging_dir / "include"), + str(sailify_staging_dir / "csrc"), + str(sailify_staging_dir / "flashinfer" / "include"), + str(sailify_staging_dir / "flashinfer" / "csrc"), + ] + base_include_dirs + + # ======================= Post-Build Cleanup ======================= # + # The build itself consumes the compat layer from + # build/sailified/.ppu_compat (first -I entry above), but tooling on the + # SAIL torch side may additionally drop a .ppu_compat directory into the + # aot tree (it shows up on the hgcc -I line). It is not part of the + # upstream sources, so remove it after every compilation / packaging step + # has finished. In skip-sailify mode root/.ppu_compat is an optional + # user-provided compat layer and must NOT be removed either (hence no + # registration there). + def _cleanup_upstream_ppu_compat(): + upstream_compat = root / ".ppu_compat" + if upstream_compat.is_dir(): + shutil.rmtree(upstream_compat, ignore_errors=True) + print(f"setup_sail: removed {upstream_compat} (post-build cleanup)") + + atexit.register(_cleanup_upstream_ppu_compat) + + +# ======================= Build Extension Modules List ======================= # +ext_modules = [ + _make_common_ops(), +] + + +# ======================= Custom Build Extension ======================= # +class _CustomBuildExt(BuildExtension): + """Custom build extension with ninja support.""" + + pass + + +# ======================= Package Discovery ======================= # +_triton_kernels_root = _TRITON_REPO.source_dir / "python" / "triton_kernels" + +_packages = find_namespace_packages(where="python") +_package_dir = {"": "python"} + +# Discover triton_kernels packages (may not exist before first clone) +if _triton_kernels_root.exists(): + _triton_pkgs = find_namespace_packages( + where=str(_triton_kernels_root), + exclude=["tests", "tests.*"], + ) +else: + _triton_pkgs = ["triton_kernels"] + +for pkg in _triton_pkgs: + _package_dir[pkg] = os.path.relpath( + _triton_kernels_root / pkg.replace(".", os.sep), root + ) +_packages += _triton_pkgs + + +# ======================= Setup ======================= # +setup( + name="sglang-kernel", + version=_get_version(), + packages=_packages, + package_dir=_package_dir, + ext_modules=ext_modules, + cmdclass={"build_ext": _CustomBuildExt.with_options(use_ninja=True)}, + options={"bdist_wheel": {"py_limited_api": "cp310"}}, +) diff --git a/python/sglang/kernels/jit/utils/arch.py b/python/sglang/kernels/jit/utils/arch.py index 7091d1790b..53de6d0d32 100644 --- a/python/sglang/kernels/jit/utils/arch.py +++ b/python/sglang/kernels/jit/utils/arch.py @@ -17,6 +17,7 @@ from sglang.kernels.jit.utils.common import ( cache_once, is_hip_runtime, is_musa_runtime, + is_sail_runtime, ) from sglang.srt.utils.common import is_cuda @@ -70,6 +71,14 @@ def _jit_cuda_version() -> tuple[int, ...]: return get_cuda_version() +def _sail_arch_suffix(major: int, minor: int) -> str: + """SAIL devices below the SM89 capability require the arch-specific target + variant for JIT compilation (the ``"a"`` suffix); SM89+ SAIL devices stay + unsuffixed like HIP/MUSA. + """ + return "a" if (major <= 8 and minor < 9) else "" + + def _cuda_arch_suffix(major: int, minor: int) -> str: """Mirror FlashInfer's `_normalize_cuda_arch`: 9.x/10.x+ -> "a"; 12.0 -> "f" and 12.x (x>0) -> "a" (SM120/SM121 need separate cubins to avoid @@ -104,11 +113,13 @@ def _init_jit_cuda_arch_once(): # JIT builds target the exact local GPU, so the arch-specific target is # always correct on Hopper+ and unlocks arch-only instructions (redux.f32). # HIP/MUSA capability numbers aren't CUDA SM versions and stay unsuffixed. - suffix = ( - "" - if (is_hip_runtime() or is_musa_runtime()) - else _cuda_arch_suffix(major, minor) - ) + if is_hip_runtime() or is_musa_runtime(): + suffix = "" + elif is_sail_runtime(): + suffix = _sail_arch_suffix(major, minor) + else: + suffix = _cuda_arch_suffix(major, minor) + _CUDA_ARCH = ArchInfo(major, minor, suffix) diff --git a/python/sglang/kernels/jit/utils/common.py b/python/sglang/kernels/jit/utils/common.py index e78317c971..298ba0a21c 100644 --- a/python/sglang/kernels/jit/utils/common.py +++ b/python/sglang/kernels/jit/utils/common.py @@ -72,6 +72,13 @@ def is_musa_runtime() -> bool: return getattr(torch.version, "musa", None) is not None +@cache_once +def is_sail_runtime() -> bool: + # T-HEAD SAIL device names carry the "ZW" tag; keep the check aligned with + # sglang.srt.utils.is_sail so all layers agree on what "running on SAIL" means. + return bool(torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name()) + + _REGISTERED_CLASSES: Dict[type, type] = {} diff --git a/python/sglang/kernels/jit/utils/compile/__init__.py b/python/sglang/kernels/jit/utils/compile/__init__.py index 14e7dfb5d8..7949b3690d 100644 --- a/python/sglang/kernels/jit/utils/compile/__init__.py +++ b/python/sglang/kernels/jit/utils/compile/__init__.py @@ -12,6 +12,7 @@ Modules, in dependency order (there are no cycles):: toolchain compilers, tvm-ffi locations, platform base flags ninja generating and running build.ninja, reading its depfiles cache build_key / deps_key, cache layout, publication + sailify CUDA -> PPU source conversion for hgcc builds loader load_jit parallel parallel_compile: several builds at once """ diff --git a/python/sglang/kernels/jit/utils/compile/cache.py b/python/sglang/kernels/jit/utils/compile/cache.py index deba51e4c3..400541e23c 100644 --- a/python/sglang/kernels/jit/utils/compile/cache.py +++ b/python/sglang/kernels/jit/utils/compile/cache.py @@ -56,7 +56,12 @@ from typing import Dict, Iterable, List, Optional, Sequence, Tuple import msgspec from sglang.kernels.jit.utils.arch import get_jit_cuda_arch -from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime, is_musa_runtime +from sglang.kernels.jit.utils.common import ( + cache_once, + is_hip_runtime, + is_musa_runtime, + is_sail_runtime, +) from sglang.kernels.jit.utils.compile import toolchain from sglang.kernels.jit.utils.compile.paths import KERNEL_PATH from sglang.kernels.jit.utils.compile.spec import BuildSpec @@ -214,6 +219,10 @@ def _target_tag() -> str: ``(major, minor)`` capability: the latter maps gfx940/gfx941/gfx942 onto a single ``9.4``, which are three different compile targets. """ + if is_sail_runtime(): + arch = envs.SGLANG_SAIL_GPU_ARCH.get() + safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in arch) + return f"sail_{safe}" if is_hip_runtime(): return toolchain.gpu_arch_name().split(":")[0] or "unknown" arch = get_jit_cuda_arch() @@ -232,7 +241,14 @@ def _environment_fingerprint() -> str: different host compiler means different system headers and different host codegen for otherwise identical inputs. """ - if is_hip_runtime(): + if is_sail_runtime(): + # Imported lazily: sailify imports this module for file digests, so a + # top-level import would be circular. + from sglang.kernels.jit.utils.compile.sailify import sailify_version + + arch = envs.SGLANG_SAIL_GPU_ARCH.get() + target = f"hgcc:{arch}:sailify-{sailify_version()}" + elif is_hip_runtime(): target = f"hip:{toolchain.gpu_arch_name()}" else: arch = get_jit_cuda_arch() diff --git a/python/sglang/kernels/jit/utils/compile/loader.py b/python/sglang/kernels/jit/utils/compile/loader.py index 7dffa00b47..890851d1f1 100644 --- a/python/sglang/kernels/jit/utils/compile/loader.py +++ b/python/sglang/kernels/jit/utils/compile/loader.py @@ -14,13 +14,14 @@ from typing import TYPE_CHECKING, List, Tuple import torch from sglang.kernels.jit.utils.arch import get_default_target_flags -from sglang.kernels.jit.utils.common import is_hip_runtime -from sglang.kernels.jit.utils.compile import cache, ninja +from sglang.kernels.jit.utils.common import is_hip_runtime, is_sail_runtime +from sglang.kernels.jit.utils.compile import cache, ninja, toolchain from sglang.kernels.jit.utils.compile.paths import ( DEFAULT_CFLAGS, DEFAULT_INCLUDE, DEFAULT_LDFLAGS, ) +from sglang.kernels.jit.utils.compile.sailify import convert_cuda_sources from sglang.kernels.jit.utils.compile.spec import BuildSpec, resolve_sources from sglang.kernels.jit.utils.deps import REGISTERED_DEPENDENCIES from sglang.srt.environ import envs @@ -95,11 +96,21 @@ def load_jit( ) includes = list(DEFAULT_INCLUDE) + (extra_include_paths or []) + if is_sail_runtime(): + includes = toolchain.base_include_paths() + includes for dep in sorted(set(extra_dependencies or [])): if dep not in REGISTERED_DEPENDENCIES: raise ValueError(f"Dependency {dep} is not registered.") includes += REGISTERED_DEPENDENCIES[dep]() + if is_sail_runtime() and cuda_files: + resolved_cuda = list(resolve_sources(cuda_files)) + converted, sailify_flags = convert_cuda_sources(resolved_cuda, includes) + cuda_files = converted # absolute paths pass through resolve_sources below + extra_cuda_cflags = ( + _filter_hgcc_cuda_flags(extra_cuda_cflags or []) + sailify_flags + ) + module_args = tuple(str(arg) for arg in args) spec = BuildSpec( module_args=module_args, @@ -202,6 +213,37 @@ def _find_prebuilt(*, spec: BuildSpec, scope: pathlib.Path) -> pathlib.Path | No return cache.find_prebuilt(scope=scope, module_name=spec.module_name) +# Verified against hgcc 2.2: it is an nvcc-style driver and accepts +# -Xcompiler, --use_fast_math, --expt-relaxed-constexpr and +# --expt-extended-lambda; the genuinely unsupported options are the +# nvcc-specific code-generation and ptxas ones below. +_HGCC_DROP_WITH_ARG = frozenset({"-Xptxas"}) +_HGCC_DROP_PREFIX = ("-gencode", "--generate-code") + + +def _filter_hgcc_cuda_flags(flags: List[str]) -> List[str]: + """Drop nvcc-only flags hgcc would not understand; keep everything else.""" + kept: List[str] = [] + dropped: List[str] = [] + skip_next = False + for flag in flags: + if skip_next: + skip_next = False + dropped.append(flag) + continue + if flag in _HGCC_DROP_WITH_ARG: + skip_next = True + dropped.append(flag) + continue + if flag.startswith(_HGCC_DROP_PREFIX): + dropped.append(flag) + continue + kept.append(flag) + if dropped: + logger.warning("Dropping nvcc-only flags hgcc does not accept: %s", dropped) + return kept + + @contextlib.contextmanager def _build_lock(scope: pathlib.Path): """Serialize builds of one module variant across processes. diff --git a/python/sglang/kernels/jit/utils/compile/sailify.py b/python/sglang/kernels/jit/utils/compile/sailify.py new file mode 100644 index 0000000000..8aa2721278 --- /dev/null +++ b/python/sglang/kernels/jit/utils/compile/sailify.py @@ -0,0 +1,237 @@ +"""Convert CUDA sources with sailify before they are handed to hgcc. + +hgcc cannot read CUDA: identifiers, API names and header paths first have to +be rewritten by sailify. Two properties of the converter shape everything in +this module: + +* ``sailify_extra_files_recursive`` converts **in place** — its per-file + output path is ``join(output_directory, relpath(input, output_directory))``, + which normalizes back onto the input itself; only the generated + ``.ppu_compat/`` headers actually land in ``output_directory``. The kernel + sources in the tree must never be rewritten, so conversion runs on a + mirror-copy of the sources, made under the JIT cache root. +* Conversion also rewrites every transitively ``#include``d header it can + discover, so the mirror has to cover the whole include closure, and the + digest that keys the mirror has to cover it too — otherwise a header edit + would be invisible to both the mirror and, transitively, the build cache. + +The mirror preserves each file's absolute path relative to ``/``, so relative +includes keep resolving inside it exactly as they did in the original tree. +""" + +from __future__ import annotations + +import hashlib +import logging +import os +import pathlib +import re +import shutil +import uuid +from typing import Dict, List, Optional, Set, Tuple + +from sglang.kernels.jit.utils.common import cache_once +from sglang.srt.environ import envs + +logger = logging.getLogger(__name__) + +# Mirrors sailify's `_RE_INCLUDE` / `DEFAULT_EXTENSIONS`: the closure below +# must contain exactly the files sailify itself would discover and convert. +_INCLUDE_RE = re.compile(r'^[ \t]*#[ \t]*include[ \t]+[<"]([^>"]+)[>"]', re.MULTILINE) +_SOURCE_EXTENSIONS = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp", ".inl") + +_KEY_HEX_LEN = 16 + + +@cache_once +def sailify_version() -> str: + """Installed sailify version, or 'unknown' (never raises).""" + try: + from importlib.metadata import version as dist_version + + return dist_version("sailify") + except Exception: + pass + try: + from sailify.version import __version__ + + return str(__version__) + except Exception: + return "unknown" + + +@cache_once +def _ppu_sdk_version() -> str: + """PPU SDK version as sailify detects it, or 'unknown' (never raises). + + The SDK version is baked into the generated ``compatible_wrapper.h``, so + it is part of the mirror digest. + """ + try: + from sailify.ppu_sdk_version import ( + detect_ppu_sdk_version, + format_version_string, + ) + + return format_version_string(detect_ppu_sdk_version()) + except Exception: + return "unknown" + + +def _sailify_root() -> pathlib.Path: + configured = envs.SGLANG_JIT_CACHE_DIR.get() or "~/.cache/sglang/jit" + return pathlib.Path(configured).expanduser() / "sailified" + + +def _mirror_path(root: pathlib.Path, source: str) -> pathlib.Path: + """The mirrored location of an absolute *source* path under *root*.""" + path = pathlib.Path(source) + return root / path.relative_to(path.anchor) + + +def _discover_closure( + cuda_files: List[str], include_dirs: List[str] +) -> Tuple[Set[str], Dict[str, Optional[str]]]: + """Every file sailify would convert, with the base each resolved against. + + Replicates sailify's own discovery: an include is tried against the + including file's directory first, then each include dir in order; the + first candidate that exists on disk wins, whether or not it is a source + extension. The base is ``None`` for includes resolved against the + including file's directory (the mirror reproduces those relative + relationships on its own) and the include dir otherwise (whose mirrored + location has to reach the compile line for the converted header to win + over the original). + """ + visited: Set[str] = set() + bases: Dict[str, Optional[str]] = {} + queue: List[str] = [] + for filepath in cuda_files: + filepath = os.path.abspath(filepath) + if filepath not in visited: + visited.add(filepath) + bases[filepath] = None + queue.append(filepath) + + while queue: + filepath = queue.pop(0) + try: + source = pathlib.Path(filepath).read_text(errors="replace") + except OSError: + continue + file_dir = os.path.dirname(filepath) + for match in _INCLUDE_RE.finditer(source): + inc = match.group(1) + candidates = [(os.path.join(file_dir, inc), None)] + [ + (os.path.join(inc_dir, inc), os.path.abspath(inc_dir)) + for inc_dir in include_dirs + ] + for candidate, base in candidates: + candidate = os.path.abspath(candidate) + if candidate in visited: + break + if os.path.isfile(candidate): + if os.path.splitext(candidate)[1] in _SOURCE_EXTENSIONS: + visited.add(candidate) + bases[candidate] = base + queue.append(candidate) + break + return visited, bases + + +def _mirror_digest(closure: Set[str], include_dirs: List[str]) -> str: + # Imported lazily: cache imports this module for the environment + # fingerprint, so a top-level import would be circular. + from sglang.kernels.jit.utils.compile import cache + + digest = hashlib.sha256() + for part in (sailify_version(), _ppu_sdk_version(), tuple(include_dirs)): + digest.update(repr(part).encode()) + digest.update(b"\0") + for path in sorted(closure): + digest.update(path.encode()) + digest.update(b"\0") + digest.update((cache._file_digest(pathlib.Path(path)) or "").encode()) + digest.update(b"\0") + return digest.hexdigest()[:_KEY_HEX_LEN] + + +def convert_cuda_sources( + cuda_files: List[str], include_dirs: List[str] +) -> Tuple[List[str], List[str]]: + """Convert .cu sources with sailify into a content-addressed dir. + + Returns (converted_cuda_files, extra_cuda_cflags) where extra flags add + the mirrored include dirs, the generated .ppu_compat include dir, and a + force-include of compatible_wrapper.h. + """ + try: + from sailify.sailify_python import sailify_extra_files_recursive + except ImportError as error: + raise RuntimeError( + "JIT builds on SAIL require the sailify converter, which is not " + "installed. Install it with `pip install -e cuda_free/sailify` from " + "the sglang repository." + ) from error + + closure, bases = _discover_closure(cuda_files, include_dirs) + outdir = _sailify_root() / _mirror_digest(closure, include_dirs) + converted = [str(_mirror_path(outdir, os.path.abspath(f))) for f in cuda_files] + + compat_header = outdir / ".ppu_compat" / "compatible_wrapper.h" + if not ( + outdir.is_dir() + and compat_header.is_file() + and all(pathlib.Path(path).is_file() for path in converted) + ): + tmp = outdir.parent / f"{outdir.name}.tmp-{uuid.uuid4().hex}" + try: + mirror: Dict[str, str] = {} + for source in sorted(closure): + target = _mirror_path(tmp, source) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, target) + mirror[source] = str(target) + sailify_extra_files_recursive( + output_directory=str(tmp), + extra_files=[mirror[source] for source in sorted(closure)], + header_include_dirs=[], + ) + outdir.parent.mkdir(parents=True, exist_ok=True) + try: + os.rename(tmp, outdir) + except OSError: + # A concurrent process published the identical content first. + if not outdir.is_dir(): + raise + except Exception as error: + raise RuntimeError( + f"sailify failed to convert CUDA sources for hgcc: {error}" + ) from error + finally: + shutil.rmtree(tmp, ignore_errors=True) + + missing = [path for path in converted if not pathlib.Path(path).is_file()] + if missing: + raise RuntimeError( + "sailify did not produce the expected converted sources: " + + ", ".join(missing) + ) + for source, path in zip(cuda_files, converted): + src_ext = os.path.splitext(source)[1] + out_ext = os.path.splitext(path)[1] + assert src_ext == out_ext, ( + f"sailify changed the extension of {source}: converted to {path}" + ) + + mirrored_include_dirs = [ + f"-I{_mirror_path(outdir, base)}" + for base in dict.fromkeys(bases.values()) + if base is not None + ] + flags = mirrored_include_dirs + [ + f"-I{outdir / '.ppu_compat'}", + "-include", + "compatible_wrapper.h", + ] + return converted, flags diff --git a/python/sglang/kernels/jit/utils/compile/toolchain.py b/python/sglang/kernels/jit/utils/compile/toolchain.py index 5c8752aa0b..ffa3b65997 100644 --- a/python/sglang/kernels/jit/utils/compile/toolchain.py +++ b/python/sglang/kernels/jit/utils/compile/toolchain.py @@ -22,10 +22,22 @@ from typing import List, Tuple import torch from sglang.kernels.jit.utils.arch import get_jit_cuda_arch -from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime +from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime, is_sail_runtime +from sglang.srt.environ import envs logger = logging.getLogger(__name__) +_SAIL_GPU_ARCHS = ( + "native", + "all", + "all-ppu", + "all-vm", + "ppu_10", + "ppu_15", + "vm_10", + "vm_15", +) + @cache_once def cuda_home() -> str: @@ -64,16 +76,59 @@ def rocm_home() -> str: @cache_once def device_compiler_path() -> str: - """The nvcc/hipcc that JIT builds actually invoke. + """The nvcc/hipcc/hgcc that JIT builds actually invoke. Resolved the same way tvm-ffi resolves it, so the binary the cache fingerprints is the binary that does the compiling. """ + if is_sail_runtime(): + return hgcc_path() if is_hip_runtime(): return os.path.join(rocm_home(), "bin", "hipcc") return os.path.join(cuda_home(), "bin", "nvcc") +@cache_once +def hgcc_path() -> str: + """The hgcc compiler, from PATH or the PPU SDK install.""" + searched = ["hgcc on PATH"] + on_path = shutil.which("hgcc") + if on_path is not None: + return on_path + for root in ( + os.environ.get("PPU_SDK"), + os.environ.get("PPU_HOME"), + "/usr/local/PPU_SDK", + ): + if root is None: + continue + candidate = os.path.join(root, "bin", "hgcc") + searched.append(candidate) + if os.path.isfile(candidate): + return candidate + raise RuntimeError( + "JIT builds on SAIL require the hgcc compiler, which was not found. Searched: " + + ", ".join(searched) + ) + + +@cache_once +def ppu_sdk_home() -> str: + """The PPU SDK root providing the hggc libraries to link against. + + Two layers live in ``lib/`` and they are not interchangeable: + * ``libhggcrt1`` (SONAME ``libhggcrt.13.0.so``) is the *runtime*, the + counterpart of cudart. It alone exports the ``hggc*`` Runtime-API + symbols and the ``__hggcRegister*`` entry points that hgcc's generated + fat-binary registration code calls from every translation unit with + device code. + * ``libhggc`` is the *driver*, the counterpart of libcuda. It exports the + ``hg*`` Driver-API symbols (e.g. ``hgPointerGetAttribute``) and none of + the ``hggc*`` ones. + """ + return os.environ.get("PPU_SDK") or "/usr/local/PPU_SDK" + + @cache_once def host_compiler_path() -> str: """The C++ compiler host code is handed to. @@ -129,6 +184,14 @@ def target_flags() -> List[str]: the compiler driver to probe: the value is part of the cache key, so it has to be decided here and not rediscovered at build time. """ + if is_sail_runtime(): + arch = envs.SGLANG_SAIL_GPU_ARCH.get() + if arch not in _SAIL_GPU_ARCHS: + raise ValueError( + f"Invalid SGLANG_SAIL_GPU_ARCH={arch!r}; expected one of " + f"{', '.join(_SAIL_GPU_ARCHS)}" + ) + return [f"--gpu-architecture={arch}"] if is_hip_runtime(): return [f"--offload-arch={gpu_arch_name()}"] arch = get_jit_cuda_arch() @@ -170,6 +233,12 @@ def base_link_flags(*, with_device: bool) -> List[str]: flags = ["-shared", f"-L{lib_dir}", f"-l{lib_name}"] if not with_device: return flags + if is_sail_runtime(): + return flags + [ + f"-L{ppu_sdk_home()}/lib", + "-lhggcrt1", + "-lhggc", + ] if is_hip_runtime(): return flags + [f"-L{rocm_home()}/lib", "-lamdhip64"] return flags + [f"-L{cuda_home()}/lib64", "-lcudart"] diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py index 2383c0196e..ae50822071 100644 --- a/python/sglang/srt/environ.py +++ b/python/sglang/srt/environ.py @@ -1331,6 +1331,12 @@ class Envs: # Drop the GB/s and TFLOPS columns from the benchmark marker's table. SGLANG_JIT_BENCHMARK_DISABLE_LOG_BANDWIDTH = EnvBool(False) SGLANG_JIT_BENCHMARK_DISABLE_LOG_FLOPS = EnvBool(False) + # The hgcc --gpu-architecture target used by JIT builds on SAIL (hgcc + # cannot read CUDA sources, so they are converted by sailify first). + # One of: native, all, all-ppu, + # all-vm, ppu_10, ppu_15, vm_10, vm_15. "native" builds for the local + # device only, matching how the nvcc path pins -gencode to this GPU. + SGLANG_SAIL_GPU_ARCH = EnvStr("native") # =================================================================== # Expert-parallel dispatch and MoE execution diff --git a/python/sglang/srt/platforms/__init__.py b/python/sglang/srt/platforms/__init__.py index 07d75a42c8..242ce1fc60 100644 --- a/python/sglang/srt/platforms/__init__.py +++ b/python/sglang/srt/platforms/__init__.py @@ -25,6 +25,7 @@ from sglang.srt.platforms.mps import MpsSRTPlatform from sglang.srt.platforms.musa import MusaSRTPlatform from sglang.srt.platforms.npu import NPUSRTPlatform from sglang.srt.platforms.rocm import RocmSRTPlatform +from sglang.srt.platforms.sail import SailSRTPlatform from sglang.srt.platforms.xpu import XpuSRTPlatform from sglang.srt.plugins import PLATFORM_PLUGINS_GROUP, load_plugins_by_group @@ -41,6 +42,10 @@ def _is_rocm_available() -> bool: return bool(torch.cuda.is_available() and torch.version.hip is not None) +def _is_sail_available() -> bool: + return bool(torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name()) + + def _is_cpu_available() -> bool: return os.getenv("SGLANG_USE_CPU_ENGINE", "0") == "1" @@ -86,6 +91,8 @@ def _resolve_platform() -> SRTPlatform: - 0 activated + SGLANG_USE_CPU_ENGINE=1 → fallback CpuSRTPlatform (checked first; an explicit opt-in wins over CUDA/ROCm availability, so developers on GPU hosts can intentionally exercise the CPU path) + - 0 activated + SAIL available → fallback SailSRTPlatform + (checked before CUDA; SAIL also reports torch.cuda.is_available()) - 0 activated + CUDA available → fallback CudaSRTPlatform - 0 activated + NPU available → fallback NPUSRTPlatform - 0 activated + ROCm available → fallback RocmSRTPlatform @@ -146,6 +153,11 @@ def _resolve_platform() -> SRTPlatform: if _is_cpu_available(): logger.debug("SGLANG_USE_CPU_ENGINE=1. Using CPU SRTPlatform defaults.") return CpuSRTPlatform() + if _is_sail_available(): + logger.debug( + "No platform plugin detected. Using SAIL SRTPlatform defaults." + ) + return SailSRTPlatform() if _is_cuda_available(): logger.debug( "No platform plugin detected. Using CUDA SRTPlatform defaults." diff --git a/python/sglang/srt/platforms/device_mixin.py b/python/sglang/srt/platforms/device_mixin.py index 3d1cde395c..09ace011cf 100644 --- a/python/sglang/srt/platforms/device_mixin.py +++ b/python/sglang/srt/platforms/device_mixin.py @@ -53,6 +53,7 @@ class PlatformEnum(enum.Enum): NPU = enum.auto() TPU = enum.auto() MPS = enum.auto() + SAIL = enum.auto() OOT = enum.auto() # Out-of-tree (external plugin) UNSPECIFIED = enum.auto() @@ -135,12 +136,16 @@ class DeviceMixin: def is_mps(self) -> bool: return self._enum == PlatformEnum.MPS + def is_sail(self) -> bool: + return self._enum == PlatformEnum.SAIL + def is_cuda_alike(self) -> bool: - """True for CUDA, ROCm, or MUSA (all expose CUDA-like APIs).""" + """True for CUDA, ROCm, MUSA, or SAIL (all expose CUDA-like APIs).""" return self._enum in ( PlatformEnum.CUDA, PlatformEnum.ROCM, PlatformEnum.MUSA, + PlatformEnum.SAIL, ) def is_out_of_tree(self) -> bool: diff --git a/python/sglang/srt/platforms/sail.py b/python/sglang/srt/platforms/sail.py new file mode 100644 index 0000000000..882a97f163 --- /dev/null +++ b/python/sglang/srt/platforms/sail.py @@ -0,0 +1,29 @@ +"""SAIL device operations for the SRT platform layer. + +T-HEAD SAIL exposes a CUDA-compatible API through its torch backend, so +``SailDeviceMixin`` inherits all device ops from ``CudaDeviceMixin`` and +only overrides identity (``_enum``, ``device_name``). +""" + +from sglang.srt.platforms.cuda import CudaDeviceMixin +from sglang.srt.platforms.device_mixin import PlatformEnum +from sglang.srt.platforms.interface import PlatformCapabilities, SRTPlatform + + +class SailDeviceMixin(CudaDeviceMixin): + """SAIL device ops — identical surface to CUDA via T-HEAD's torch backend.""" + + _enum: PlatformEnum = PlatformEnum.SAIL + device_name: str = "sail" + # device_type stays "cuda" — torch.device("cuda") is the only valid + # device-type string for SAIL devices in PyTorch. + + +class SailSRTPlatform(SailDeviceMixin, SRTPlatform): + """Default in-tree T-HEAD SAIL SRT platform.""" + + capabilities = PlatformCapabilities( + supports_triton=True, + graph_capture=True, + piecewise_graph=True, + ) diff --git a/python/sglang/srt/speculative/eagle_worker_v2.py b/python/sglang/srt/speculative/eagle_worker_v2.py index dc73ee46d6..f1d5cea6f8 100644 --- a/python/sglang/srt/speculative/eagle_worker_v2.py +++ b/python/sglang/srt/speculative/eagle_worker_v2.py @@ -407,8 +407,6 @@ class EagleDraftWorker(EagleDraftWorkerBase): def _configure_qsa_mtp_index_share(self) -> None: """Reuse the draft-extend QSA selection across the MTP decode steps; chain speculation only: with topk > 1 decode rows are not request-major.""" - from sglang.srt.layers.attention.qsa.qsa_indexer import QSAIndexer - hf_config = self.draft_runner.model_config.hf_config if ( not _qsa_index_share_requested(hf_config) @@ -426,6 +424,8 @@ class EagleDraftWorker(EagleDraftWorkerBase): "speculative decoding" ) return + from sglang.srt.layers.attention.qsa.qsa_indexer import QSAIndexer + layer_ids = sorted( { module.layer_id diff --git a/python/sglang/srt/utils/common.py b/python/sglang/srt/utils/common.py index c84312cceb..d980bc8c1f 100644 --- a/python/sglang/srt/utils/common.py +++ b/python/sglang/srt/utils/common.py @@ -161,7 +161,7 @@ def is_cuda(): @lru_cache(maxsize=1) def is_cuda_alike(): - return is_cuda() or is_hip() + return is_cuda() or is_hip() or is_sail() @lru_cache(maxsize=1) @@ -239,6 +239,11 @@ def is_mps() -> bool: return hasattr(torch, "mps") and torch.mps.is_available() +@lru_cache(maxsize=1) +def is_sail() -> bool: + return torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name() + + def is_float4_e2m1fn_x2(dtype) -> bool: """Check if dtype is float4_e2m1fn_x2 and CUDA is available.""" target_dtype = getattr(torch, "float4_e2m1fn_x2", None) diff --git a/scripts/ci/ppu/build_and_test.sh b/scripts/ci/ppu/build_and_test.sh new file mode 100755 index 0000000000..ceed9c548a --- /dev/null +++ b/scripts/ci/ppu/build_and_test.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +set -euo pipefail + +phase=${1:?Usage: build_and_test.sh build|test} +case "$phase" in + build|test) ;; + *) printf 'Unknown phase: %s\n' "$phase" >&2; exit 2 ;; +esac +: "${PPU_CI_ARTIFACT_DIR:?}" +: "${PPU_CI_WHEEL_DIR:?}" +: "${PPU_CI_SOURCE_SHA:?}" +mkdir -p "$PPU_CI_ARTIFACT_DIR" +artifacts=$(realpath "$PPU_CI_ARTIFACT_DIR") +wheel_dir=$(realpath "$PPU_CI_WHEEL_DIR") +exec > >(tee "$artifacts/$phase.log") 2>&1 + +repo=$(realpath "$(dirname "${BASH_SOURCE[0]}")/../../..") +checker="$repo/scripts/ci/ppu/check_dependencies.py" +unset PYTHONPATH PYTHONHOME VIRTUAL_ENV +export PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1 SGLANG_TEST_MAX_RETRY=0 SGLANG_IS_IN_CI=1 + +verify_wheels() { + if ! (cd "$wheel_dir" && sha256sum source-sha.txt ./*.whl ./runtime-deps/*.whl | cmp -s SHA256SUMS -); then + printf 'Wheel manifest does not match the complete wheel inventory\n' >&2 + return 1 + fi +} + +if [[ "$phase" == build ]]; then + if [[ "$(git -C "$repo" rev-parse HEAD)" != "$PPU_CI_SOURCE_SHA" ]]; then + printf 'Source checkout does not match PPU_CI_SOURCE_SHA\n' >&2 + exit 2 + fi + if [[ -n "$(git -C "$repo" status --porcelain --ignored)" ]]; then + printf 'Source checkout must be clean, including untracked and ignored files\n' >&2 + exit 2 + fi + : "${PPU_SDK:?}" + if compgen -G "$wheel_dir/*.whl" >/dev/null; then + printf 'Build wheel directory must be empty: %s\n' "$wheel_dir" >&2 + exit 2 + fi + sdk_root=$(realpath "$PPU_SDK") + set +u + # shellcheck source=/dev/null + source "$sdk_root/envsetup.sh" ppu + set -u + export PPU_SDK="$sdk_root" PPU_HOME="$sdk_root" + export CUDA_HOME="$sdk_root" CUDA_PATH="$sdk_root" + export PATH="$sdk_root/bin:$PATH" + export LD_LIBRARY_PATH="$sdk_root/lib:${LD_LIBRARY_PATH:-}" + export LIBRARY_PATH="$sdk_root/lib:${LIBRARY_PATH:-}" + unset TORCH_CUDA_ARCH_LIST SGL_KERNEL_SKIP_SAILIFY SGL_KERNEL_SKIP_THIRD_PARTY + export PYTORCH_SAIL_ARCH="${PYTORCH_SAIL_ARCH:-ppu_10;ppu_15}" + export SGL_KERNEL_USE_SAILIFY=1 + export MAX_JOBS="${MAX_JOBS:-8}" SGL_KERNEL_COMPILE_THREADS="${SGL_KERNEL_COMPILE_THREADS:-8}" + + python3 - <<'PY' +import torch +from torch.utils.cpp_extension import _get_cuda_arch_flags + +assert getattr(torch.version, "sail", None), "A cuda-free SAIL Torch build is required for compilation" +flags = _get_cuda_arch_flags() +assert any(flag.startswith("--gpu-architecture=ppu_") for flag in flags), flags +assert not any("gencode" in flag for flag in flags), flags +print("Build Torch:", torch.__version__, "SAIL:", torch.version.sail, "Arch flags:", flags) +PY + hgcc --version + python3 -m pip install --index-url https://pypi.org/simple \ + 'setuptools>=75' 'setuptools-scm>=8' 'setuptools-rust>=1.10' wheel build ninja + mkdir -p "$wheel_dir/runtime-deps" + python3 -m pip wheel --no-deps --no-build-isolation \ + --wheel-dir "$wheel_dir/runtime-deps" \ + git+https://github.com/t-head/sailify.git@f401ecae76d7b4991d44920bde9edaac7e655fd8 + python3 -m pip install --no-deps --force-reinstall "$wheel_dir/runtime-deps/"*.whl + requirements=$(python3 "$checker" requirements) + mapfile -t eval_requirements <<< "$requirements" + python3 -m pip wheel --index-url https://pypi.org/simple --no-deps --no-build-isolation \ + --wheel-dir "$wheel_dir/runtime-deps" "${eval_requirements[@]}" + python3 "$checker" snapshot "$artifacts/build-dependencies.json" + + work=$(mktemp -d) + mkdir "$work/source" + git -C "$repo" archive "$PPU_CI_SOURCE_SHA" | tar -C "$work/source" -xf - + cp "$work/source/python/pyproject_other.toml" "$work/source/python/pyproject.toml" + # This lane validates text inference, not the optional multimodal Rust extension. + export SGLANG_BUILD_RUST_EXTS=none + python3 -m build --wheel --no-isolation --outdir "$wheel_dir" "$work/source/python" + cd "$work/source/python/sglang/kernels/aot" + cp pyproject_sail.toml pyproject.toml + python3 setup_sail.py bdist_wheel --dist-dir "$wheel_dir" + cd "$wheel_dir" + printf '%s\n' "$PPU_CI_SOURCE_SHA" > source-sha.txt + sha256sum source-sha.txt ./*.whl ./runtime-deps/*.whl > SHA256SUMS + exit 0 +fi + +verify_wheels +if [[ "$(<"$wheel_dir/source-sha.txt")" != "$PPU_CI_SOURCE_SHA" ]]; then + printf 'Wheel source revision does not match PPU_CI_SOURCE_SHA\n' >&2 + exit 2 +fi +: "${PPU_CI_TARGET_MODEL_PATH:?}" +: "${PPU_CI_EAGLE3_MODEL_PATH:?}" +: "${PPU_CI_DFLASH_MODEL_PATH:?}" +: "${PPU_CI_EVAL_CACHE:?}" +export HOME +HOME=$(mktemp -d) +export HF_HOME="$HOME/hf-cache" HF_HUB_CACHE="$HOME/hf-cache/hub" HF_HUB_OFFLINE=1 +export UMD_ENABLE_COREDUMP_ON_EXCEPTION=1 UMD_ENABLE_LIGHTWEIGHT_COREDUMP=1 +mkdir -p "$artifacts/eval-results" +ln -s "$artifacts/eval-results" "$HOME/.sgl_eval" +python3 "$checker" snapshot "$artifacts/dependencies-before.json" +finalize() { + code=$? + trap - EXIT + set +e + if ! python3 "$checker" snapshot "$artifacts/dependencies-after.json"; then + code=1 + elif ! python3 "$checker" check "$artifacts/dependencies-before.json" "$artifacts/dependencies-after.json"; then + code=1 + fi + if ! verify_wheels; then + code=1 + fi + printf '%s\n' "$code" > "$artifacts/exit-code.txt" + exit "$code" +} +trap finalize EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +python3 "$repo/scripts/ci/ppu/check_ppu_environment.py" +python3 -c 'import torch; print("Runtime Torch:", torch.__version__, "SAIL build marker:", getattr(torch.version, "sail", None)); assert torch.cuda.device_count() == 1' +python3 -m pip uninstall -y sgl-kernel +python3 -m pip install --no-deps --no-index --force-reinstall "$wheel_dir/"*.whl +missing_wheels=$(python3 "$checker" missing-wheels "$wheel_dir/runtime-deps") +if [[ -n "$missing_wheels" ]]; then + mapfile -t runtime_wheels <<< "$missing_wheels" + python3 -m pip install --no-deps --no-index "${runtime_wheels[@]}" +fi +python3 "$checker" snapshot "$artifacts/dependencies-installed.json" +python3 "$checker" check "$artifacts/dependencies-before.json" "$artifacts/dependencies-installed.json" +python3 - <<'PY' +from sailify.sailify_python import sailify_extra_files_recursive +import sgl_kernel +import sglang +import torch +from sglang.srt.platforms import current_platform + +assert current_platform.is_sail(), "The installed SGLang did not select SAIL" +print("Runtime Torch:", torch.__version__, "SAIL build marker:", getattr(torch.version, "sail", None)) +print("SGLang:", sglang.__file__) +print("AOT extension:", sgl_kernel.common_ops.__file__) +PY +python3 "$repo/scripts/ci/ppu/prepare_runtime.py" + +cd "$artifacts" +python3 "$repo/test/run_suite.py" --hw ppu --suite stage-a-test-1-gpu-ppu --timeout-per-file 1200 \ + 2>&1 | tee "$artifacts/sanity.log" +# Require both sanity files; update this count when extending the suite. +grep -Fxq 'Test Summary: 2/2 passed' "$artifacts/sanity.log" diff --git a/scripts/ci/ppu/check_dependencies.py b/scripts/ci/ppu/check_dependencies.py new file mode 100644 index 0000000000..4a0057912d --- /dev/null +++ b/scripts/ci/ppu/check_dependencies.py @@ -0,0 +1,129 @@ +import argparse +import hashlib +import json +import re +import sys +from importlib import metadata +from pathlib import Path + +BUILD_TARGETS = {"sglang", "sgl-kernel", "sglang-kernel"} +PINNED_ADDITIONS = { + "sailify": "1.0.0", + "sgl-eval": "0.1.2", + "math-verify": "0.9.0", + "latex2sympy2-extended": "1.11.0", + "antlr4-python3-runtime": "4.9.3", + "editdistance": "0.8.1", +} + + +def normalize_name(name): + return re.sub(r"[-_.]+", "-", name).lower() + + +def snapshot(): + packages = {} + for dist in metadata.distributions(): + name = normalize_name(dist.metadata["Name"]) + if name not in packages: + packages[name] = { + "version": dist.version, + "record": hashlib.sha256( + (dist.read_text("RECORD") or "").encode() + ).hexdigest(), + } + return packages + + +def validate_evaluators(packages): + for name, version in PINNED_ADDITIONS.items(): + if name == "sailify" or name not in packages: + continue + installed = packages[name]["version"] + if installed != version: + raise ValueError( + f"Preinstalled {name}=={installed} does not match required " + f"{name}=={version}; refusing to replace it." + ) + + +def missing_wheels(wheel_dir, packages): + if not wheel_dir.is_dir(): + raise ValueError(f"Wheel directory does not exist: {wheel_dir}") + available = {} + for path in wheel_dir.resolve().glob("*.whl"): + match = re.fullmatch( + r"([^-]+)-([^-]+)-(?:[0-9][^-]*-)?[^-]+-[^-]+-[^-]+\.whl", path.name + ) + if path.is_file() and match: + key = (normalize_name(match[1]), match[2]) + available.setdefault(key, []).append(path) + selected = [] + for name, version in PINNED_ADDITIONS.items(): + if name in packages: + continue + matches = available.get((name, version), []) + if len(matches) != 1: + raise ValueError( + f"Expected exactly one wheel for {name}=={version} in {wheel_dir}; " + f"found {len(matches)}." + ) + selected.append(str(matches[0])) + return selected + + +def main(): + parser = argparse.ArgumentParser() + commands = parser.add_subparsers(dest="command", required=True) + capture = commands.add_parser("snapshot") + capture.add_argument("output", type=Path) + check = commands.add_parser("check") + check.add_argument("before", type=Path) + check.add_argument("after", type=Path) + commands.add_parser("requirements") + wheels = commands.add_parser("missing-wheels") + wheels.add_argument("wheel_dir", type=Path) + args = parser.parse_args() + if args.command == "snapshot": + args.output.write_text(json.dumps(snapshot(), indent=2, sort_keys=True) + "\n") + return 0 + if args.command == "requirements": + for name, version in PINNED_ADDITIONS.items(): + if name != "sailify": + print(f"{name}=={version}") + return 0 + if args.command == "missing-wheels": + try: + packages = snapshot() + validate_evaluators(packages) + lines = missing_wheels(args.wheel_dir, packages) + except ValueError as error: + print(error, file=sys.stderr) + return 1 + for line in lines: + print(line) + return 0 + + before = json.loads(args.before.read_text()) + after = json.loads(args.after.read_text()) + changed = { + name: {"before": before.get(name), "after": after.get(name)} + for name in before.keys() | after.keys() + if name not in BUILD_TARGETS + and not ( + name not in before + and name in PINNED_ADDITIONS + and after[name]["version"] == PINNED_ADDITIONS[name] + ) + and before.get(name) != after.get(name) + } + if changed: + print("Unexpected dependency changes:", file=sys.stderr) + print(json.dumps(changed, indent=2, sort_keys=True), file=sys.stderr) + return 1 + print("All preinstalled dependencies other than build targets are unchanged.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ci/ppu/prepare_runtime.py b/scripts/ci/ppu/prepare_runtime.py new file mode 100644 index 0000000000..d6d0954707 --- /dev/null +++ b/scripts/ci/ppu/prepare_runtime.py @@ -0,0 +1,59 @@ +import hashlib +import os +from pathlib import Path + +MMLU_SHA256 = "2182319e74add5855b87c4abf4136310b900f8d2772460054681feadb7f2c52f" +MODEL_PATH_ENVS = { + "meta-llama/Llama-3.1-8B-Instruct": "PPU_CI_TARGET_MODEL_PATH", + "lmsys/sglang-EAGLE3-LLaMA3.1-Instruct-8B": "PPU_CI_EAGLE3_MODEL_PATH", + "z-lab/LLaMA3.1-8B-Instruct-DFlash-UltraChat": "PPU_CI_DFLASH_MODEL_PATH", +} + + +def prepare_model_cache(hub, checkpoints): + for model, checkpoint in checkpoints.items(): + checkpoint = Path(checkpoint).resolve(strict=True) + if not (checkpoint / "config.json").is_file(): + raise FileNotFoundError( + f"Missing model config: {checkpoint / 'config.json'}" + ) + root = hub / ("models--" + model.replace("/", "--")) + (root / "refs").mkdir(parents=True) + (root / "snapshots").mkdir() + # Hub reads the ref verbatim, including any trailing newline. + (root / "refs/main").write_text("main") + (root / "snapshots/main").symlink_to(checkpoint, target_is_directory=True) + + +def prepare_mmlu_cache(source, destination): + data = (source / "mmlu/test.jsonl").read_bytes() + marker = (source / "mmlu/test.jsonl.sha256").read_text() + if hashlib.sha256(data).hexdigest() != MMLU_SHA256 or marker != MMLU_SHA256 + "\n": + raise ValueError(f"MMLU cache checksum mismatch: {source}") + (destination / "mmlu").mkdir(parents=True) + (destination / "mmlu/test.jsonl").write_bytes(data) + (destination / "mmlu/test.jsonl.sha256").write_text(marker) + + +def main(): + from huggingface_hub import hf_hub_download + from sgl_eval.evals._loader import load_via_prepare + from sgl_eval.registry import get + + home = Path.home() + hub = Path(os.environ["HF_HUB_CACHE"]) + checkpoints = {model: os.environ[key] for model, key in MODEL_PATH_ENVS.items()} + prepare_model_cache(hub, checkpoints) + for model in checkpoints: + hf_hub_download(model, "config.json", cache_dir=hub, local_files_only=True) + prepare_mmlu_cache(Path(os.environ["PPU_CI_EVAL_CACHE"]), home / ".cache/sgl_eval") + assert get("mmlu").name == "mmlu", "MMLU evaluator must be registered" + examples = load_via_prepare("mmlu", ("test",), sample_seed=0)(200) + assert len(examples) == 200, "MMLU must load all 200 evaluation examples" + print( + "Offline model references and independent MMLU cache are ready (200 examples)." + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/ci/ppu/run_selftests.sh b/scripts/ci/ppu/run_selftests.sh new file mode 100755 index 0000000000..c8067debfb --- /dev/null +++ b/scripts/ci/ppu/run_selftests.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "$(uname -s)" != "Linux" ]]; then + printf '%s\n' 'PPU infrastructure selftests require Linux.' >&2 + exit 1 +fi +for command in flock git jq python3; do + if ! command -v "$command" >/dev/null; then + printf 'Missing required command: %s\n' "$command" >&2 + exit 1 + fi +done + +ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../.." && pwd) +export PYTHONPATH="$ROOT/python${PYTHONPATH:+:$PYTHONPATH}" +export PYTHONDONTWRITEBYTECODE=1 +export SGLANG_IS_IN_CI=0 +export SGLANG_TEST_MAX_RETRY=0 +export HF_HUB_OFFLINE=1 + +printf '%s\n' 'Running PPU infrastructure selftests with the current Python environment; no packages will be installed.' +for file in test_ppu_ci_dependencies.py test_ppu_ci_docker.py test_ppu_ci_suite.py; do + printf '\nRunning %s\n' "$file" + python3 "$ROOT/scripts/ci/ppu/$file" -f +done +printf '\n%s\n' 'PPU infrastructure selftests passed (3 files).' diff --git a/scripts/ci/ppu/run_test.sh b/scripts/ci/ppu/run_test.sh new file mode 100755 index 0000000000..e72a9ec273 --- /dev/null +++ b/scripts/ci/ppu/run_test.sh @@ -0,0 +1,247 @@ +#!/usr/bin/env bash +set -euo pipefail + +fail() { printf 'PPU CI: %s\n' "$*" >&2; exit 2; } + +for name in PPU_CI_RUNTIME_IMAGE PPU_CI_SOURCE_SHA PPU_CI_WHEEL_DIR PPU_CI_ARTIFACT_DIR \ + PPU_CI_TARGET_MODEL_PATH PPU_CI_EAGLE3_MODEL_PATH PPU_CI_DFLASH_MODEL_PATH PPU_CI_EVAL_CACHE; do + [[ -n "${!name:-}" ]] || fail "Set $name explicitly" +done +device=${PPU_CI_DEVICE:-${NVIDIA_VISIBLE_DEVICES:-}} +[[ "$device" =~ ^[0-9]+$ ]] || fail 'Select exactly one numeric device with PPU_CI_DEVICE' +# Canonicalize without integer overflow; 01 and 1 must share the same lock. +device="${device#"${device%%[!0]*}"}" +device=${device:-0} +repo=$(git -C "$(dirname "${BASH_SOURCE[0]}")" rev-parse --show-toplevel) +repo=$(realpath -e "$repo") +[[ "$(git -C "$repo" rev-parse HEAD)" == "$PPU_CI_SOURCE_SHA" ]] || fail 'HEAD must equal PPU_CI_SOURCE_SHA exactly' +status=$(git -C "$repo" status --porcelain=v1 --untracked-files=normal --ignored --ignore-submodules=none) +[[ -z "$status" ]] || fail 'Source must be pristine, including untracked and ignored files' + +# Exact inventories prevent unchecked extra wheels from being installed. +paths=$(python3 - "$repo" <<'PY' +import hashlib +import os +from pathlib import Path +import re +import sys + + +def fail(message): + sys.exit("PPU CI: " + message) + + +def below(path, parent): + return os.path.commonpath([str(path), str(parent)]) == str(parent) + + +def validate_symlinks(root): + for directory, dirs, files in os.walk( + root, followlinks=False, onerror=lambda error: fail(str(error)) + ): + for name in dirs + files: + link = Path(directory) / name + if not link.is_symlink(): + continue + if Path(os.readlink(link)).is_absolute(): + fail("Absolute symlink in read-only input: " + str(link)) + try: + destination = link.resolve(strict=True) + except (OSError, RuntimeError) as error: + fail("Invalid symlink " + str(link) + ": " + str(error)) + if not below(destination, root): + fail("Escaping symlink in read-only input: " + str(link)) + + +try: + repo = Path(sys.argv[1]) + names = ["WHEEL_DIR", "ARTIFACT_DIR", "TARGET_MODEL_PATH", "EAGLE3_MODEL_PATH", "DFLASH_MODEL_PATH", "EVAL_CACHE"] + paths = [] + for name in names: + raw = os.environ["PPU_CI_" + name] + if not Path(raw).is_absolute(): + fail(name + " must be absolute") + path = Path(raw).resolve(strict=True) + if not path.is_dir(): + fail(name + " must be a directory") + paths.append(path) + for path in [repo] + paths: + if "," in str(path): + fail("Docker mount paths must not contain commas") + if "\n" in str(path) or "\r" in str(path): + fail("Docker mount paths must not contain newlines") + wheels, artifacts, target, eagle3, dflash, cache = paths + if below(wheels, repo) or below(artifacts, repo): + fail("Wheels and artifacts must be outside source") + if any(below(artifacts, path) for path in [wheels, target, eagle3, dflash, cache]): + fail("Artifacts must not be inside read-only inputs") + for root in [target, eagle3, dflash, cache]: + validate_symlinks(root) + for model in [target, eagle3, dflash]: + if not (model / "config.json").is_file(): + fail("Missing model config.json: " + str(model)) + for name in ["test.jsonl", "test.jsonl.sha256"]: + if not (cache / "mmlu" / name).is_file(): + fail("Missing eval cache mmlu/" + name) + if (wheels / "source-sha.txt").read_text() != os.environ["PPU_CI_SOURCE_SHA"] + "\n": + fail("Wheel source-sha.txt must match PPU_CI_SOURCE_SHA") + if (wheels / "runtime-deps").is_symlink(): + fail("Wheel inventory must not use symlink directories") + inventory = {"source-sha.txt": wheels / "source-sha.txt"} + for wheel in wheels.rglob("*.whl"): + name = "./" + str(wheel.relative_to(wheels)) + if not re.fullmatch(r"\./(?:runtime-deps/)?[A-Za-z0-9][A-Za-z0-9_.+-]*\.whl", name): + fail("Unexpected wheel inventory entry: " + name) + inventory[name] = wheel + if not list(wheels.glob("*.whl")) or not list((wheels / "runtime-deps").glob("*.whl")): + fail("Wheel inventory needs main and runtime-deps wheels") + checksums = {} + for line in (wheels / "SHA256SUMS").read_text().splitlines(): + match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) + if not match or match[2] in checksums: + fail("Invalid or duplicate checksum inventory entry") + checksums[match[2]] = match[1] + if checksums.keys() != inventory.keys(): + fail("Checksum inventory must list source-sha.txt and every wheel exactly") + for name, path in inventory.items(): + if path.is_symlink() or not path.is_file(): + fail("Wheel inventory requires regular files: " + name) + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + if digest.hexdigest() != checksums[name]: + fail("Wheel checksum mismatch: " + name) + print("\n".join(map(str, paths))) +except (OSError, ValueError) as error: + fail(str(error)) +PY +) || exit 2 +mapfile -t inputs <<< "$paths" +wheels=${inputs[0]} +artifact_parent=${inputs[1]} + +# Never unlink the shared lock: waiters must keep using the same inode. +exec 9>>"/tmp/sglang-ppu-ci-device-$device.lock" +flock -n 9 || fail "PPU device $device is busy" +private=$(mktemp -d "$artifact_parent/runtime.XXXXXXXX") +uid=$(id -u) +gid=$(id -g) +prefix="sglang-ppu-ci-$uid-$$-${private##*.}" +container="" +docker_pid="" +image_id="" +# Invoked by the EXIT trap, including an interrupted wait. +# shellcheck disable=SC2329 +cleanup() { + code=$? + trap - EXIT + trap '' INT TERM + set +e + cleanup_code=0 + if [[ -n "$container" ]]; then + # Leave time for removal and ownership recovery before runner SIGKILL. + docker stop --time=2 "$container" 9>&- >/dev/null 2>&1 + docker rm --force "$container" 9>&- >/dev/null 2>&1 || cleanup_code=1 + fi + if [[ -n "$docker_pid" ]]; then + kill "$docker_pid" 2>/dev/null + wait "$docker_pid" 2>/dev/null + fi + # Recover ownership only after the runtime can no longer write artifacts. + if [[ -n "$image_id" ]]; then + docker run --rm --name "$prefix-ownership" --runtime=runc --network=none \ + --env NVIDIA_VISIBLE_DEVICES=void --user 0:0 \ + --mount "type=bind,source=$private,target=/artifacts" \ + --entrypoint chown "$image_id" -hR -- "$uid:$gid" /artifacts \ + 9>&- >>"$private/ownership.log" 2>&1 || cleanup_code=1 + fi + if [[ "$cleanup_code" != 0 ]]; then + printf 'PPU CI: container cleanup or artifact ownership recovery failed\n' >&2 + [[ "$code" != 0 ]] || code=1 + fi + exec 9>&- + exit "$code" +} +trap 'cleanup' EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +if ! image_id=$(docker image inspect "$PPU_CI_RUNTIME_IMAGE" --format '{{.Id}}' 9>&- 2>/dev/null); then + # Raw Docker diagnostics must stay outside all uploaded or mounted paths. + pull_log=$(python3 - "$repo" "${inputs[@]}" <<'PY' +import os +from pathlib import Path +import sys +import tempfile + +try: + home = Path(os.environ.get("HOME", "")) + if not home.is_absolute(): + sys.exit("PPU CI: Private image logs require an absolute HOME directory") + home = home.resolve(strict=True) + if not home.is_dir() or "\n" in str(home) or "\r" in str(home): + sys.exit("PPU CI: Private image logs require a valid HOME directory") + excluded = sys.argv[1:] + [ + os.environ[name] for name in ("RUNNER_TEMP", "GITHUB_WORKSPACE") + if os.environ.get(name) + ] + for raw in excluded: + path = Path(raw).resolve() + if os.path.commonpath([str(home), str(path)]) == str(path): + sys.exit("PPU CI: Private image logs require HOME outside temporary, source, artifact and input directories") + directory = tempfile.mkdtemp(prefix=".sglang-ppu-ci-pull.", dir=str(home)) + fd, log = tempfile.mkstemp(prefix="pull-", suffix=".log", dir=directory) + os.close(fd) + print(log) +except (OSError, ValueError, RuntimeError): + sys.exit("PPU CI: Private image logs could not be created under HOME") +PY + ) || exit 2 + printf 'PPU CI: Private image pull log: %s\n' "$pull_log" + docker pull "$PPU_CI_RUNTIME_IMAGE" 9>&- >"$pull_log" 2>&1 & + docker_pid=$! + wait "$docker_pid" || { + code=$? + printf '%s\n' 'PPU CI: Failed to pull runtime image' >&2 + exit "$code" + } + docker_pid="" + image_id=$(docker image inspect "$PPU_CI_RUNTIME_IMAGE" --format '{{.Id}}' 9>&- 2>>"$pull_log") || { + code=$? + printf '%s\n' 'PPU CI: Failed to inspect runtime image after pull' >&2 + exit "$code" + } +fi +[[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || fail 'Docker did not resolve an immutable image ID' +printf '%s\n' "$image_id" > "$private/runtime-image-id.txt" +printf '%s\n' "$PPU_CI_SOURCE_SHA" > "$private/source-sha.txt" +printf 'PPU CI artifacts: %s\n' "$private" + +# Synchronous creation prevents containers from appearing after cleanup. +container="$prefix-test" +docker create --name "$container" --runtime=runc --shm-size=16g \ + --device=/dev/alixpu --device=/dev/alixpu_ctl --device=/dev/alixpu_sep \ + --device="/dev/alixpu_ppu$device" \ + --mount "type=bind,source=$repo,target=/source,readonly" \ + --mount "type=bind,source=$wheels,target=/wheels,readonly" \ + --mount "type=bind,source=${inputs[2]},target=/models/target,readonly" \ + --mount "type=bind,source=${inputs[3]},target=/models/eagle3,readonly" \ + --mount "type=bind,source=${inputs[4]},target=/models/dflash,readonly" \ + --mount "type=bind,source=${inputs[5]},target=/eval-cache,readonly" \ + --mount "type=bind,source=$private,target=/artifacts" \ + --env NVIDIA_VISIBLE_DEVICES=void --env CUDA_VISIBLE_DEVICES=0 \ + --env PPU_CI_SOURCE_SHA="$PPU_CI_SOURCE_SHA" \ + --env PPU_CI_WHEEL_DIR=/wheels --env PPU_CI_ARTIFACT_DIR=/artifacts \ + --env PPU_CI_TARGET_MODEL_PATH=/models/target \ + --env PPU_CI_EAGLE3_MODEL_PATH=/models/eagle3 \ + --env PPU_CI_DFLASH_MODEL_PATH=/models/dflash \ + --env PPU_CI_EVAL_CACHE=/eval-cache --env SGLANG_IS_IN_CI=1 \ + --entrypoint bash "$image_id" /source/scripts/ci/ppu/build_and_test.sh test \ + 9>&- >"$private/container-id.txt" +docker start --attach "$container" 9>&- >"$private/docker.log" 2>&1 & +docker_pid=$! +code=0 +wait "$docker_pid" || code=$? +docker_pid="" +exit "$code" diff --git a/scripts/ci/ppu/test_ppu_ci_dependencies.py b/scripts/ci/ppu/test_ppu_ci_dependencies.py new file mode 100644 index 0000000000..203dfe005c --- /dev/null +++ b/scripts/ci/ppu/test_ppu_ci_dependencies.py @@ -0,0 +1,243 @@ +import hashlib +import json +import os +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from sglang.test.test_utils import CustomTestCase + +SCRIPT = Path(__file__).resolve().parents[3] / "scripts/ci/ppu/check_dependencies.py" +ADDITIONS = { + "sailify": "1.0.0", + "sgl-eval": "0.1.2", + "math-verify": "0.9.0", + "latex2sympy2-extended": "1.11.0", + "antlr4-python3-runtime": "4.9.3", + "editdistance": "0.8.1", +} +WHEELS = { + "sailify": "sailify-1.0.0-py3-none-any.whl", + "sgl-eval": "sgl_eval-0.1.2-py3-none-any.whl", + "math-verify": "Math.Verify-0.9.0-py3-none-any.whl", + "latex2sympy2-extended": "latex2sympy2_extended-1.11.0-py3-none-any.whl", + "antlr4-python3-runtime": "antlr4_python3_runtime-4.9.3-1-py3-none-any.whl", + "editdistance": "editdistance-0.8.1-cp312-cp312-linux_x86_64.whl", +} + + +class TestPPUCIDependencies(CustomTestCase): + def check_snapshots(self, before, after): + with tempfile.TemporaryDirectory() as directory: + paths = [Path(directory) / name for name in ("before.json", "after.json")] + for path, snapshot in zip(paths, (before, after)): + path.write_text(json.dumps(snapshot)) + return subprocess.run( + [sys.executable, str(SCRIPT), "check", *map(str, paths)], + capture_output=True, + text=True, + ) + + def test_built_replacements_and_pinned_runtime_additions_are_allowed(self): + before = { + "torch": {"version": "2.13.0", "record": "compatible"}, + "triton": {"version": "3.7.0", "record": "vendor"}, + "sglang": {"version": "0.5.17", "record": "preinstalled"}, + "sglang-kernel": {"version": "0.4.8", "record": "preinstalled"}, + } + after = { + **before, + "sglang": {"version": "0.5.18", "record": "built"}, + "sglang-kernel": {"version": "0.4.9", "record": "built"}, + **{ + name: {"version": version, "record": "added"} + for name, version in ADDITIONS.items() + }, + } + result = self.check_snapshots(before, after) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_unpinned_runtime_additions_are_rejected(self): + for name, version in ADDITIONS.items(): + with self.subTest(name=name): + result = self.check_snapshots( + {}, {name: {"version": version + ".1", "record": "added"}} + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn(name, result.stderr) + + def test_existing_dependencies_are_preserved(self): + before = { + "torch": {"version": "2.13.0", "record": "compatible"}, + "triton": {"version": "3.7.0", "record": "vendor"}, + "sailify": {"version": "vendor-version", "record": "vendor"}, + "sgl-eval": {"version": ADDITIONS["sgl-eval"], "record": "vendor"}, + } + result = self.check_snapshots(before, before) + self.assertEqual(result.returncode, 0, result.stderr) + for name, replacement in ( + ("torch", {"version": "2.13.0", "record": "cuda-free"}), + ("triton", {"version": "3.8.0", "record": "vendor"}), + ("triton", {"version": "3.7.0", "record": "upstream"}), + ("triton", None), + ("sailify", {"version": ADDITIONS["sailify"], "record": "vendor"}), + ("sailify", {"version": "vendor-version", "record": "different"}), + ("sailify", None), + ("sgl-eval", {"version": "0.1.3", "record": "vendor"}), + ("sgl-eval", {"version": ADDITIONS["sgl-eval"], "record": "different"}), + ("sgl-eval", None), + ("nvidia-cublas-cu13", {"version": "13", "record": "new"}), + ): + with self.subTest(name=name, replacement=replacement): + after = before.copy() + if replacement is None: + del after[name] + else: + after[name] = replacement + result = self.check_snapshots(before, after) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Unexpected dependency changes", result.stderr) + self.assertIn(name, result.stderr) + + def run_isolated_cli(self, command, installed=None, wheel_names=()): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + site = root / "site" + site.mkdir() + for name, version in (installed or {}).items(): + info = site / f"{name.replace('-', '_')}-{version}.dist-info" + info.mkdir() + (info / "METADATA").write_text(f"Name: {name}\nVersion: {version}\n") + (info / "RECORD").write_text("preinstalled") + wheel_dir = root / "wheel house" + wheel_dir.mkdir() + for name in wheel_names: + (wheel_dir / name).touch() + args = [str(wheel_dir)] if command == "missing-wheels" else [] + result = subprocess.run( + [sys.executable, "-S", str(SCRIPT), command, *args], + env={**os.environ, "PYTHONPATH": str(site)}, + capture_output=True, + text=True, + ) + return result, wheel_dir + + def test_requirements_cli_emits_only_pinned_evaluators(self): + result, _ = self.run_isolated_cli( + "requirements", {"sailify": "vendor-version", "sgl-eval": "99.0.0"} + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + result.stdout, + "sgl-eval==0.1.2\n" + "math-verify==0.9.0\n" + "latex2sympy2-extended==1.11.0\n" + "antlr4-python3-runtime==4.9.3\n" + "editdistance==0.8.1\n", + ) + self.assertEqual(result.stderr, "") + + def test_missing_wheels_cli_selects_exact_normalized_pins(self): + result, wheel_dir = self.run_isolated_cli( + "missing-wheels", + wheel_names=[ + *WHEELS.values(), + "sgl_eval-0.1.20-py3-none-any.whl", + "sgl_eval_extra-0.1.2-py3-none-any.whl", + "sgl_eval-0.1.2.tar.gz", + "torch-2.13.0-py3-none-any.whl", + ], + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + result.stdout, + "".join(f"{wheel_dir / name}\n" for name in WHEELS.values()), + ) + self.assertEqual(result.stderr, "") + + def test_missing_wheels_cli_skips_preinstalled_distributions(self): + for installed in ( + {"Sailify": "vendor-version", "SGL.Eval": "0.1.2"}, + {**ADDITIONS, "sailify": "vendor-version"}, + ): + with self.subTest(installed=installed): + missing = list(WHEELS.values())[2:] if "SGL.Eval" in installed else [] + result, wheel_dir = self.run_isolated_cli( + "missing-wheels", installed, missing + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + result.stdout, "".join(f"{wheel_dir / name}\n" for name in missing) + ) + self.assertEqual(result.stderr, "") + + def test_cli_rejects_preinstalled_evaluator_pin_conflicts(self): + for name, version in ADDITIONS.items(): + if name == "sailify": + continue + with self.subTest(name=name): + result, _ = self.run_isolated_cli( + "missing-wheels", {name: version + ".1"}, WHEELS.values() + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, "") + self.assertIn(name, result.stderr) + self.assertIn(version + ".1", result.stderr) + self.assertIn(version, result.stderr) + + def test_missing_wheels_cli_rejects_invalid_candidates(self): + for name, wheel in WHEELS.items(): + for case, candidates in ( + ("missing", []), + ("wrong-version", [wheel.replace(ADDITIONS[name], "99.0.0")]), + ("duplicate", [wheel, wheel.replace(".whl", "2.whl")]), + ): + with self.subTest(name=name, case=case): + wheels = [value for value in WHEELS.values() if value != wheel] + result, _ = self.run_isolated_cli( + "missing-wheels", wheel_names=wheels + candidates + ) + self.assertNotEqual(result.returncode, 0) + self.assertEqual(result.stdout, "") + self.assertIn(f"{name}=={ADDITIONS[name]}", result.stderr) + + def test_snapshot_uses_first_distribution_on_python_path(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + sites = [root / name for name in ("build", "runtime")] + for site in sites: + info = site / "ppu_ci_snapshot_probe-1.0.dist-info" + info.mkdir(parents=True) + (info / "METADATA").write_text( + "Name: ppu-ci-snapshot-probe\nVersion: 1.0\n" + ) + (info / "RECORD").write_text(site.name) + output = root / "snapshot.json" + for order in (sites, sites[::-1]): + with self.subTest(first=order[0].name): + result = subprocess.run( + [sys.executable, str(SCRIPT), "snapshot", str(output)], + env={ + **os.environ, + "PYTHONPATH": os.pathsep.join(map(str, order)), + }, + capture_output=True, + text=True, + ) + self.assertEqual(result.returncode, 0, result.stderr) + snapshot = json.loads(output.read_text()) + self.assertEqual( + snapshot["ppu-ci-snapshot-probe"], + { + "version": "1.0", + "record": hashlib.sha256( + order[0].name.encode() + ).hexdigest(), + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/ci/ppu/test_ppu_ci_docker.py b/scripts/ci/ppu/test_ppu_ci_docker.py new file mode 100644 index 0000000000..040bfb4ca4 --- /dev/null +++ b/scripts/ci/ppu/test_ppu_ci_docker.py @@ -0,0 +1,650 @@ +"""Host launcher protocol tests; Docker/git boundaries need no PPU or daemon.""" + +import hashlib +import json +import os +import select +import shutil +import signal +import subprocess +import sys +import tempfile +import time +import unittest +import uuid +from pathlib import Path + +import yaml + +from sglang.test.test_utils import CustomTestCase + +if sys.platform == "linux": + import fcntl + +REPO = Path(__file__).resolve().parents[3] +SCRIPT = REPO / "scripts/ci/ppu/run_test.sh" +WORKFLOW = REPO / ".github/workflows/pr-test-ppu.yml" +# Finish before GitHub's ~7.5s SIGINT + 2.5s SIGTERM force-kill window. +CANCELLATION_BUDGET = 7.5 +SHA = "a" * 40 +IMAGE_ID = "sha256:" + "b" * 64 + +# Stub Git to avoid modifying the checkout under test. +GIT = r""" +import os +import sys +from pathlib import Path + +args = sys.argv[1:] +root = Path(os.environ["FIXTURE_SOURCE"]) +assert args[0] == "-C" and Path(args[1]).resolve() in (root, root / "scripts/ci/ppu"), args +args = args[2:] +if args == ["rev-parse", "--show-toplevel"]: + print(root) +elif args == ["rev-parse", "HEAD"]: + print("a" * 40) +elif args[0] == "status": + assert any(arg.startswith("--porcelain") for arg in args), args + if (root / "dirty-tracked").exists(): + print(" M tracked.py") + if (root / "dirty-untracked").exists(): + print("?? untracked.py") + if (root / "dirty-ignored").exists() and any(arg.startswith("--ignored") for arg in args): + print("!! ignored.whl") +else: + raise AssertionError(args) +""" + +DOCKER = r""" +import fcntl +import json +import os +import signal +import sys +import time +from pathlib import Path + +args = sys.argv[1:] +root = Path(os.environ["FIXTURE_ROOT"]) +lock = Path(os.environ["FIXTURE_LOCK"]) +held = False +if lock.exists(): + with lock.open("a") as handle: + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + held = True +with (root / "docker.jsonl").open("a") as log: + log.write(json.dumps({"args": args, "lock_held": held}) + "\n") +state = root / "container.json" +if args[:2] == ["image", "inspect"]: + print("Inspecting " + args[2], file=sys.stderr) + if os.environ.get("MISSING_IMAGE") and not (root / "pulled").exists(): + sys.exit(1) + if os.environ.get("INSPECT_EXIT"): + sys.exit(int(os.environ["INSPECT_EXIT"])) + print("sha256:" + "b" * 64) +elif args[0] == "pull": + print("Pulling " + args[1]) + print("Registry: " + args[1].split("/")[0], file=sys.stderr) + print("Repository: " + args[1], file=sys.stderr) + if os.environ.get("PULL_EXIT"): + sys.exit(int(os.environ["PULL_EXIT"])) + if os.environ.get("BLOCK_PULL"): + (root / "pull.pid").write_text(str(os.getpid())) + signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) + with (root / "ready.fifo").open("w") as ready: + ready.write("started\n") + signal.pause() + (root / "pulled").touch() +elif args[0] == "create": + name = args[args.index("--name") + 1] + assert not state.exists(), "another container was overwritten" + state.write_text(json.dumps({"name": name})) + print("fixture-container-id") +elif args[0] == "start": + data = json.loads(state.read_text()) + assert args[-1] == data["name"] + data["pid"] = os.getpid() + state.write_text(json.dumps(data)) + if os.environ.get("BLOCK_TEST"): + # Model PID 1 deferring TERM while its foreground inference is running. + if os.environ.get("DELAY_CONTAINER_TERM"): + signal.signal(signal.SIGTERM, signal.SIG_IGN) + else: + signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) + with (root / "ready.fifo").open("w") as ready: + ready.write("started\n") + signal.pause() + sys.exit(int(os.environ.get("TEST_EXIT", "0"))) +elif args[0] == "stop": + data = json.loads(state.read_text()) + assert args[-1] == data["name"], "stopped someone else's container" + if "pid" in data: + try: + os.kill(data["pid"], signal.SIGTERM) + if os.environ.get("DELAY_CONTAINER_TERM"): + # Simulate Docker's daemon waiting the requested grace, then KILL. + grace = 10.0 + for index, arg in enumerate(args): + if arg.startswith(("--time=", "--timeout=")): + grace = float(arg.split("=", 1)[1]) + elif arg in ("--time", "--timeout", "-t"): + grace = float(args[index + 1]) + started = time.monotonic() + time.sleep(grace) + os.kill(data["pid"], signal.SIGKILL) + (root / "stop-delay.json").write_text(json.dumps({ + "grace": grace, "elapsed": time.monotonic() - started, + })) + except ProcessLookupError: + pass +elif args[0] == "rm": + assert args[-1] == json.loads(state.read_text())["name"] + state.unlink() +elif args[0] == "run": + assert not state.exists(), "ownership recovery ran before container removal" + assert "chown" in args, args + mounts = [args[i + 1] for i, arg in enumerate(args) if arg == "--mount"] + assert len(mounts) == 1, "ownership helper exposed shared inputs" + mount = dict(item.split("=", 1) for item in mounts[0].split(",")) + assert mount["target"] == "/artifacts" + private = Path(mount["source"]) + (private / "ownership-recovered").touch() +else: + raise AssertionError(args) +""" + + +@unittest.skipUnless( + sys.platform == "linux" and shutil.which("flock"), + "The Docker host launcher requires Linux and util-linux flock", +) +class TestPPUCIDocker(CustomTestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="ppu-docker-test-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name).resolve() + self.source = self.root / "source with spaces" + script_dir = self.source / "scripts/ci/ppu" + script_dir.mkdir(parents=True) + self.launcher = script_dir / "run_test.sh" + if SCRIPT.exists(): + shutil.copyfile(SCRIPT, self.launcher) + self.bin = self.root / "bin" + self.bin.mkdir() + for name, body in (("docker", DOCKER), ("git", GIT)): + path = self.bin / name + path.write_text(f"#!{sys.executable}\n" + body) + path.chmod(0o700) + self.wheels = self.root / "wheel house" + (self.wheels / "runtime-deps").mkdir(parents=True) + (self.wheels / "source-sha.txt").write_text(SHA + "\n") + (self.wheels / "sglang-1-py3-none-any.whl").write_bytes(b"main wheel") + (self.wheels / "runtime-deps/sailify-1-py3-none-any.whl").write_bytes( + b"dependency" + ) + self.manifest() + self.artifacts = self.root / "artifacts" + self.artifacts.mkdir() + self.home = self.root / "runner home" + self.home.mkdir() + self.runner_temp = self.root / "runner temp" + self.runner_temp.mkdir() + self.models = [self.root / name for name in ("target", "eagle3", "dflash")] + for model in self.models: + model.mkdir() + (model / "config.json").write_text("{}") + self.cache = self.root / "eval-cache" + (self.cache / "mmlu").mkdir(parents=True) + data = b'{"question": "fixture"}\n' + (self.cache / "mmlu/test.jsonl").write_bytes(data) + (self.cache / "mmlu/test.jsonl.sha256").write_text( + hashlib.sha256(data).hexdigest() + "\n" + ) + self.device = str(uuid.uuid4().int) + self.lock = Path(f"/tmp/sglang-ppu-ci-device-{self.device}.lock") + # LIFO cleanup keeps the fixture lock until launcher processes exit. + self.addCleanup(self.lock.unlink, missing_ok=True) + self.env = { + key: value + for key, value in os.environ.items() + if not key.startswith(("PPU_CI_", "CONFIG_PPU_CI_")) + and key != "NVIDIA_VISIBLE_DEVICES" + } + self.env.update( + PATH=f"{self.bin}:{os.environ['PATH']}", + HOME=str(self.home), + RUNNER_TEMP=str(self.runner_temp), + GITHUB_WORKSPACE=str(self.source), + FIXTURE_ROOT=str(self.root), + FIXTURE_SOURCE=str(self.source), + FIXTURE_LOCK=str(self.lock), + PPU_CI_RUNTIME_IMAGE="example.invalid/ppu/runtime:fixture", + PPU_CI_SOURCE_SHA=SHA, + PPU_CI_DEVICE=self.device, + PPU_CI_WHEEL_DIR=str(self.wheels), + PPU_CI_ARTIFACT_DIR=str(self.artifacts), + PPU_CI_TARGET_MODEL_PATH=str(self.models[0]), + PPU_CI_EAGLE3_MODEL_PATH=str(self.models[1]), + PPU_CI_DFLASH_MODEL_PATH=str(self.models[2]), + PPU_CI_EVAL_CACHE=str(self.cache), + ) + os.mkfifo(self.root / "ready.fifo") + self.ready = os.open(self.root / "ready.fifo", os.O_RDWR | os.O_NONBLOCK) + self.addCleanup(os.close, self.ready) + + def manifest(self): + names = ["source-sha.txt"] + [ + "./" + str(path.relative_to(self.wheels)) + for path in sorted(self.wheels.rglob("*.whl")) + ] + (self.wheels / "SHA256SUMS").write_text( + "".join( + f"{hashlib.sha256((self.wheels / name).read_bytes()).hexdigest()} {name}\n" + for name in names + ) + ) + + def run_launcher(self, **updates): + return subprocess.run( + ["bash", str(self.launcher)], + cwd=self.root, + env={**self.env, **updates}, + capture_output=True, + text=True, + timeout=15, + ) + + def events(self): + path = self.root / "docker.jsonl" + return ( + [json.loads(line) for line in path.read_text().splitlines()] + if path.exists() + else [] + ) + + def rejected(self, message, **updates): + result = self.run_launcher(**updates) + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn(message, result.stderr) + self.assertEqual(self.events(), [], "validation must precede Docker") + + def test_runtime_image_requires_runner_configuration(self): + self.env.pop("PPU_CI_RUNTIME_IMAGE") + self.rejected("Set PPU_CI_RUNTIME_IMAGE explicitly") + + def test_image_acquisition_errors_are_private_and_preserve_status(self): + logs = set() + for variable, code in (("PULL_EXIT", 23), ("INSPECT_EXIT", 24)): + with self.subTest(failure=variable): + result = self.run_launcher(MISSING_IMAGE="1", **{variable: str(code)}) + self.assertEqual(result.returncode, code, result.stdout + result.stderr) + self.assertIn("PPU CI:", result.stderr) + self.assert_image_reference_is_private(result) + log = self.assert_private_pull_log(result.stdout) + logs.add(log) + if variable == "INSPECT_EXIT": + self.assertIn("Inspecting ", log.read_text()) + self.assertFalse( + any(event["args"][0] == "create" for event in self.events()) + ) + with self.lock.open("a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.assertEqual(len(logs), 2) + + def test_private_log_rejects_temporary_or_exposed_home(self): + alias = self.root / "home alias" + for home in ( + self.runner_temp, + self.artifacts, + self.source, + self.wheels, + *self.models, + self.cache, + ): + with self.subTest(home=home.name): + alias.symlink_to(home, target_is_directory=True) + try: + result = self.run_launcher(HOME=str(alias), MISSING_IMAGE="1") + finally: + alias.unlink() + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn("Private image logs", result.stderr) + self.assertFalse( + any(event["args"][0] == "pull" for event in self.events()) + ) + self.assertEqual(list(home.glob(".sglang-ppu-ci-pull.*")), []) + self.assert_image_reference_is_private(result) + + def assert_private_pull_log(self, output): + prefix = "PPU CI: Private image pull log: " + paths = [ + line[len(prefix) :] + for line in output.splitlines() + if line.startswith(prefix) + ] + self.assertEqual(len(paths), 1, output) + path = Path(paths[0]) + self.assertTrue(path.is_relative_to(self.home)) + self.assertFalse(path.is_relative_to(self.runner_temp)) + self.assertFalse(path.is_relative_to(self.artifacts)) + self.assertEqual(path.parent.stat().st_mode & 0o777, 0o700) + self.assertEqual(path.stat().st_mode & 0o777, 0o600) + content = path.read_text() + self.assertIn("Pulling " + self.env["PPU_CI_RUNTIME_IMAGE"], content) + self.assertIn("Repository: " + self.env["PPU_CI_RUNTIME_IMAGE"], content) + return path + + def assert_image_reference_is_private(self, result): + registry = self.env["PPU_CI_RUNTIME_IMAGE"].split("/")[0] + self.assertNotIn(registry, result.stdout + result.stderr) + for path in self.artifacts.rglob("*"): + if path.is_file(): + self.assertNotIn(registry, path.read_text(), str(path)) + + def test_device_is_explicit_and_single_numeric(self): + """Never turn absent, invalid or multi-card runner assignments into card 0.""" + for device in ("", "all", "void", "1,2", "-1", "1x"): + with self.subTest(device=device): + self.rejected("numeric device", PPU_CI_DEVICE=device) + self.rejected("numeric device", PPU_CI_DEVICE="bad", NVIDIA_VISIBLE_DEVICES="2") + + def test_source_identity_includes_untracked_and_ignored_inputs(self): + """A clean tracked diff alone is insufficient provenance for wheel builds.""" + self.rejected("HEAD", PPU_CI_SOURCE_SHA="c" * 40) + for kind in ("tracked", "untracked", "ignored"): + with self.subTest(kind=kind): + marker = self.source / f"dirty-{kind}" + marker.touch() + self.rejected("pristine") + marker.unlink() + (self.wheels / "source-sha.txt").write_text("c" * 40 + "\n") + self.manifest() + self.rejected("source-sha.txt") + + def test_checksum_covers_content_and_exact_installable_inventory(self): + """Checking listed hashes alone permits unlisted packages to be installed.""" + for name in ("injected.whl", ".hidden.whl", "runtime-deps/injected.whl"): + with self.subTest(name=name): + injected = self.wheels / name + injected.write_bytes(b"injected") + self.rejected("inventory") + injected.unlink() + for wheel in self.wheels.rglob("*.whl"): + with self.subTest(wheel=wheel.name): + original = wheel.read_bytes() + wheel.write_bytes(b"tampered") + self.rejected("checksum") + wheel.write_bytes(original) + manifest = self.wheels / "SHA256SUMS" + original = manifest.read_text() + manifest.write_text(original + original.splitlines(keepends=True)[0]) + self.rejected("inventory") + manifest.write_text(original.replace("source-sha.txt", "../source-sha.txt")) + self.rejected("inventory") + + def test_mounts_require_valid_inputs_and_no_source_overlap(self): + """Canonicalize before containment checks; no writable mount hides source.""" + for path in ( + self.models[0] / "config.json", + self.cache / "mmlu/test.jsonl.sha256", + ): + original = path.read_bytes() + path.unlink() + self.rejected(path.name) + path.write_bytes(original) + self.rejected("absolute", PPU_CI_WHEEL_DIR="wheel house") + alias = self.root / "alias" + alias.symlink_to(self.source, target_is_directory=True) + self.rejected("outside source", PPU_CI_ARTIFACT_DIR=str(alias)) + self.rejected("outside source", PPU_CI_WHEEL_DIR=str(alias)) + comma = self.root / "bad,mount" + comma.mkdir() + self.rejected("commas", PPU_CI_ARTIFACT_DIR=str(comma)) + + def test_model_and_cache_symlinks_stay_within_each_mount(self): + """Docker remaps each root, so host-valid links can still break mounts.""" + for root in [*self.models, self.cache]: + nested = root / "nested" + nested.mkdir() + (root / "weights.bin").write_bytes(b"internal") + outside = root.with_name(root.name + "-outside") + outside.mkdir() + (outside / "weights.bin").write_bytes(b"external") + other_mount = self.cache if root != self.cache else self.models[0] + cases = ( + ("file-escape", os.path.relpath(outside / "weights.bin", nested)), + ("absolute-file", str(root / "weights.bin")), + ("absolute-directory", str(root)), + ("directory-escape", os.path.relpath(other_mount, nested)), + ("dangling", "../missing.bin"), + ) + for kind, destination in cases: + with self.subTest(root=root.name, link=kind): + link = nested / kind + link.symlink_to(destination) + try: + self.rejected("symlink") + finally: + link.unlink() + (nested / "internal-file").symlink_to("../weights.bin") + (nested / "internal-directory").symlink_to("..", target_is_directory=True) + result = self.run_launcher() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_lifecycle() + + def assert_lifecycle(self): + events = self.events() + self.assertTrue(events) + self.assertTrue(all(event["lock_held"] for event in events), events) + commands = [event["args"][0] for event in events] + self.assertLess(commands.index("stop"), commands.index("rm")) + self.assertLess(commands.index("rm"), commands.index("run")) + create = next(event["args"] for event in events if event["args"][0] == "create") + name = create[create.index("--name") + 1] + for event in events: + if event["args"][0] in ("stop", "rm"): + self.assertEqual(event["args"][-1], name) + ownership = events[-1]["args"] + self.assertEqual(ownership[0], "run") + self.assertIn(f"{os.getuid()}:{os.getgid()}", ownership) + self.assertIn("--runtime=runc", ownership) + self.assertIn("NVIDIA_VISIBLE_DEVICES=void", ownership) + self.assertIn(IMAGE_ID, ownership) + self.assertFalse((self.root / "container.json").exists()) + self.assertEqual(len(list(self.artifacts.glob("*/ownership-recovered"))), 1) + with self.lock.open("a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + return create + + def test_nonzero_device_uses_readonly_inputs_and_pinned_image_id(self): + """A tag may move after inspect; an NVIDIA default runtime must not add GPUs.""" + result = self.run_launcher(MISSING_IMAGE="1") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assert_image_reference_is_private(result) + self.assert_private_pull_log(result.stdout) + create = self.assert_lifecycle() + self.assertIn("--runtime=runc", create) + self.assertIn("NVIDIA_VISIBLE_DEVICES=void", create) + self.assertIn("CUDA_VISIBLE_DEVICES=0", create) + self.assertEqual( + {arg for arg in create if arg.startswith("--device=")}, + { + f"--device=/dev/{name}" + for name in ( + "alixpu", + "alixpu_ctl", + "alixpu_sep", + f"alixpu_ppu{self.device}", + ) + }, + ) + self.assertEqual( + create[-3:], [IMAGE_ID, "/source/scripts/ci/ppu/build_and_test.sh", "test"] + ) + self.assertNotIn(self.env["PPU_CI_RUNTIME_IMAGE"], create) + mounts = [create[i + 1] for i, arg in enumerate(create) if arg == "--mount"] + expected = { + "/source": self.source, + "/wheels": self.wheels, + "/models/target": self.models[0], + "/models/eagle3": self.models[1], + "/models/dflash": self.models[2], + "/eval-cache": self.cache, + } + self.assertEqual(len(mounts), 7) + for target, source in expected.items(): + self.assertIn(f"type=bind,source={source},target={target},readonly", mounts) + private = next(mount for mount in mounts if "target=/artifacts" in mount) + self.assertNotIn("readonly", private) + self.assertIn(f"source={self.artifacts}/", private) + for forbidden in ( + "--privileged", + "--ipc=host", + "--network=host", + "docker.sock", + ): + self.assertNotIn(forbidden, " ".join(create)) + records = list(self.artifacts.glob("*/runtime-image-id.txt")) + self.assertEqual([path.read_text().strip() for path in records], [IMAGE_ID]) + self.assertEqual(sum(event["args"][0] == "pull" for event in self.events()), 1) + + def test_numeric_runner_fallback_and_failure_status(self): + """Cleanup and ownership recovery must not turn failed tests green.""" + result = self.run_launcher( + PPU_CI_DEVICE="", NVIDIA_VISIBLE_DEVICES=self.device, TEST_EXIT="29" + ) + self.assertEqual(result.returncode, 29, result.stdout + result.stderr) + create = self.assert_lifecycle() + self.assertIn(f"--device=/dev/alixpu_ppu{self.device}", create) + self.assertFalse(any(event["args"][0] == "pull" for event in self.events())) + self.assertEqual(list(self.home.iterdir()), []) + + def start_blocked(self, **updates): + workflow = yaml.safe_load(WORKFLOW.read_text()) + step = next( + step + for step in workflow["jobs"]["ppu-sanity"]["steps"] + if step.get("name") + == "Run both speculative sanity files in isolated Docker" + ) + env = { + **self.env, + "BLOCK_TEST": "1", + "RUNNER_TEMP": str(self.root / "runner-a"), + **updates, + } + for key in step["env"]: + env[key] = env.pop(key.removeprefix("CONFIG_"), "") + # Sourcing prevents bash -c's implicit exec from masking the wrapper bug. + step_script = self.root / "workflow-step.sh" + step_script.write_text(step["run"]) + process = subprocess.Popen( + [ + "bash", + "-e", + "-o", + "pipefail", + "-c", + 'source "$1"', + "workflow-step", + str(step_script), + ], + cwd=self.source, + env=env, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + start_new_session=True, + ) + + def cleanup(): + # A broken wrapper may exit before its children release pipes and locks. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.communicate(timeout=5) + + self.addCleanup(cleanup) + readable, _, _ = select.select([self.ready], [], [], 10) + if not readable and process.poll() is not None: + output, errors = process.communicate(timeout=1) + self.fail(f"workflow exited before container start: {output}{errors}") + self.assertTrue(readable, "launcher did not reach attached container start") + self.assertEqual(os.read(self.ready, 100), b"started\n") + return process + + def test_contention_does_not_touch_other_container(self): + """Different RUNNER_TEMP values must still serialize the same physical card.""" + first = self.start_blocked() + before = self.events() + result = self.run_launcher(RUNNER_TEMP=str(self.root / "runner-b")) + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn("busy", result.stderr) + self.assertEqual(self.events(), before) + self.assertIsNone(first.poll()) + first.terminate() + first.communicate(timeout=10) + self.assertEqual(first.returncode, 143) + self.assert_lifecycle() + + def assert_workflow_cancellation(self, sig, code, **updates): + process = self.start_blocked(**updates) + started = time.monotonic() + process.send_signal(sig) + try: + output, errors = process.communicate(timeout=CANCELLATION_BUDGET) + except subprocess.TimeoutExpired: + self.fail( + "workflow cancellation did not finish cleanup before the " + f"{CANCELLATION_BUDGET}s budget; status={process.poll()}, " + f"Docker events={self.events()}" + ) + elapsed = time.monotonic() - started + self.assertEqual(process.returncode, code, output + errors) + self.assertLess(elapsed, CANCELLATION_BUDGET) + self.assert_lifecycle() + return elapsed + + def test_pull_cancellation_preserves_private_diagnostics(self): + for sig, code in ((signal.SIGINT, 130), (signal.SIGTERM, 143)): + with self.subTest(signal=sig): + process = self.start_blocked(MISSING_IMAGE="1", BLOCK_PULL="1") + process.send_signal(sig) + output, errors = process.communicate(timeout=CANCELLATION_BUDGET) + self.assertEqual(process.returncode, code, output + errors) + self.assert_private_pull_log(output) + self.assert_image_reference_is_private( + subprocess.CompletedProcess([], code, output, errors) + ) + self.assertFalse( + any(event["args"][0] == "create" for event in self.events()) + ) + with self.assertRaises(ProcessLookupError): + os.kill(int((self.root / "pull.pid").read_text()), 0) + with self.lock.open("a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + + def test_workflow_sigterm_cleans_up_before_unlocking(self): + """Signalling the step PID must not orphan its attached child launcher.""" + self.assert_workflow_cancellation(signal.SIGTERM, 143) + + def test_workflow_sigint_cleans_up_before_unlocking(self): + """GitHub's initial INT must reach cleanup without waiting for inference.""" + self.assert_workflow_cancellation(signal.SIGINT, 130) + + def test_workflow_cancellation_with_delayed_container_term(self): + """A PID 1 deferring TERM must not consume the runner's force-kill budget.""" + elapsed = self.assert_workflow_cancellation( + signal.SIGINT, 130, DELAY_CONTAINER_TERM="1" + ) + delay = json.loads((self.root / "stop-delay.json").read_text()) + self.assertGreater(delay["grace"], 0) + self.assertGreaterEqual(delay["elapsed"], delay["grace"]) + self.assertGreaterEqual(elapsed, delay["elapsed"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/ci/ppu/test_ppu_ci_suite.py b/scripts/ci/ppu/test_ppu_ci_suite.py new file mode 100644 index 0000000000..9a3ce4463c --- /dev/null +++ b/scripts/ci/ppu/test_ppu_ci_suite.py @@ -0,0 +1,499 @@ +import fnmatch +import hashlib +import importlib.util +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import yaml + +from sglang.test.ci.ci_register import HWBackend, collect_tests, ut_parse_one_file +from sglang.test.test_utils import CustomTestCase + +RUNNER = Path(__file__).resolve().parents[3] / "test/run_suite.py" + + +class TestPPUCISuite(CustomTestCase): + def test_manual_checks_are_not_ci_registered(self): + files = list(Path(__file__).parent.glob("test_ppu_ci_*.py")) + self.assertCountEqual( + [path.name for path in files], + [ + "test_ppu_ci_dependencies.py", + "test_ppu_ci_docker.py", + "test_ppu_ci_suite.py", + ], + ) + for path in files: + with self.subTest(path=path.name): + self.assertEqual(ut_parse_one_file(str(path)), ([], True)) + self.assertEqual( + list((RUNNER.parent / "registered").rglob("test_ppu_ci_*.py")), [] + ) + + def test_ppu_suite_contains_both_speculative_sanity_files(self): + registered = RUNNER.parent / "registered" + files = [ + str(path) + for path in registered.rglob("*.py") + if path.name not in ("conftest.py", "__init__.py") + ] + tests = collect_tests(files) + ppu_tests = [ + test + for test in tests + if test.backend == HWBackend.PPU + and test.effective_suite == "stage-a-test-1-gpu-ppu" + and not test.disabled + ] + self.assertCountEqual( + [ + Path(test.filename).relative_to(registered).as_posix() + for test in ppu_tests + ], + ["core/test_basic_sanity_eagle3.py", "core/test_basic_sanity_dflash.py"], + ) + + def test_runtime_requires_both_sanity_files_to_pass(self): + source = Path(__file__).with_name("build_and_test.sh").read_text() + marker = 'cd "$artifacts"\n' + self.assertIn(marker, source) + script = ( + "\n".join(source.splitlines()[:2]) + + "\n" + + marker + + source.split(marker, 1)[1] + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "repo with spaces" + (root / "test").mkdir(parents=True) + artifacts = root / "artifacts" + artifacts.mkdir() + (root / "test/run_suite.py").write_text( + "import os, sys\n" + "print(os.environ['FIXTURE_SUMMARY'], file=sys.stderr)\n" + "sys.exit(int(os.environ['FIXTURE_EXIT']))\n" + ) + for summary, exit_code, expected in ( + ("Test Summary: 2/2 passed", 0, 0), + ("Test Summary: 0/0 passed", 0, 1), + ("Test Summary: 1/1 passed", 0, 1), + ("Test Summary: 1/2 passed", 0, 1), + ("Test Summary: 3/3 passed", 0, 1), + ("Test Summary: 2/2 passed", 7, 7), + ("Test Summary: 2/2 passed (incomplete)", 0, 1), + ("", 0, 1), + ): + with self.subTest(summary=summary, exit_code=exit_code): + result = subprocess.run( + ["bash", "-c", script], + env=dict( + os.environ, + repo=str(root), + artifacts=str(artifacts), + FIXTURE_SUMMARY=summary, + FIXTURE_EXIT=str(exit_code), + ), + capture_output=True, + text=True, + timeout=10, + ) + self.assertEqual( + result.returncode, expected, result.stdout + result.stderr + ) + + +class TestPPUCIWorkflow(CustomTestCase): + @classmethod + def setUpClass(cls): + path = RUNNER.parent.parent / ".github/workflows/pr-test-ppu.yml" + cls.jobs = yaml.safe_load(path.read_text())["jobs"] + + def test_runtime_image_is_only_configured_by_runner_environment(self): + path = RUNNER.parent.parent / ".github/workflows/pr-test-ppu.yml" + workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader) + for event in ("workflow_dispatch", "workflow_call"): + self.assertNotIn("runtime_image", workflow["on"][event]["inputs"]) + self.assertNotIn("PPU_CI_RUNTIME_IMAGE", path.read_text()) + + def test_shared_ci_changes_do_not_require_ppu_labels(self): + """Shared CI edits must not opt unrelated PRs into the PPU label gate.""" + step = next( + step + for step in self.jobs["check-changes"]["steps"] + if step.get("id") == "filter" + ) + patterns = yaml.safe_load(step["with"]["filters"])["ppu"] + for path, expected in ( + ("python/sglang/test/ci/ci_register.py", False), + ("python/sglang/test/ci/ci_utils.py", False), + ("test/run_suite.py", False), + (".github/workflows/pr-test-ppu.yml", True), + ("scripts/ci/ppu/run_test.sh", True), + ("python/sglang/srt/platforms/sail.py", True), + ("scripts/ci/ppu/test_ppu_ci_suite.py", True), + ): + with self.subTest(path=path): + self.assertEqual( + any(fnmatch.fnmatchcase(path, pattern) for pattern in patterns), + expected, + ) + + def test_device_jobs_require_build_but_not_manual_checks(self): + self.assertNotIn("ppu-ci-selftest", self.jobs) + self.assertCountEqual( + self.jobs["ppu-build"]["needs"], ["check-changes", "pr-gate"] + ) + self.assertCountEqual( + self.jobs["ppu-sanity"]["needs"], ["check-changes", "pr-gate", "ppu-build"] + ) + self.assertCountEqual( + self.jobs["pr-test-ppu-finish"]["needs"], + ["pr-gate", "check-changes", "ppu-build", "ppu-sanity"], + ) + self.assertEqual( + self.jobs["ppu-sanity"]["if"], "needs.check-changes.outputs.ppu == 'true'" + ) + self.assertEqual( + self.jobs["pr-test-ppu-finish"]["if"], + "always() && needs.check-changes.result != 'skipped'", + ) + runtime = RUNNER.parent.parent / "scripts/ci/ppu/build_and_test.sh" + self.assertNotIn("--hw cpu", runtime.read_text()) + + def test_jobs_check_out_the_triggering_ref_and_verify_the_pinned_sha(self): + # Device jobs check out the triggering ref like the other PR test + # workflows; the scripts' HEAD == PPU_CI_SOURCE_SHA checks are covered by + # test_build_rejects_wrong_revision_and_uncommitted_inputs below and by + # test_source_identity_includes_untracked_and_ignored_inputs in + # test_ppu_ci_docker.py. + expected = self.jobs["check-changes"]["steps"][0]["with"]["ref"] + self.assertEqual(expected, "${{ inputs.ref || github.sha }}") + for name in ("ppu-build", "ppu-sanity"): + with self.subTest(job=name): + job = self.jobs[name] + checkout = next( + step + for step in job["steps"] + if step.get("uses", "").startswith("actions/checkout@") + ) + self.assertEqual(checkout["with"]["ref"], expected) + self.assertEqual( + job["env"]["PPU_CI_SOURCE_SHA"], + "${{ needs.check-changes.outputs.source-sha }}", + ) + + def test_sanity_runs_on_every_ppu_generation_with_distinct_artifacts(self): + sanity = self.jobs["ppu-sanity"] + self.assertEqual(sanity["runs-on"], "${{ matrix.runner }}") + self.assertIs(sanity["strategy"]["fail-fast"], False) + self.assertEqual( + sanity["strategy"]["matrix"]["runner"], ["8-ppu-m890p", "16-ppu-zw810e"] + ) + self.assertIn("matrix.runner", sanity["name"]) + upload = next( + step + for step in sanity["steps"] + if step.get("name") == "Upload runtime diagnostics" + ) + self.assertIn("${{ matrix.runner }}", upload["with"]["name"]) + + def test_finish_requires_successful_build_and_sanity_when_in_scope(self): + finish = self.jobs["pr-test-ppu-finish"]["steps"][0] + statuses = ("success", "failure", "cancelled", "skipped") + for build in statuses: + for sanity in statuses: + for in_scope in (True, False): + with self.subTest(build=build, sanity=sanity, in_scope=in_scope): + needs = { + name: {"result": "success"} + for name in self.jobs["pr-test-ppu-finish"]["needs"] + } + needs["ppu-build"] = {"result": build} + needs["ppu-sanity"] = {"result": sanity} + result = subprocess.run( + ["bash", "-e", "-o", "pipefail", "-c", finish["run"]], + env=dict( + os.environ, + NEEDS_JSON=json.dumps(needs), + PPU_IN_SCOPE=str(in_scope).lower(), + BUILD_RESULT=build, + SANITY_RESULT=sanity, + ), + capture_output=True, + text=True, + timeout=10, + ) + allowed = {"success"} if in_scope else {"success", "skipped"} + self.assertEqual( + result.returncode == 0, + build in allowed and sanity in allowed, + result.stdout + result.stderr, + ) + for variable, job in ( + ("BUILD_RESULT", "ppu-build"), + ("SANITY_RESULT", "ppu-sanity"), + ): + self.assertEqual(finish["env"][variable], "${{ needs." + job + ".result }}") + + +class TestPPUManualSelftests(CustomTestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + self.repo = self.root / "repo with spaces" + directory = self.repo / "scripts/ci/ppu" + directory.mkdir(parents=True) + self.script = directory / "run_selftests.sh" + source = Path(__file__).with_name("run_selftests.sh") + self.assertTrue(source.is_file(), "Manual selftest entry point is missing") + self.script.write_bytes(source.read_bytes()) + self.files = [ + "test_ppu_ci_dependencies.py", + "test_ppu_ci_docker.py", + "test_ppu_ci_suite.py", + ] + self.result_path = self.root / "executed.jsonl" + self.env = dict( + os.environ, + FIXTURE_RESULTS=str(self.result_path), + FIXTURE_FAILURE="", + SGLANG_IS_IN_CI="1", + SGLANG_TEST_MAX_RETRY="9", + PYTHONDONTWRITEBYTECODE="0", + HF_HUB_OFFLINE="0", + PYTHONPATH=str(self.root / "installed"), + ) + for folder, value in ( + (self.repo / "python", "source"), + (self.root / "installed", "installed"), + ): + folder.mkdir() + (folder / "selftest_fixture.py").write_text(f"ORIGIN = {value!r}\n") + for name in self.files: + (directory / name).write_text( + "import json, os, unittest\n" + "from pathlib import Path\n" + "from selftest_fixture import ORIGIN\n" + "class Check(unittest.TestCase):\n" + " def test_environment(self):\n" + " with open(os.environ['FIXTURE_RESULTS'], 'a') as output:\n" + " output.write(json.dumps(Path(__file__).name) + '\\n')\n" + " self.assertEqual(ORIGIN, 'source')\n" + " for key, value in {'SGLANG_IS_IN_CI': '0', 'SGLANG_TEST_MAX_RETRY': '0',\n" + " 'HF_HUB_OFFLINE': '1',\n" + " 'PYTHONDONTWRITEBYTECODE': '1'}.items():\n" + " self.assertEqual(os.environ[key], value)\n" + " self.assertNotEqual(Path(__file__).name, os.environ['FIXTURE_FAILURE'])\n" + "unittest.main()\n" + ) + + def run_entry(self, env=None): + return subprocess.run( + [shutil.which("bash"), str(self.script)], + cwd=self.root, + env=self.env if env is None else env, + capture_output=True, + text=True, + timeout=15, + ) + + def test_runs_all_files_from_unrelated_working_directory(self): + result = self.run_entry() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual( + [json.loads(line) for line in self.result_path.read_text().splitlines()], + self.files, + ) + self.assertEqual(result.stderr.count("Ran 1 test"), 3) + self.assertEqual(list(self.repo.rglob("__pycache__")), []) + + def test_stops_and_propagates_test_failure_or_missing_file(self): + target = self.script.parent / self.files[1] + original = target.read_bytes() + for failure, code in (("assertion", 1), ("exit", 7), ("missing", 2)): + with self.subTest(failure=failure): + target.write_bytes(original) + self.result_path.write_text("") + self.env["FIXTURE_FAILURE"] = target.name + if failure == "exit": + target.write_text("import sys\nsys.exit(7)\n") + elif failure == "missing": + target.unlink() + result = self.run_entry() + self.assertEqual(result.returncode, code, result.stdout + result.stderr) + executed = self.result_path.read_text() + self.assertIn(self.files[0], executed) + self.assertNotIn(self.files[2], executed) + + def test_missing_prerequisites_fail_before_running_tests(self): + tools = self.root / "tools" + tools.mkdir() + uname = tools / "uname" + uname.write_text("#!/bin/sh\nprintf '%s\\n' Linux\n") + uname.chmod(0o755) + commands = ("flock", "git", "jq", "python3") + for name in commands: + (tools / name).symlink_to(shutil.which(name)) + for missing in ("Linux", *commands): + with self.subTest(missing=missing): + if missing == "Linux": + uname.write_text("#!/bin/sh\nprintf '%s\\n' Darwin\n") + else: + (tools / missing).unlink() + result = self.run_entry(dict(self.env, PATH=str(tools))) + self.assertNotEqual(result.returncode, 0, result.stdout) + self.assertIn(missing, result.stderr) + self.assertFalse(self.result_path.exists()) + if missing == "Linux": + uname.write_text("#!/bin/sh\nprintf '%s\\n' Linux\n") + else: + (tools / missing).symlink_to(shutil.which(missing)) + + +class TestPPURuntimeCache(CustomTestCase): + @classmethod + def setUpClass(cls): + path = RUNNER.parent.parent / "scripts/ci/ppu/prepare_runtime.py" + spec = importlib.util.spec_from_file_location("ppu_prepare_runtime", path) + cls.prepare = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.prepare) + + def test_hub_ref_resolves_offline_without_writing_checkpoint(self): + """A newline in refs/main makes offline hub lookups miss the snapshot.""" + from huggingface_hub import hf_hub_download + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + checkpoint = root / "checkpoint" + checkpoint.mkdir() + (checkpoint / "config.json").write_text('{"model_type": "llama"}') + hub = root / "hub" + self.prepare.prepare_model_cache(hub, {"test/model": checkpoint}) + resolved = hf_hub_download( + "test/model", "config.json", cache_dir=hub, local_files_only=True + ) + self.assertEqual(Path(resolved).resolve(), checkpoint / "config.json") + self.assertEqual(list(checkpoint.iterdir()), [checkpoint / "config.json"]) + + def test_eval_cache_copy_is_independent_and_rejects_corruption(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source" + (source / "mmlu").mkdir(parents=True) + data = source / "mmlu/test.jsonl" + marker = source / "mmlu/test.jsonl.sha256" + content = b'{"question": "fixture"}\n' + digest = hashlib.sha256(content).hexdigest() + data.write_bytes(content) + marker.write_text(digest + "\n") + with patch.object(self.prepare, "MMLU_SHA256", digest): + destination = root / "private" + self.prepare.prepare_mmlu_cache(source, destination) + copied = destination / "mmlu/test.jsonl" + self.assertFalse(copied.is_symlink()) + self.assertFalse(copied.samefile(data)) + self.assertEqual(copied.read_bytes(), content) + copied.write_text("private cache update") + self.assertEqual(data.read_bytes(), content) + for corrupt in (data, marker): + with self.subTest(corrupt=corrupt.name): + original = corrupt.read_bytes() + corrupt.write_text("corrupted") + with self.assertRaisesRegex(ValueError, "MMLU"): + self.prepare.prepare_mmlu_cache(source, root / "rejected") + self.assertFalse((root / "rejected").exists()) + corrupt.write_bytes(original) + marker.unlink() + with self.assertRaises(FileNotFoundError): + self.prepare.prepare_mmlu_cache(source, root / "missing") + + +class TestPPUBuildProvenance(CustomTestCase): + def test_build_rejects_wrong_revision_and_uncommitted_inputs(self): + """HEAD alone cannot identify a build that also consumes uncommitted files.""" + source = RUNNER.parent.parent / "scripts/ci/ppu/build_and_test.sh" + for state in ("revision", "tracked", "untracked", "ignored"): + with self.subTest(state=state), tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + repo = root / "repo" + script = repo / "scripts/ci/ppu/build_and_test.sh" + script.parent.mkdir(parents=True) + script.write_bytes(source.read_bytes()) + (repo / ".gitignore").write_text("ignored\n") + (repo / "tracked").write_text("committed") + wheels = root / "wheels" + wheels.mkdir() + env = dict( + os.environ, + GIT_CONFIG_GLOBAL=os.devnull, + GIT_CONFIG_NOSYSTEM="1", + GIT_AUTHOR_NAME="Fixture", + GIT_AUTHOR_EMAIL="fixture@example.invalid", + GIT_COMMITTER_NAME="Fixture", + GIT_COMMITTER_EMAIL="fixture@example.invalid", + PPU_CI_ARTIFACT_DIR=str(root / "artifacts"), + PPU_CI_WHEEL_DIR=str(wheels), + PPU_SDK=str(root / "missing-sdk"), + ) + for args in ( + ("init", "-q"), + ("add", "."), + ("commit", "-qm", "fixture"), + ): + subprocess.run(["git", "-C", str(repo), *args], env=env, check=True) + sha = subprocess.check_output( + ["git", "-C", str(repo), "rev-parse", "HEAD"], env=env, text=True + ).strip() + env["PPU_CI_SOURCE_SHA"] = "0" * 40 if state == "revision" else sha + if state != "revision": + (repo / state).write_text("uncommitted") + result = subprocess.run( + ["bash", str(script), "build"], + env=env, + capture_output=True, + text=True, + timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Source checkout", result.stdout + result.stderr) + + def test_runtime_rejects_unlisted_wheel_before_installation(self): + """A valid manifest must not leave additional installable wheels unchecked.""" + script = RUNNER.parent.parent / "scripts/ci/ppu/build_and_test.sh" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + wheels = root / "wheels" + (wheels / "runtime-deps").mkdir(parents=True) + files = ("source-sha.txt", "./sglang.whl", "./runtime-deps/sailify.whl") + manifest = [] + for name in files: + content = b"fixture" + (wheels / name).write_bytes(content) + manifest.append(f"{hashlib.sha256(content).hexdigest()} {name}\n") + (wheels / "SHA256SUMS").write_text("".join(manifest)) + (wheels / "unchecked.whl").write_text("not covered by the manifest") + result = subprocess.run( + ["bash", str(script), "test"], + env=dict( + os.environ, + PPU_CI_SOURCE_SHA="fixture", + PPU_CI_ARTIFACT_DIR=str(root / "artifacts"), + PPU_CI_WHEEL_DIR=str(wheels), + ), + capture_output=True, + text=True, + timeout=30, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("Wheel manifest", result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/registered/core/test_basic_sanity_dflash.py b/test/registered/core/test_basic_sanity_dflash.py index 45f5eeedb3..470227b49c 100644 --- a/test/registered/core/test_basic_sanity_dflash.py +++ b/test/registered/core/test_basic_sanity_dflash.py @@ -5,7 +5,7 @@ test_basic_sanity.py / test_basic_sanity_eagle3.py with the DFLASH path active import unittest from sglang.srt.utils import kill_process_tree -from sglang.test.ci.ci_register import register_cuda_ci +from sglang.test.ci.ci_register import register_cuda_ci, register_ppu_ci from sglang.test.kits.basic_api_contract_kit import BasicAPIContractMixin from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin from sglang.test.kits.basic_scheduler_stress_kit import BasicSchedulerStressMixin @@ -22,6 +22,8 @@ from sglang.test.test_utils import ( ) register_cuda_ci(est_time=135, stage="base-a", runner_config="1-gpu-small") +# backend-specific: SAIL DFLASH verification kernels, decode graphs, and sampling masks. +register_ppu_ci(est_time=450, suite="stage-a-test-1-gpu-ppu") class TestBasicSanityDFlash( diff --git a/test/registered/core/test_basic_sanity_eagle3.py b/test/registered/core/test_basic_sanity_eagle3.py index 1ad5185a10..4e664e13f6 100644 --- a/test/registered/core/test_basic_sanity_eagle3.py +++ b/test/registered/core/test_basic_sanity_eagle3.py @@ -4,7 +4,11 @@ test_basic_sanity.py with the spec-decoding path active.""" import unittest from sglang.srt.utils import kill_process_tree -from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci +from sglang.test.ci.ci_register import ( + register_amd_ci, + register_cuda_ci, + register_ppu_ci, +) from sglang.test.kits.basic_api_contract_kit import BasicAPIContractMixin from sglang.test.kits.basic_decode_correctness_kit import BasicDecodeCorrectnessMixin from sglang.test.kits.basic_scheduler_stress_kit import BasicSchedulerStressMixin @@ -22,6 +26,8 @@ from sglang.test.test_utils import ( register_cuda_ci(est_time=167, stage="base-a", runner_config="1-gpu-small") register_amd_ci(est_time=200, suite="stage-a-test-1-gpu-small-amd") +# backend-specific: SAIL EAGLE3 kernels, decode graphs, and device-timer occupancy. +register_ppu_ci(est_time=350, suite="stage-a-test-1-gpu-ppu") class TestBasicSanityEagle3( diff --git a/test/registered/unit/platforms/test_platform_interface.py b/test/registered/unit/platforms/test_platform_interface.py index 35249d37ba..b7b3ca6f13 100644 --- a/test/registered/unit/platforms/test_platform_interface.py +++ b/test/registered/unit/platforms/test_platform_interface.py @@ -10,6 +10,7 @@ from unittest.mock import MagicMock, patch import torch from sglang import _platform_stubs +from sglang.kernels.jit.utils.arch import _sail_arch_suffix from sglang.srt.platforms import _load_platform_class, _resolve_platform, interface from sglang.srt.platforms.cpu import CpuSRTPlatform from sglang.srt.platforms.cuda import CudaSRTPlatform @@ -23,6 +24,7 @@ from sglang.srt.platforms.interface import SRTPlatform from sglang.srt.platforms.mps import MpsSRTPlatform from sglang.srt.platforms.npu import NPUSRTPlatform from sglang.srt.platforms.rocm import RocmSRTPlatform +from sglang.srt.platforms.sail import SailSRTPlatform from sglang.srt.platforms.xpu import XpuSRTPlatform from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase @@ -233,6 +235,36 @@ class TestCudaDeviceMixin(CustomTestCase): mock_cuda_seed.assert_called_once_with(123) +class TestSailDeviceMixin(CustomTestCase): + """Tests for SAIL device operation defaults (CUDA-compatible surface).""" + + def test_sail_identity_overrides_cuda_identity(self): + base = SailSRTPlatform() + self.assertEqual(base._enum, PlatformEnum.SAIL) + self.assertEqual(base.device_name, "sail") + # device_type stays "cuda" — torch.device("cuda") is the only valid + # device-type string for SAIL devices in PyTorch. + self.assertEqual(base.device_type, "cuda") + self.assertTrue(base.is_sail()) + self.assertTrue(base.is_cuda_alike()) + + def test_sail_srt_platform_capabilities(self): + base = SailSRTPlatform() + self.assertTrue(base.capabilities.supports_triton) + self.assertTrue(base.capabilities.graph_capture) + self.assertTrue(base.capabilities.piecewise_graph) + + def test_sail_arch_suffix_below_sm89(self): + # SAIL devices below the SM89 capability require the arch-specific + # target variant for JIT compilation. + self.assertEqual(_sail_arch_suffix(8, 0), "a") + self.assertEqual(_sail_arch_suffix(8, 8), "a") + + def test_sail_arch_suffix_sm89_and_above(self): + self.assertEqual(_sail_arch_suffix(8, 9), "") + self.assertEqual(_sail_arch_suffix(9, 0), "") + + class TestXpuDeviceMixin(CustomTestCase): """Tests for XPU device operation defaults.""" diff --git a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py index bcfc5f8435..3969b04b87 100644 --- a/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py +++ b/test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py @@ -6,6 +6,7 @@ tests check that the pre-allocated `parent_list` / `top_scores_index` match the slow path (`organize_draft_results`) for num_steps in {1, 2, 3, 4}. """ +import builtins import contextlib import unittest from types import SimpleNamespace @@ -264,6 +265,7 @@ class TestEagleWorkerV2BackendFallback(CustomTestCase): self.assertEqual(worker.draft_forward.called, not expect_graph) def test_preserves_initialized_backend_when_draft_extend_backend_is_unset(self): + """Non-QSA initialization must work without optional QSA dependencies.""" worker = object.__new__(EagleDraftWorker) existing_backend = object() decode_backend = object() @@ -276,10 +278,19 @@ class TestEagleWorkerV2BackendFallback(CustomTestCase): worker.topk = 1 worker.speculative_num_steps = 2 worker.seed_dsa_topk_from_draft_extend = False + real_import = builtins.__import__ - with patch( - "sglang.srt.speculative.eagle_worker_v2.DraftBackendFactory", - _make_backend_factory(decode_backend, None), + def import_without_qsa(name, *args, **kwargs): + if name == "sglang.srt.layers.attention.qsa.qsa_indexer": + raise OSError("Optional QSA dependency is unavailable") + return real_import(name, *args, **kwargs) + + with ( + patch("builtins.__import__", new=import_without_qsa), + patch( + "sglang.srt.speculative.eagle_worker_v2.DraftBackendFactory", + _make_backend_factory(decode_backend, None), + ), ): worker.init_attention_backend() diff --git a/test/run_suite.py b/test/run_suite.py index b26d045ad3..c56b709508 100644 --- a/test/run_suite.py +++ b/test/run_suite.py @@ -132,14 +132,9 @@ PER_COMMIT_SUITES = { # stage-b needs a self-hosted Apple Silicon runner; dispatched manually. "stage-b-e2e-mps", ], - # PPU has no suite in any of the three dicts yet: pr-test-ppu.yml only runs - # the runner preflight until the PPU SRT platform and AOT kernels land. - # Declaring a name here before a workflow dispatches it would let a test - # register, validate, and count as covered while never running, so each PPU - # suite name arrives with the job that runs it. Until then PPU is in - # _SUITE_CHECKED_BACKENDS with no valid suite, so validate_all_suites() - # rejects any register_ppu_ci() outright. - HWBackend.PPU: [], + HWBackend.PPU: [ + "stage-a-test-1-gpu-ppu", + ], } # Nightly test suites (run nightly, organized by GPU configuration)