|
| 1 | +# Copyright 2026 FlagOS Contributors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Shared fixtures and helpers for the cross-backend profiler contract.""" |
| 16 | + |
| 17 | +import json |
| 18 | +import os |
| 19 | +import tempfile |
| 20 | +from dataclasses import dataclass |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +import pytest |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(frozen=True) |
| 27 | +class ProfilerCapabilities: |
| 28 | + """Observable profiler features expected from the active backend.""" |
| 29 | + |
| 30 | + platform: str |
| 31 | + device: bool |
| 32 | + kernel: bool |
| 33 | + runtime: bool |
| 34 | + memcpy: bool |
| 35 | + memset: bool |
| 36 | + flow: bool |
| 37 | + linkage: bool |
| 38 | + metadata: bool |
| 39 | + |
| 40 | + |
| 41 | +def detect_platform() -> str: |
| 42 | + """Reuse the integration platform conventions for profiler selection.""" |
| 43 | + accelerator = os.environ.get("ACCELERATOR", "").lower() |
| 44 | + if accelerator in {"ascend", "metax", "maca", "musa", "gcu"}: |
| 45 | + return "metax" if accelerator == "maca" else accelerator |
| 46 | + if os.environ.get("PPU_SDK") or os.environ.get("PPU_HOME"): |
| 47 | + return "ppu" |
| 48 | + if Path("/usr/local/PPU_SDK").is_dir(): |
| 49 | + return "ppu" |
| 50 | + |
| 51 | + try: |
| 52 | + import torch_fl |
| 53 | + |
| 54 | + marker = Path(torch_fl.__file__).resolve().parent / "lib" / "flagos_platform" |
| 55 | + platform = marker.read_text().strip().lower() |
| 56 | + if platform: |
| 57 | + return platform |
| 58 | + except (ImportError, OSError): |
| 59 | + pass |
| 60 | + |
| 61 | + config = os.environ.get("FLAGOS_BACKEND_CONFIG", "").lower() |
| 62 | + for platform in ("ascend", "metax", "musa", "gcu", "cuda"): |
| 63 | + if platform in config: |
| 64 | + return platform |
| 65 | + return "cuda" |
| 66 | + |
| 67 | + |
| 68 | +def _torch_device(): |
| 69 | + import torch |
| 70 | + |
| 71 | + return torch.device("flagos", 0) |
| 72 | + |
| 73 | + |
| 74 | +def _torch_module(): |
| 75 | + import torch |
| 76 | + |
| 77 | + return torch |
| 78 | + |
| 79 | + |
| 80 | +def capabilities_for_platform(platform: str) -> ProfilerCapabilities: |
| 81 | + """Describe public profiler features currently emitted by each tracer. |
| 82 | +
|
| 83 | + The capability table is intentionally about observable behavior, not vendor |
| 84 | + library names. Ascend currently exposes CPU/Trace records only in CI; all |
| 85 | + other supported tracers are expected to provide kernel and runtime records. |
| 86 | + """ |
| 87 | + device = platform != "ascend" |
| 88 | + runtime = device |
| 89 | + return ProfilerCapabilities( |
| 90 | + platform=platform, |
| 91 | + device=device, |
| 92 | + kernel=device, |
| 93 | + runtime=runtime, |
| 94 | + memcpy=device and platform in {"cuda", "metax", "ppu"}, |
| 95 | + memset=device and platform in {"cuda", "metax"}, |
| 96 | + flow=device, |
| 97 | + linkage=device, |
| 98 | + metadata=device, |
| 99 | + ) |
| 100 | + |
| 101 | + |
| 102 | +@pytest.fixture(scope="session") |
| 103 | +def profiler_capabilities(): |
| 104 | + """Capabilities for the active hardware/backend.""" |
| 105 | + return capabilities_for_platform(detect_platform()) |
| 106 | + |
| 107 | + |
| 108 | +@pytest.fixture(scope="module") |
| 109 | +def profile_result(): |
| 110 | + """Capture one common workload and export it as a Chrome trace.""" |
| 111 | + torch = _torch_module() |
| 112 | + device = _torch_device() |
| 113 | + x = torch.randn(256, 256, device=device) |
| 114 | + y = torch.randn(256, 256, device=device) |
| 115 | + small = torch.randn(16, device=device) |
| 116 | + |
| 117 | + with torch.profiler.profile( |
| 118 | + activities=[ |
| 119 | + torch.profiler.ProfilerActivity.CPU, |
| 120 | + torch.profiler.ProfilerActivity.PrivateUse1, |
| 121 | + ], |
| 122 | + with_stack=False, |
| 123 | + ) as prof: |
| 124 | + for _ in range(3): |
| 125 | + z = (x @ y).relu() |
| 126 | + torch.sort(small) |
| 127 | + z.sum().item() |
| 128 | + |
| 129 | + with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as trace_file: |
| 130 | + trace_path = Path(trace_file.name) |
| 131 | + try: |
| 132 | + prof.export_chrome_trace(str(trace_path)) |
| 133 | + trace = json.loads(trace_path.read_text()) |
| 134 | + finally: |
| 135 | + trace_path.unlink(missing_ok=True) |
| 136 | + return prof, trace |
| 137 | + |
| 138 | + |
| 139 | +def events_in(trace, category, *, completed_only=True): |
| 140 | + """Return trace events in one category.""" |
| 141 | + events = [ |
| 142 | + event for event in trace.get("traceEvents", []) if event.get("cat") == category |
| 143 | + ] |
| 144 | + if completed_only: |
| 145 | + return [event for event in events if event.get("ph") == "X"] |
| 146 | + return events |
| 147 | + |
| 148 | + |
| 149 | +def event_categories(trace): |
| 150 | + """Return categories for completed trace events.""" |
| 151 | + return { |
| 152 | + event.get("cat") |
| 153 | + for event in trace.get("traceEvents", []) |
| 154 | + if event.get("ph") == "X" |
| 155 | + } |
| 156 | + |
| 157 | + |
| 158 | +def arg_key_union(trace, category): |
| 159 | + """Return the union of argument keys for all events in a category.""" |
| 160 | + keys = set() |
| 161 | + for event in events_in(trace, category): |
| 162 | + keys.update((event.get("args") or {}).keys()) |
| 163 | + return keys |
| 164 | + |
| 165 | + |
| 166 | +def op_name_by_external_id(trace): |
| 167 | + """Map Kineto External ids to CPU operation names.""" |
| 168 | + return { |
| 169 | + (event.get("args") or {}).get("External id"): event.get("name") |
| 170 | + for event in events_in(trace, "cpu_op") |
| 171 | + if (event.get("args") or {}).get("External id") is not None |
| 172 | + } |
0 commit comments