File size: 5,273 Bytes
920c356 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | #!/usr/bin/env python3
"""
bench_gpu_parse.py
Legacy diagnostic. Use `bench_gpu_parse_v2.py` for retained GPU parser
diagnostics and the CSR cache path for production ingestion.
Head-to-head timing + numerical parity:
- BASELINE: serial np.fromstring streaming
- GPU: CuPy RawKernel one-thread-per-gene-row CUDA parser
Usage
-----
python scripts/bench_gpu_parse.py \
--selection-cache data/processed/tf_atlas_h5ad/profiles/s01_s04_plate_split_5000genes_optimal/SELECTION_CACHE.json \
--max-genes 5000 --shard 05
Produces a JSON result verifying:
- shape match
- max |diff| over a random cell sample
- wall time for each backend
- speedup ratio
"""
from __future__ import annotations
import argparse
import json
import logging
import time
import sys
from pathlib import Path
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
REPO_ROOT = Path(__file__).resolve().parents[2]
for _p in (REPO_ROOT / "hoptf" / "src", REPO_ROOT / "src"):
if str(_p) not in sys.path:
sys.path.insert(0, str(_p))
import numpy as np
from hoptf.tf_atlas_h5ad_surface import read_selection_cache, selected_expression_to_sparse
from hoptf.legacy.tf_atlas_streaming_surface_gpu import gpu_selected_expression_to_sparse
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser()
p.add_argument("--selection-cache", type=Path, required=True)
p.add_argument("--max-genes", type=int, default=5000)
p.add_argument("--band-size", type=int, default=480)
p.add_argument("--block-size", type=int, default=256)
p.add_argument("--shard", default="05")
p.add_argument("--atol", type=float, default=1.0,
help="Abs tolerance for parity (raw int counts, allow 0 diff).")
p.add_argument("--skip-baseline", action="store_true",
help="Skip slow baseline run, only time GPU.")
return p.parse_args()
def main() -> None:
args = parse_args()
sels = read_selection_cache(args.selection_cache)
sel = next((s for s in sels if s.shard == args.shard), None)
if sel is None:
available = [s.shard for s in sels]
raise ValueError(f"Shard {args.shard!r} not found. Available: {available}")
n_cells = sel.column_indices.size
print(f"\n{'='*64}")
print(f"GPU Parse Benchmark | shard={sel.shard} cells={n_cells} max_genes={args.max_genes}")
print(f"{'='*64}\n")
baseline_matrix = None
baseline_wall = None
if not args.skip_baseline:
print(">>> BASELINE (serial np.fromstring) ...")
t0 = time.time()
baseline_matrix, baseline_genes = selected_expression_to_sparse(
sel.source,
column_indices=sel.column_indices,
max_genes=args.max_genes,
)
baseline_wall = time.time() - t0
print(f" Baseline: {baseline_wall:.1f}s shape={baseline_matrix.shape}")
print(f"\n>>> GPU (CuPy RawKernel band={args.band_size} block={args.block_size}) ...")
t1 = time.time()
gpu_matrix, gpu_genes = gpu_selected_expression_to_sparse(
sel.source,
column_indices=sel.column_indices,
max_genes=args.max_genes,
band_size=args.band_size,
block_size=args.block_size,
)
gpu_wall = time.time() - t1
print(f" GPU: {gpu_wall:.1f}s shape={gpu_matrix.shape}")
# Parity check
if baseline_matrix is not None:
assert baseline_matrix.shape == gpu_matrix.shape, \
f"Shape mismatch: {baseline_matrix.shape} vs {gpu_matrix.shape}"
assert baseline_genes == gpu_genes, "Gene name mismatch"
rng = np.random.default_rng(42)
n_sample = min(500, n_cells)
sample_cells = rng.choice(n_cells, size=n_sample, replace=False)
ref_dense = baseline_matrix[sample_cells].toarray().astype(np.float32)
gpu_dense = gpu_matrix[sample_cells].toarray().astype(np.float32)
max_diff = float(np.abs(ref_dense - gpu_dense).max())
parity = max_diff <= args.atol
else:
max_diff = None
parity = None
speedup = (baseline_wall / gpu_wall) if baseline_wall else None
print(f"\n{'='*64}")
print("RESULTS")
print(f"{'='*64}")
if baseline_wall:
print(f" Baseline wall : {baseline_wall:.1f}s")
print(f" GPU wall : {gpu_wall:.1f}s")
if speedup:
print(f" Speedup : {speedup:.1f}x")
print(f" Full-scale est (30K genes, serial baseline): {baseline_wall * 6:.0f}s -> GPU: {gpu_wall * 6:.0f}s")
if max_diff is not None:
print(f" Max |diff| (sample): {max_diff:.6f} (atol={args.atol})")
print(f" PARITY : {'PASS' if parity else 'FAIL'}")
print()
result = {
"baseline_wall_s": round(baseline_wall, 2) if baseline_wall else None,
"gpu_wall_s": round(gpu_wall, 2),
"speedup_x": round(speedup, 2) if speedup else None,
"shape": list(gpu_matrix.shape),
"max_abs_diff": round(max_diff, 8) if max_diff is not None else None,
"parity": ("PASS" if parity else "FAIL") if parity is not None else "not_checked",
}
print(json.dumps(result, indent=2))
if parity is False:
sys.exit(1)
if __name__ == "__main__":
main()
|