triton-cache-loader 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import os as _os; _os.environ.get("TRITON_CACHE_LOADER_DISABLE") != "1" and __import__("triton_cache_loader.hooks.import_hook").hooks.import_hook.install_lazy_hook()
@@ -0,0 +1,252 @@
1
+ """Architecture-synchronized Triton autotuning & kernel cache preloader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+
8
+ TYPE_CHECKING = False
9
+
10
+ if TYPE_CHECKING:
11
+ from pathlib import Path
12
+ from typing import Any, Dict, Optional, Union
13
+
14
+ from triton_cache_loader.config import CacheMode, LoaderConfig, SyncPolicy
15
+ from triton_cache_loader.engine import HealthCheckReport, PreloadReport
16
+ from triton_cache_loader.engine.exceptions import (
17
+ ArchSyncError,
18
+ BundleNotFoundError,
19
+ CacheMissError,
20
+ CorruptBundleError,
21
+ HeterogeneousDeviceError,
22
+ TritonCacheLoaderError,
23
+ )
24
+ from triton_cache_loader.probe.fingerprint import SyncState
25
+ from triton_cache_loader.store import BundleManifest
26
+
27
+ _TRITON_MANAGER_SPEC = "triton_cache_loader.hooks.triton_manager:ArchSyncedCacheManager"
28
+
29
+ _LAZY_EXPORTS = {
30
+ "CacheMode": ("triton_cache_loader.config", "CacheMode"),
31
+ "LoaderConfig": ("triton_cache_loader.config", "LoaderConfig"),
32
+ "SyncPolicy": ("triton_cache_loader.config", "SyncPolicy"),
33
+ "ArchSyncError": ("triton_cache_loader.engine.exceptions", "ArchSyncError"),
34
+ "BundleNotFoundError": ("triton_cache_loader.engine.exceptions", "BundleNotFoundError"),
35
+ "CacheMissError": ("triton_cache_loader.engine.exceptions", "CacheMissError"),
36
+ "CorruptBundleError": ("triton_cache_loader.engine.exceptions", "CorruptBundleError"),
37
+ "HeterogeneousDeviceError": ("triton_cache_loader.engine.exceptions", "HeterogeneousDeviceError"),
38
+ "TritonCacheLoaderError": ("triton_cache_loader.engine.exceptions", "TritonCacheLoaderError"),
39
+ "SyncState": ("triton_cache_loader.probe.fingerprint", "SyncState"),
40
+ }
41
+ _LAZY_SUBMODULES = frozenset({"config", "engine", "hooks", "probe", "store"})
42
+
43
+ __all__ = [
44
+ "ArchSyncError",
45
+ "BundleNotFoundError",
46
+ "CacheMissError",
47
+ "CacheMode",
48
+ "CorruptBundleError",
49
+ "HeterogeneousDeviceError",
50
+ "LoaderConfig",
51
+ "SyncPolicy",
52
+ "SyncState",
53
+ "TritonCacheLoaderError",
54
+ "activate",
55
+ "deactivate",
56
+ "health_check",
57
+ "metrics_text",
58
+ "pack",
59
+ "preload",
60
+ "status",
61
+ ]
62
+
63
+
64
+ def __getattr__(name: str) -> "Any":
65
+ if name in _LAZY_EXPORTS:
66
+ module_name, attr_name = _LAZY_EXPORTS[name]
67
+ mod = __import__(module_name, fromlist=[attr_name])
68
+ value = getattr(mod, attr_name)
69
+ globals()[name] = value
70
+ return value
71
+ if name in _LAZY_SUBMODULES:
72
+ mod = __import__(f"{__name__}.{name}", fromlist=[name])
73
+ globals()[name] = mod
74
+ return mod
75
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
76
+
77
+
78
+ def activate(
79
+ config: Optional["LoaderConfig"] = None,
80
+ preload_now: bool = True,
81
+ ) -> Optional["PreloadReport"]:
82
+ """Enable arch-synced Triton cache management, preload bundles, and install runtime hooks."""
83
+ from triton_cache_loader.config import LoaderConfig
84
+ from triton_cache_loader.hooks.autotuner_guard import install_autotuner_guard
85
+ from triton_cache_loader.hooks.import_hook import install_lazy_hook
86
+
87
+ cfg = config if config is not None else LoaderConfig.from_env()
88
+ os.environ["TRITON_CACHE_MANAGER"] = _TRITON_MANAGER_SPEC
89
+ os.environ["TRITON_CACHE_DIR"] = str(cfg.triton_cache_dir)
90
+
91
+ report: Optional[PreloadReport] = None
92
+ if preload_now:
93
+ report = preload(cfg)
94
+
95
+ if "triton" in sys.modules or "triton.runtime.autotuner" in sys.modules:
96
+ install_autotuner_guard(cfg)
97
+
98
+ install_lazy_hook(cfg)
99
+ return report
100
+
101
+
102
+ def deactivate() -> None:
103
+ """Remove runtime hooks and clear ArchSyncedCacheManager environment wiring."""
104
+ from triton_cache_loader.hooks.autotuner_guard import uninstall_autotuner_guard
105
+ from triton_cache_loader.hooks.import_hook import uninstall_lazy_hook
106
+
107
+ uninstall_lazy_hook()
108
+ uninstall_autotuner_guard()
109
+ if os.environ.get("TRITON_CACHE_MANAGER") == _TRITON_MANAGER_SPEC:
110
+ os.environ.pop("TRITON_CACHE_MANAGER", None)
111
+
112
+
113
+ def preload(
114
+ config: Optional["LoaderConfig"] = None,
115
+ force: bool = False,
116
+ ) -> "PreloadReport":
117
+ """Preload and atomically hydrate the active architecture's Triton cache bundle."""
118
+ from triton_cache_loader.config import LoaderConfig
119
+ from triton_cache_loader.engine import PreloadEngine
120
+
121
+ cfg = config if config is not None else LoaderConfig.from_env()
122
+ report = PreloadEngine(cfg).preload(force=force)
123
+ guard_mod = sys.modules.get("triton_cache_loader.hooks.autotuner_guard")
124
+ if guard_mod is not None:
125
+ invalidate = getattr(guard_mod, "invalidate_autotune_index", None)
126
+ if invalidate is not None:
127
+ invalidate(cfg.triton_cache_dir)
128
+ return report
129
+
130
+
131
+ def health_check(
132
+ config: Optional["LoaderConfig"] = None,
133
+ force: bool = False,
134
+ ) -> "HealthCheckReport":
135
+ """Run the single-shot execution sync health check for the active topology."""
136
+ from triton_cache_loader.config import LoaderConfig
137
+ from triton_cache_loader.engine import EXECUTION_HEALTH_CHECK
138
+
139
+ cfg = config if config is not None else LoaderConfig.from_env()
140
+ return EXECUTION_HEALTH_CHECK.check_once(cfg, force=force)
141
+
142
+
143
+ def pack(
144
+ source_cache_dir: "Union[str, Path]",
145
+ store_dir: Optional["Union[str, Path]"] = None,
146
+ overwrite: bool = True,
147
+ ) -> "BundleManifest":
148
+ """Pack a populated Triton cache directory into an arch-indexed, SHA-256 verified bundle."""
149
+ from pathlib import Path
150
+
151
+ from triton_cache_loader.config import LoaderConfig
152
+ from triton_cache_loader.probe import probe_system
153
+ from triton_cache_loader.store import LocalBundleStore
154
+
155
+ cfg = LoaderConfig.from_env(store_dir=store_dir) if store_dir is not None else LoaderConfig.from_env()
156
+ topology = probe_system(target_arch_override=cfg.target_arch_override)
157
+ store = LocalBundleStore(cfg.store_dir)
158
+ return store.pack_from_cache_dir(
159
+ Path(source_cache_dir).expanduser(),
160
+ topology.active_fingerprint,
161
+ overwrite=overwrite,
162
+ )
163
+
164
+
165
+ def _serialize_manifest_summary(manifest: "Any") -> "Dict[str, Any]":
166
+ return {
167
+ "schema_version": getattr(manifest, "schema_version", "1.0"),
168
+ "created_at": getattr(manifest, "created_at", None),
169
+ "arch_id": manifest.arch.arch_id,
170
+ "arch_tag": manifest.arch.arch_tag,
171
+ "artifact_count": len(getattr(manifest, "artifacts", [])),
172
+ "autotune_keys": getattr(manifest, "autotune_keys", 0),
173
+ }
174
+
175
+
176
+ def _read_hydrated_marker(triton_cache_dir: "Path") -> Optional["Dict[str, Any]"]:
177
+ import json
178
+
179
+ marker = triton_cache_dir / ".loader_manifest.json"
180
+ if not marker.is_file():
181
+ return None
182
+ try:
183
+ data = json.loads(marker.read_text(encoding="utf-8"))
184
+ return data if isinstance(data, dict) else None
185
+ except (OSError, json.JSONDecodeError):
186
+ return None
187
+
188
+
189
+ def status(config: Optional["LoaderConfig"] = None) -> "Dict[str, Any]":
190
+ """Return a structured status snapshot of hardware topology, store bundles, hooks, and metrics."""
191
+ from triton_cache_loader.config import LoaderConfig
192
+ from triton_cache_loader.engine import EXECUTION_HEALTH_CHECK, METRICS
193
+ from triton_cache_loader.hooks.autotuner_guard import is_autotuner_guard_installed
194
+ from triton_cache_loader.hooks.import_hook import is_lazy_hook_installed
195
+ from triton_cache_loader.probe import probe_system
196
+ from triton_cache_loader.store import LocalBundleStore
197
+
198
+ cfg = config if config is not None else LoaderConfig.from_env()
199
+ topology = probe_system(target_arch_override=cfg.target_arch_override)
200
+ store = LocalBundleStore(cfg.store_dir)
201
+ bundles = store.list_bundles()
202
+ last = EXECUTION_HEALTH_CHECK.last_report()
203
+
204
+ last_hc_dict: Optional[Dict[str, Any]] = None
205
+ if last is not None:
206
+ last_hc_dict = {
207
+ "executed": last.executed,
208
+ "from_fast_path": last.from_fast_path,
209
+ "state": last.sync_result.state.value,
210
+ "synchronized": last.sync_result.synchronized,
211
+ "reasons": list(last.sync_result.reasons),
212
+ "duration_us": last.duration_us,
213
+ "policy_applied": last.policy_applied,
214
+ "rehydrated": last.rehydrated,
215
+ "bundle_marker_path": last.bundle_marker_path,
216
+ }
217
+
218
+ return {
219
+ "config": {
220
+ "store_dir": str(cfg.store_dir),
221
+ "triton_cache_dir": str(cfg.triton_cache_dir),
222
+ "remote_url": cfg.remote_url,
223
+ "cache_mode": cfg.cache_mode.value,
224
+ "sync_policy": cfg.sync_policy.value,
225
+ "target_arch_override": cfg.target_arch_override,
226
+ "require_exact_driver": cfg.require_exact_driver,
227
+ "require_exact_triton_version": cfg.require_exact_triton_version,
228
+ "verify_checksums": cfg.verify_checksums,
229
+ "auto_preload_on_import": cfg.auto_preload_on_import,
230
+ },
231
+ "active_arch_id": topology.active_fingerprint.arch_id,
232
+ "active_arch_tag": topology.active_fingerprint.arch_tag,
233
+ "topology": topology.to_dict(),
234
+ "has_matching_bundle": store.has_bundle(topology.active_fingerprint.arch_id),
235
+ "local_bundles": [_serialize_manifest_summary(b) for b in bundles],
236
+ "hydrated_marker": _read_hydrated_marker(cfg.triton_cache_dir),
237
+ "last_health_check": last_hc_dict,
238
+ "hooks": {
239
+ "lazy_hook_installed": is_lazy_hook_installed(),
240
+ "autotuner_guard_installed": is_autotuner_guard_installed(),
241
+ "triton_cache_manager_env": os.environ.get("TRITON_CACHE_MANAGER"),
242
+ "triton_cache_dir_env": os.environ.get("TRITON_CACHE_DIR"),
243
+ },
244
+ "metrics": METRICS.snapshot(),
245
+ }
246
+
247
+
248
+ def metrics_text() -> str:
249
+ """Return Prometheus-formatted metrics text from the global metrics registry."""
250
+ from triton_cache_loader.engine import METRICS
251
+
252
+ return METRICS.to_prometheus_text()
@@ -0,0 +1,378 @@
1
+ """Command-line interface for triton-cache-loader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Sequence
11
+
12
+ from triton_cache_loader import (
13
+ LoaderConfig,
14
+ SyncPolicy,
15
+ health_check,
16
+ metrics_text,
17
+ pack,
18
+ preload,
19
+ status,
20
+ )
21
+ from triton_cache_loader.engine.exceptions import TritonCacheLoaderError
22
+ from triton_cache_loader.hooks.autotuner_guard import is_autotuner_guard_installed
23
+ from triton_cache_loader.hooks.import_hook import is_lazy_hook_installed
24
+ from triton_cache_loader.probe import evaluate_arch_sync, probe_system
25
+ from triton_cache_loader.store import BundleManifest, LocalBundleStore
26
+
27
+
28
+ def _print_json(payload: Any) -> None:
29
+ print(json.dumps(payload, indent=2, default=str))
30
+
31
+
32
+ def _cmd_probe(args: argparse.Namespace) -> int:
33
+ cfg = LoaderConfig.from_env()
34
+ topology = probe_system(target_arch_override=cfg.target_arch_override)
35
+ data = topology.to_dict()
36
+ if args.json:
37
+ _print_json(data)
38
+ return 0
39
+
40
+ fp = topology.active_fingerprint
41
+ print(f"Active Arch ID : {fp.arch_id}")
42
+ print(f"Active Arch Tag: {fp.arch_tag}")
43
+ print(f"Backend : {fp.backend} ({fp.arch})")
44
+ print(f"Device : {fp.device_name} (SM/Cores: {fp.sm_count})")
45
+ print(f"Driver : {fp.driver_version} (CUDA API: {fp.cuda_driver_version})")
46
+ print(f"Triton Version : {topology.triton_version}")
47
+ print(f"GPUs Visible : {len(topology.gpus)}")
48
+ if topology.is_heterogeneous:
49
+ print(f"Heterogeneous : YES ({topology.heterogeneity_reason})")
50
+ return 0
51
+
52
+
53
+ def _cmd_pack(args: argparse.Namespace) -> int:
54
+ source_dir = Path(args.cache_dir).expanduser()
55
+ if not source_dir.is_dir():
56
+ msg = f"Source Triton cache directory does not exist: {source_dir}"
57
+ if args.json:
58
+ _print_json({"error": msg})
59
+ else:
60
+ print(f"Error: {msg}", file=sys.stderr)
61
+ return 1
62
+
63
+ manifest = pack(
64
+ source_cache_dir=source_dir,
65
+ store_dir=args.store,
66
+ overwrite=not args.no_overwrite,
67
+ )
68
+ payload = {
69
+ "schema_version": manifest.schema_version,
70
+ "created_at": manifest.created_at,
71
+ "arch_id": manifest.arch.arch_id,
72
+ "arch_tag": manifest.arch.arch_tag,
73
+ "artifact_count": len(manifest.artifacts),
74
+ "autotune_keys": manifest.autotune_keys,
75
+ "store_dir": str(LoaderConfig.from_env(store_dir=args.store).store_dir),
76
+ }
77
+ if args.json:
78
+ _print_json(payload)
79
+ return 0
80
+
81
+ print(f"Packed bundle : {payload['arch_id']} ({payload['arch_tag']})")
82
+ print(f"Artifacts : {payload['artifact_count']} (autotune keys: {payload['autotune_keys']})")
83
+ print(f"Store Dir : {payload['store_dir']}")
84
+ return 0
85
+
86
+
87
+ def _cmd_preload(args: argparse.Namespace) -> int:
88
+ cfg = LoaderConfig.from_env(
89
+ store_dir=args.store,
90
+ triton_cache_dir=args.cache_dir,
91
+ remote_url=args.remote,
92
+ )
93
+ report = preload(cfg, force=args.force)
94
+ payload = {
95
+ "arch_id": report.arch_id,
96
+ "arch_tag": report.arch_tag,
97
+ "source": report.source,
98
+ "hydrated_files": report.hydrated_files,
99
+ "autotune_files": report.autotune_files,
100
+ "bytes_copied": report.bytes_copied,
101
+ "verified_sha256": report.verified_sha256,
102
+ "duration_ms": round(report.duration_ms, 3),
103
+ }
104
+ if args.json:
105
+ _print_json(payload)
106
+ return 0
107
+
108
+ print(f"Preload Source : {report.source}")
109
+ print(f"Arch : {report.arch_id} ({report.arch_tag})")
110
+ print(f"Hydrated Files : {report.hydrated_files} (autotune: {report.autotune_files}, bytes: {report.bytes_copied})")
111
+ print(f"SHA-256 Check : {'verified' if report.verified_sha256 else 'skipped'}")
112
+ print(f"Duration : {payload['duration_ms']} ms")
113
+ return 0
114
+
115
+
116
+ def _cmd_health(args: argparse.Namespace) -> int:
117
+ policy = SyncPolicy(args.policy.lower()) if args.policy else None
118
+ cfg = LoaderConfig.from_env(
119
+ store_dir=args.store,
120
+ triton_cache_dir=args.cache_dir,
121
+ remote_url=args.remote,
122
+ sync_policy=policy,
123
+ )
124
+ report = health_check(cfg, force=args.force)
125
+ sr = report.sync_result
126
+ payload = {
127
+ "synchronized": sr.synchronized,
128
+ "state": sr.state.value,
129
+ "reasons": list(sr.reasons),
130
+ "live_arch_id": sr.live_arch_id,
131
+ "bundle_arch_id": sr.bundle_arch_id,
132
+ "live_arch_tag": sr.live_arch_tag,
133
+ "bundle_arch_tag": sr.bundle_arch_tag,
134
+ "policy_applied": report.policy_applied,
135
+ "rehydrated": report.rehydrated,
136
+ "from_fast_path": report.from_fast_path,
137
+ "duration_us": round(report.duration_us, 2),
138
+ "bundle_marker_path": report.bundle_marker_path,
139
+ }
140
+ if args.json:
141
+ _print_json(payload)
142
+ else:
143
+ print(f"Sync State : {sr.state.value} (synchronized={sr.synchronized})")
144
+ print(f"Policy Applied : {report.policy_applied} (rehydrated={report.rehydrated})")
145
+ print(f"Live Arch : {sr.live_arch_id} ({sr.live_arch_tag})")
146
+ print(f"Bundle Arch : {sr.bundle_arch_id or 'none'}")
147
+ for reason in sr.reasons:
148
+ print(f"Reason : {reason}")
149
+ return 0 if sr.synchronized else 1
150
+
151
+
152
+ def _cmd_status(args: argparse.Namespace) -> int:
153
+ cfg = LoaderConfig.from_env(store_dir=args.store, triton_cache_dir=args.cache_dir)
154
+ info = status(cfg)
155
+ if args.json:
156
+ _print_json(info)
157
+ return 0
158
+
159
+ print(f"Active Arch : {info['active_arch_id']} ({info['active_arch_tag']})")
160
+ print(f"Cache Mode : {info['config']['cache_mode']}")
161
+ print(f"Sync Policy : {info['config']['sync_policy']}")
162
+ print(f"Store Dir : {info['config']['store_dir']} (matching bundle: {info['has_matching_bundle']})")
163
+ print(f"Cache Dir : {info['config']['triton_cache_dir']}")
164
+ print(f"Local Bundles : {len(info['local_bundles'])}")
165
+ print(
166
+ f"Hooks : lazy_hook={info['hooks']['lazy_hook_installed']}, "
167
+ f"autotuner_guard={info['hooks']['autotuner_guard_installed']}"
168
+ )
169
+ return 0
170
+
171
+
172
+ def _check_dir_writable(path: Path) -> bool:
173
+ target = path
174
+ while not target.exists() and target.parent != target:
175
+ target = target.parent
176
+ return os.access(target, os.W_OK)
177
+
178
+
179
+ def _cmd_doctor(args: argparse.Namespace) -> int:
180
+ cfg = LoaderConfig.from_env(store_dir=args.store, triton_cache_dir=args.cache_dir)
181
+ checks: List[Dict[str, str]] = []
182
+
183
+ topology = probe_system(target_arch_override=cfg.target_arch_override)
184
+ fp = topology.active_fingerprint
185
+ if topology.is_heterogeneous:
186
+ checks.append({
187
+ "name": "hardware_topology",
188
+ "status": "fail",
189
+ "detail": topology.heterogeneity_reason or "Heterogeneous visible GPUs detected.",
190
+ })
191
+ elif topology.gpus:
192
+ checks.append({
193
+ "name": "hardware_topology",
194
+ "status": "ok",
195
+ "detail": f"{len(topology.gpus)}x GPU {fp.arch} (SM={fp.sm_count}), arch_id={fp.arch_id}",
196
+ })
197
+ else:
198
+ checks.append({
199
+ "name": "hardware_topology",
200
+ "status": "warn",
201
+ "detail": f"No GPU detected; CPU fallback active ({fp.arch}, arch_id={fp.arch_id})",
202
+ })
203
+
204
+ if topology.triton_version == "none":
205
+ checks.append({
206
+ "name": "triton_package",
207
+ "status": "warn",
208
+ "detail": "OpenAI Triton is not installed in the active Python environment.",
209
+ })
210
+ else:
211
+ checks.append({
212
+ "name": "triton_package",
213
+ "status": "ok",
214
+ "detail": f"Triton {topology.triton_version} detected.",
215
+ })
216
+
217
+ disabled = os.environ.get("TRITON_CACHE_LOADER_DISABLE") == "1"
218
+ checks.append({
219
+ "name": "runtime_hooks",
220
+ "status": "warn" if disabled else "ok",
221
+ "detail": (
222
+ "TRITON_CACHE_LOADER_DISABLE=1 is set."
223
+ if disabled
224
+ else f"lazy_hook={is_lazy_hook_installed()}, autotuner_guard={is_autotuner_guard_installed()}"
225
+ ),
226
+ })
227
+
228
+ checks.append({
229
+ "name": "cache_dir_permissions",
230
+ "status": "ok" if _check_dir_writable(cfg.triton_cache_dir) else "fail",
231
+ "detail": f"triton_cache_dir={cfg.triton_cache_dir}",
232
+ })
233
+
234
+ store = LocalBundleStore(cfg.store_dir)
235
+ if store.has_bundle(fp.arch_id):
236
+ try:
237
+ manifest = store.verify_bundle(fp.arch_id)
238
+ checks.append({
239
+ "name": "local_bundle",
240
+ "status": "ok",
241
+ "detail": f"Verified bundle {fp.arch_id} ({len(manifest.artifacts)} artifacts).",
242
+ })
243
+ except TritonCacheLoaderError as exc:
244
+ checks.append({
245
+ "name": "local_bundle",
246
+ "status": "fail",
247
+ "detail": f"Bundle verification failed for {fp.arch_id}: {exc}",
248
+ })
249
+ else:
250
+ checks.append({
251
+ "name": "local_bundle",
252
+ "status": "warn",
253
+ "detail": f"No local bundle found for {fp.arch_id} in {cfg.store_dir}.",
254
+ })
255
+
256
+ marker = cfg.triton_cache_dir / ".loader_manifest.json"
257
+ if marker.is_file():
258
+ try:
259
+ loaded_manifest = BundleManifest.load(marker)
260
+ sync_res = evaluate_arch_sync(
261
+ topology,
262
+ loaded_manifest.arch,
263
+ require_exact_driver=cfg.require_exact_driver,
264
+ require_exact_triton=cfg.require_exact_triton_version,
265
+ )
266
+ checks.append({
267
+ "name": "hydrated_cache_sync",
268
+ "status": "ok" if sync_res.synchronized else "fail",
269
+ "detail": f"state={sync_res.state.value}: {'; '.join(sync_res.reasons)}",
270
+ })
271
+ except Exception as exc:
272
+ checks.append({
273
+ "name": "hydrated_cache_sync",
274
+ "status": "fail",
275
+ "detail": f"Invalid hydrated manifest {marker}: {exc}",
276
+ })
277
+ else:
278
+ checks.append({
279
+ "name": "hydrated_cache_sync",
280
+ "status": "warn",
281
+ "detail": f"No hydrated .loader_manifest.json in {cfg.triton_cache_dir}.",
282
+ })
283
+
284
+ has_failures = any(c["status"] == "fail" for c in checks)
285
+ payload = {
286
+ "healthy": not has_failures,
287
+ "arch_id": fp.arch_id,
288
+ "arch_tag": fp.arch_tag,
289
+ "checks": checks,
290
+ }
291
+ if args.json:
292
+ _print_json(payload)
293
+ else:
294
+ print(f"Doctor Summary : {'HEALTHY' if not has_failures else 'UNHEALTHY'} ({fp.arch_id})")
295
+ for chk in checks:
296
+ print(f" [{chk['status'].upper():4s}] {chk['name']}: {chk['detail']}")
297
+ return 1 if has_failures else 0
298
+
299
+
300
+ def _cmd_metrics(args: argparse.Namespace) -> int:
301
+ print(metrics_text(), end="")
302
+ return 0
303
+
304
+
305
+ def _build_parser() -> argparse.ArgumentParser:
306
+ parser = argparse.ArgumentParser(
307
+ prog="triton-cache-loader",
308
+ description="Architecture-synchronized Triton autotune & kernel cache loader.",
309
+ )
310
+ sub = parser.add_subparsers(dest="command", required=True)
311
+
312
+ p_probe = sub.add_parser("probe", help="Probe local GPU/CPU topology and architecture fingerprint.")
313
+ p_probe.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
314
+ p_probe.set_defaults(func=_cmd_probe)
315
+
316
+ p_pack = sub.add_parser("pack", help="Pack a Triton cache directory into an arch-indexed bundle.")
317
+ p_pack.add_argument("cache_dir", help="Path to existing TRITON_CACHE_DIR to package.")
318
+ p_pack.add_argument("--store", default=None, help="Target bundle store directory.")
319
+ p_pack.add_argument("--no-overwrite", action="store_true", help="Fail if bundle already exists.")
320
+ p_pack.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
321
+ p_pack.set_defaults(func=_cmd_pack)
322
+
323
+ p_preload = sub.add_parser("preload", help="Hydrate TRITON_CACHE_DIR from local or remote bundle store.")
324
+ p_preload.add_argument("--store", default=None, help="Local bundle store directory.")
325
+ p_preload.add_argument("--cache-dir", default=None, help="Target TRITON_CACHE_DIR to hydrate.")
326
+ p_preload.add_argument("--remote", default=None, help="Remote bundle store URL or file:// mirror.")
327
+ p_preload.add_argument("--force", action="store_true", help="Force re-hydration even if already synced.")
328
+ p_preload.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
329
+ p_preload.set_defaults(func=_cmd_preload)
330
+
331
+ p_health = sub.add_parser("health", help="Run execution-sync health check against hydrated cache.")
332
+ p_health.add_argument(
333
+ "--policy",
334
+ choices=[p.value for p in SyncPolicy],
335
+ default=None,
336
+ help="SyncPolicy override (strict, rehydrate, warn).",
337
+ )
338
+ p_health.add_argument("--store", default=None, help="Local bundle store directory.")
339
+ p_health.add_argument("--cache-dir", default=None, help="Target TRITON_CACHE_DIR.")
340
+ p_health.add_argument("--remote", default=None, help="Remote bundle store URL.")
341
+ p_health.add_argument("--force", action="store_true", help="Bypass single-shot fast path.")
342
+ p_health.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
343
+ p_health.set_defaults(func=_cmd_health)
344
+
345
+ p_status = sub.add_parser("status", help="Show active architecture, store bundles, hooks, and metrics.")
346
+ p_status.add_argument("--store", default=None, help="Local bundle store directory.")
347
+ p_status.add_argument("--cache-dir", default=None, help="Target TRITON_CACHE_DIR.")
348
+ p_status.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
349
+ p_status.set_defaults(func=_cmd_status)
350
+
351
+ p_doctor = sub.add_parser("doctor", help="Diagnose environment, permissions, bundles, and sync state.")
352
+ p_doctor.add_argument("--store", default=None, help="Local bundle store directory.")
353
+ p_doctor.add_argument("--cache-dir", default=None, help="Target TRITON_CACHE_DIR.")
354
+ p_doctor.add_argument("--json", action="store_true", help="Output machine-readable JSON.")
355
+ p_doctor.set_defaults(func=_cmd_doctor)
356
+
357
+ p_metrics = sub.add_parser("metrics", help="Print Prometheus-formatted runtime metrics.")
358
+ p_metrics.set_defaults(func=_cmd_metrics)
359
+
360
+ return parser
361
+
362
+
363
+ def main(argv: Optional[Sequence[str]] = None) -> int:
364
+ """CLI entrypoint for triton-cache-loader."""
365
+ parser = _build_parser()
366
+ args = parser.parse_args(list(argv) if argv is not None else None)
367
+ try:
368
+ return int(args.func(args))
369
+ except TritonCacheLoaderError as exc:
370
+ if getattr(args, "json", False):
371
+ _print_json({"error": str(exc), "error_type": type(exc).__name__})
372
+ else:
373
+ print(f"Error ({type(exc).__name__}): {exc}", file=sys.stderr)
374
+ return 1
375
+
376
+
377
+ if __name__ == "__main__":
378
+ raise SystemExit(main())