File size: 7,373 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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
"""
bench_gpu_parse.py

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
import hoptf.legacy.tf_atlas_streaming_surface_gpu_v2 as gpu_v2
from hoptf.legacy.tf_atlas_streaming_surface_gpu_v2 import (
    gpu_selected_expression_to_sparse,
    cupy_sparse_selected_expression_to_sparse,
    h5ad_cache_to_sparse,
    raw_sparse_selected_expression_to_sparse,
    resolve_h5ad_cache_path,
)


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.")
    p.add_argument(
        "--backend",
        choices=("raw-sparse", "raw-gpu", "raw-cupy-sparse", "h5ad-csr"),
        default="raw-sparse",
        help="Benchmark backend. h5ad-csr is an explicit cache-load path only.",
    )
    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}")

    h5ad_cache = resolve_h5ad_cache_path(args.selection_cache, sel.shard)
    if args.backend == "h5ad-csr" and not h5ad_cache.exists():
        raise FileNotFoundError(f"H5AD CSR cache not found: {h5ad_cache}")

    if args.backend == "h5ad-csr":
        print(f"\n>>> GPU v2 (cached H5AD CSR  path={h5ad_cache}) ...")
    elif args.backend == "raw-gpu":
        print(f"\n>>> GPU v2 (CuPy RawKernel  band={args.band_size}  block={args.block_size}) ...")
    elif args.backend == "raw-cupy-sparse":
        print(f"\n>>> GPU v2 (CuPy sparse parser  band={args.band_size}) ...")
    else:
        print(f"\n>>> RAW SPARSE v2 (Numba bytes->CSC  band={args.band_size}) ...")
    t1 = time.time()
    if args.backend == "h5ad-csr":
        gpu_matrix, gpu_genes = h5ad_cache_to_sparse(h5ad_cache, max_genes=args.max_genes)
    elif args.backend == "raw-gpu":
        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,
        )
    elif args.backend == "raw-cupy-sparse":
        gpu_matrix, gpu_genes = cupy_sparse_selected_expression_to_sparse(
            sel.source,
            column_indices=sel.column_indices,
            max_genes=args.max_genes,
            band_size=args.band_size,
        )
    else:
        gpu_matrix, gpu_genes = raw_sparse_selected_expression_to_sparse(
            sel.source,
            column_indices=sel.column_indices,
            max_genes=args.max_genes,
            band_size=args.band_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 backend        : {args.backend}")
    print(f"  GPU wall           : {gpu_wall:.1f}s")
    if gpu_v2.LAST_RAW_SPARSE_TIMING is not None:
        print(f"  Raw sparse phases  : {json.dumps(gpu_v2.LAST_RAW_SPARSE_TIMING.summary(), sort_keys=True)}")
    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),
        "gpu_backend": args.backend,
        "h5ad_cache": str(h5ad_cache) if args.backend == "h5ad-csr" else None,
        "raw_sparse_timing": (
            gpu_v2.LAST_RAW_SPARSE_TIMING.summary()
            if gpu_v2.LAST_RAW_SPARSE_TIMING is not None else None
        ),
        "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()