|
| 1 | +# Copyright (c) Facebook, Inc. and its affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | +"""Anonymous feature-usage telemetry for bitsandbytes. |
| 6 | +
|
| 7 | +Sends one HEAD request per distinct feature per process via |
| 8 | +`huggingface_hub.utils.send_telemetry()`. Data lands in the Hugging Face |
| 9 | +Hub telemetry index under `path_prefix == "/api/telemetry/bitsandbytes/"` |
| 10 | +and informs maintenance and deprecation decisions. |
| 11 | +
|
| 12 | +What is collected |
| 13 | + - Session fingerprint (once per process, first feature use): |
| 14 | + bnb version, OS name/version, CPU arch, glibc version, Python/torch |
| 15 | + versions, accelerator vendor/name/arch/count. |
| 16 | + - Per-feature events: feature name plus feature-specific metadata |
| 17 | + (e.g. `quant_type="nf4"`, `bits="8"`, `paged="true"`). |
| 18 | +
|
| 19 | +What is NOT collected |
| 20 | + Model names, file paths, parameter shapes, user identifiers, training |
| 21 | + data, gradient values, or any value derived from user input. |
| 22 | +
|
| 23 | +Automatically disabled when running under pytest (detected via |
| 24 | +`pytest` in `sys.modules` or `PYTEST_CURRENT_TEST` env var) so that test |
| 25 | +runs in CI and locally do not pollute the real-usage stream. |
| 26 | +
|
| 27 | +Opt-out (any of the following env vars disables all telemetry): |
| 28 | + - BNB_DISABLE_TELEMETRY=1 (bitsandbytes only) |
| 29 | + - HF_HUB_DISABLE_TELEMETRY=1 (all HF libraries) |
| 30 | + - HF_HUB_OFFLINE=1 (all HF libraries) |
| 31 | +
|
| 32 | +End-to-end verification: |
| 33 | + Set `BNB_TELEMETRY_TAG=<some-id>` before importing bitsandbytes and the |
| 34 | + value is attached as `bitsandbytes.tag` on every event. Use this to |
| 35 | + correlate a single run's events in ES. |
| 36 | +
|
| 37 | +No-ops silently if `huggingface_hub` is not installed, and never raises. |
| 38 | +
|
| 39 | +Keys are namespaced under `bitsandbytes.*` in the resulting |
| 40 | +`metadata.bitsandbytes.*` fields so they do not collide with fields logged |
| 41 | +by other libraries in the shared telemetry index. |
| 42 | +""" |
| 43 | + |
| 44 | +from __future__ import annotations |
| 45 | + |
| 46 | +import logging |
| 47 | +import os |
| 48 | +import platform |
| 49 | +import sys |
| 50 | +from typing import Optional |
| 51 | + |
| 52 | +logger = logging.getLogger(__name__) |
| 53 | + |
| 54 | +_REPORTED: set[str] = set() |
| 55 | +_FINGERPRINT: Optional[dict[str, str]] = None |
| 56 | + |
| 57 | +_TRUTHY = frozenset({"1", "true", "yes", "on"}) |
| 58 | + |
| 59 | + |
| 60 | +def _is_pytest() -> bool: |
| 61 | + """Detect whether we are running inside a pytest process. |
| 62 | +
|
| 63 | + Telemetry is suppressed during test runs so that CI and local test |
| 64 | + invocations don't pollute the real-usage stream. Tests that want to |
| 65 | + assert on telemetry behavior monkey-patch this function to return False. |
| 66 | + """ |
| 67 | + return "pytest" in sys.modules or "PYTEST_CURRENT_TEST" in os.environ |
| 68 | + |
| 69 | + |
| 70 | +def _is_disabled() -> bool: |
| 71 | + for var in ("BNB_DISABLE_TELEMETRY", "HF_HUB_DISABLE_TELEMETRY", "HF_HUB_OFFLINE"): |
| 72 | + if os.environ.get(var, "").strip().lower() in _TRUTHY: |
| 73 | + return True |
| 74 | + if _is_pytest(): |
| 75 | + return True |
| 76 | + return False |
| 77 | + |
| 78 | + |
| 79 | +def _os_info() -> tuple[str, str]: |
| 80 | + os_name = platform.system() |
| 81 | + os_name = {"Darwin": "macOS"}.get(os_name, os_name) |
| 82 | + if os_name == "Windows": |
| 83 | + try: |
| 84 | + build = sys.getwindowsversion().build |
| 85 | + os_version = f"11 (build {build})" if build >= 22000 else f"10 (build {build})" |
| 86 | + except Exception: |
| 87 | + os_version = platform.release() |
| 88 | + elif os_name == "macOS": |
| 89 | + os_version = platform.mac_ver()[0] or platform.release() |
| 90 | + else: |
| 91 | + os_version = platform.release() |
| 92 | + return os_name, os_version |
| 93 | + |
| 94 | + |
| 95 | +def _accel_info() -> dict[str, str]: |
| 96 | + info: dict[str, str] = {} |
| 97 | + try: |
| 98 | + import torch |
| 99 | + except ImportError: |
| 100 | + info["bitsandbytes.accel"] = "unknown" |
| 101 | + return info |
| 102 | + |
| 103 | + try: |
| 104 | + if torch.cuda.is_available(): |
| 105 | + vendor = "amd" if getattr(torch.version, "hip", None) else "nvidia" |
| 106 | + info["bitsandbytes.accel"] = vendor |
| 107 | + info["bitsandbytes.accel_count"] = str(torch.cuda.device_count()) |
| 108 | + props = torch.cuda.get_device_properties(0) |
| 109 | + info["bitsandbytes.accel_name"] = props.name |
| 110 | + if vendor == "nvidia": |
| 111 | + info["bitsandbytes.accel_arch"] = f"sm_{props.major}{props.minor}" |
| 112 | + else: |
| 113 | + info["bitsandbytes.accel_arch"] = getattr(props, "gcnArchName", "unknown") |
| 114 | + return info |
| 115 | + |
| 116 | + if hasattr(torch, "xpu") and torch.xpu.is_available(): |
| 117 | + info["bitsandbytes.accel"] = "xpu" |
| 118 | + info["bitsandbytes.accel_count"] = str(torch.xpu.device_count()) |
| 119 | + try: |
| 120 | + info["bitsandbytes.accel_name"] = torch.xpu.get_device_properties(0).name |
| 121 | + except Exception: |
| 122 | + pass |
| 123 | + return info |
| 124 | + |
| 125 | + if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): |
| 126 | + info["bitsandbytes.accel"] = "mps" |
| 127 | + return info |
| 128 | + |
| 129 | + if hasattr(torch, "hpu") and torch.hpu.is_available(): |
| 130 | + info["bitsandbytes.accel"] = "hpu" |
| 131 | + return info |
| 132 | + except Exception: |
| 133 | + pass |
| 134 | + |
| 135 | + info["bitsandbytes.accel"] = "cpu" |
| 136 | + return info |
| 137 | + |
| 138 | + |
| 139 | +def _fingerprint() -> dict[str, str]: |
| 140 | + global _FINGERPRINT |
| 141 | + if _FINGERPRINT is not None: |
| 142 | + return _FINGERPRINT |
| 143 | + |
| 144 | + try: |
| 145 | + import bitsandbytes |
| 146 | + |
| 147 | + version = bitsandbytes.__version__ |
| 148 | + except Exception: |
| 149 | + version = "unknown" |
| 150 | + |
| 151 | + os_name, os_version = _os_info() |
| 152 | + info = { |
| 153 | + "bitsandbytes.version": version, |
| 154 | + "bitsandbytes.os": os_name, |
| 155 | + "bitsandbytes.os_version": os_version, |
| 156 | + "bitsandbytes.arch": platform.machine(), |
| 157 | + "bitsandbytes.python": platform.python_version(), |
| 158 | + } |
| 159 | + if os_name == "Linux": |
| 160 | + try: |
| 161 | + libc_name, libc_ver = platform.libc_ver() |
| 162 | + if libc_name: |
| 163 | + info["bitsandbytes.libc"] = f"{libc_name}-{libc_ver}" |
| 164 | + except Exception: |
| 165 | + pass |
| 166 | + try: |
| 167 | + import torch |
| 168 | + |
| 169 | + info["bitsandbytes.torch"] = torch.__version__ |
| 170 | + except ImportError: |
| 171 | + pass |
| 172 | + |
| 173 | + info.update(_accel_info()) |
| 174 | + |
| 175 | + _FINGERPRINT = info |
| 176 | + return info |
| 177 | + |
| 178 | + |
| 179 | +def report_feature(feature: str, details: Optional[dict[str, object]] = None) -> None: |
| 180 | + """Report that a bitsandbytes feature was used. |
| 181 | +
|
| 182 | + Fires at most once per `feature` per process. Subsequent calls with the |
| 183 | + same `feature` are O(1) no-ops. |
| 184 | +
|
| 185 | + Args: |
| 186 | + feature: Short feature name. Becomes the final URL path segment: |
| 187 | + `/api/telemetry/bitsandbytes/{feature}` (so it appears as |
| 188 | + `path_filename` in ES queries). |
| 189 | + details: Optional feature-specific key/value metadata. Keys without a |
| 190 | + `bitsandbytes.` prefix are prefixed automatically. |
| 191 | + """ |
| 192 | + if feature in _REPORTED: |
| 193 | + return |
| 194 | + _REPORTED.add(feature) |
| 195 | + |
| 196 | + if _is_disabled(): |
| 197 | + return |
| 198 | + |
| 199 | + try: |
| 200 | + from huggingface_hub.utils import send_telemetry |
| 201 | + except ImportError: |
| 202 | + return |
| 203 | + |
| 204 | + fingerprint = _fingerprint() |
| 205 | + user_agent = dict(fingerprint) |
| 206 | + user_agent["bitsandbytes.feature"] = feature |
| 207 | + if details: |
| 208 | + for k, v in details.items(): |
| 209 | + key = k if k.startswith("bitsandbytes.") else f"bitsandbytes.{k}" |
| 210 | + user_agent[key] = str(v) |
| 211 | + |
| 212 | + tag = os.environ.get("BNB_TELEMETRY_TAG", "").strip() |
| 213 | + if tag: |
| 214 | + user_agent["bitsandbytes.tag"] = tag |
| 215 | + |
| 216 | + try: |
| 217 | + send_telemetry( |
| 218 | + topic=f"bitsandbytes/{feature}", |
| 219 | + library_name="bitsandbytes", |
| 220 | + library_version=fingerprint.get("bitsandbytes.version", "unknown"), |
| 221 | + user_agent=user_agent, |
| 222 | + ) |
| 223 | + except Exception as e: |
| 224 | + logger.debug("bitsandbytes telemetry send failed: %s", e) |
| 225 | + |
| 226 | + |
| 227 | +def _reset_for_testing() -> None: |
| 228 | + """Clear module state. Intended for use in test fixtures only.""" |
| 229 | + global _FINGERPRINT |
| 230 | + _REPORTED.clear() |
| 231 | + _FINGERPRINT = None |
0 commit comments