File size: 13,722 Bytes
dcce49b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""
Offline PCA-emb dictionary computation for grn_svd (latent_dim=1).

Pipeline:
  1. Load sparse attention cache + scGPT gene embeddings
  2. Sample (control, perturbed) pairs, compute sparse delta attention
  3. Project delta through gene_emb: delta_512d = sparse_delta @ gene_emb
  4. Center + PCA on 512D features -> first principal component v
  5. Compute combined weight: w = gene_emb @ v (5035, 1)
  6. Save as dict compatible with grn_svd format

Math: (Δ_attn @ gene_emb) @ v = Δ_attn @ (gene_emb @ v) = Δ_attn @ w
      -> _sparse_project(W=w) gives (B, G, 1), same structure as SVD dict.

Usage:
    python scripts/compute_pca_emb_dict.py \
        --data-name norman --fold 1 --split-method additive \
        --topk 30 --use-negative-edge \
        --sparse-cache-path .../norman_attn_L11_sparse.h5 \
        --scgpt-model-dir .../scGPT_pretrained \
        --n-pairs-per-condition 50 \
        --output-path cache/pca_emb_dict_norman_f1.pt
"""

import sys
import os

_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, _PROJECT_ROOT)

import _bootstrap_scdfm  # noqa: F401

import argparse
import json
import numpy as np
import torch
import h5py
from sklearn.decomposition import PCA

from src.data.data import get_data_classes
from src.data.sparse_raw_cache import _read_sparse_batch

_REPO_ROOT = os.path.normpath(os.path.join(_PROJECT_ROOT, "..", "..", "transfer", "code"))


def load_scgpt_gene_embeddings(scgpt_model_dir, hvg_gene_names):
    """
    Load scGPT gene embeddings for HVG genes without importing the full scGPT package.

    Returns:
        gene_emb: (G_full, 512) float32 tensor, zero for genes not in vocab
        valid_mask: (G_full,) bool — True for genes in scGPT vocab
    """
    # Load vocab
    vocab_path = os.path.join(scgpt_model_dir, "vocab.json")
    with open(vocab_path, "r") as f:
        scgpt_vocab = json.load(f)

    # Map HVG genes to scGPT token IDs
    hvg_to_scgpt = []
    for gene in hvg_gene_names:
        hvg_to_scgpt.append(scgpt_vocab.get(gene, -1))
    hvg_to_scgpt = torch.tensor(hvg_to_scgpt, dtype=torch.long)
    valid_mask = hvg_to_scgpt >= 0

    # Load model args to get d_model
    with open(os.path.join(scgpt_model_dir, "args.json"), "r") as f:
        model_args = json.load(f)
    d_model = model_args.get("embsize", 512)

    # Load checkpoint — extract only embedding weights
    ckpt_path = os.path.join(scgpt_model_dir, "best_model.pt")
    ckpt = torch.load(ckpt_path, map_location="cpu", weights_only=False)
    # scGPT stores encoder as nn.Embedding; key is "encoder.embedding.weight"
    emb_weight = None
    for key in ckpt:
        if "encoder" in key and "weight" in key:
            if ckpt[key].dim() == 2 and ckpt[key].shape[1] == d_model:
                emb_weight = ckpt[key]
                print(f"  Found embedding weights: key='{key}', shape={emb_weight.shape}")
                break
    if emb_weight is None:
        raise RuntimeError(f"Cannot find encoder embedding weights in {ckpt_path}")

    # Build gene_emb: (G_full, D), zero for missing genes
    G_full = len(hvg_gene_names)
    gene_emb = torch.zeros(G_full, d_model)
    valid_ids = hvg_to_scgpt[valid_mask]
    gene_emb[valid_mask] = emb_weight[valid_ids].float()

    n_valid = valid_mask.sum().item()
    n_missing = G_full - n_valid
    print(f"  Gene embeddings: {n_valid}/{G_full} valid, {n_missing} missing (zero)")

    return gene_emb, valid_mask.numpy()


def parse_args():
    p = argparse.ArgumentParser(description="Compute PCA-emb dictionary for grn_svd (1D)")
    p.add_argument("--data-name", type=str, default="norman")
    p.add_argument("--sparse-cache-path", type=str, required=True)
    p.add_argument("--scgpt-model-dir", type=str, required=True,
                   help="Path to scGPT pretrained model dir (contains vocab.json, args.json, best_model.pt)")
    p.add_argument("--fold", type=int, default=1)
    p.add_argument("--split-method", type=str, default="additive")
    p.add_argument("--topk", type=int, default=30, help="GRN graph topk for scDFM process_data")
    p.add_argument("--use-negative-edge", action="store_true", default=True)
    p.add_argument("--n-top-genes", type=int, default=5000)
    p.add_argument("--n-pairs-per-condition", type=int, default=50)
    p.add_argument("--delta-topk", type=int, default=30, help="Per-row top-K on delta")
    p.add_argument("--rows-per-pair", type=int, default=500,
                   help="Gene rows to sample per pair (0 = all)")
    p.add_argument("--output-path", type=str, required=True)
    return p.parse_args()


def main():
    args = parse_args()

    # === 1. Load scDFM data to get train/test split ===
    Data, PerturbationDataset, TrainSampler, TestDataset = get_data_classes()

    scdfm_data_path = os.path.join(_REPO_ROOT, "scDFM", "data")
    data_manager = Data(scdfm_data_path)
    data_manager.load_data(args.data_name)

    if "gene_name" in data_manager.adata.var.columns and data_manager.adata.var_names[0].startswith("ENSG"):
        data_manager.adata.var_names = data_manager.adata.var["gene_name"].values
        data_manager.adata.var_names_make_unique()

    data_manager.process_data(
        n_top_genes=args.n_top_genes,
        split_method=args.split_method,
        fold=args.fold,
        use_negative_edge=args.use_negative_edge,
        k=args.topk,
    )
    train_sampler, _, _ = data_manager.load_flow_data(batch_size=32)

    train_conditions = train_sampler._perturbation_covariates
    adata = train_sampler.adata
    ctrl_mask = adata.obs["perturbation_covariates"] == "control+control"
    if ctrl_mask.sum() == 0:
        ctrl_mask = adata.obs["condition"].isin(["control", "ctrl"])
    ctrl_cell_ids = list(adata.obs_names[ctrl_mask])

    cond_to_cells = {}
    for cond in train_conditions:
        cond_mask = adata.obs["perturbation_covariates"] == cond
        cond_to_cells[cond] = list(adata.obs_names[cond_mask])

    print(f"Training conditions: {len(train_conditions)}")
    print(f"Control cells: {len(ctrl_cell_ids)}")

    # === 2. Load scGPT gene embeddings ===
    hvg_gene_names = list(data_manager.adata.var_names)
    print(f"\nLoading scGPT gene embeddings...")
    gene_emb, valid_gene_mask = load_scgpt_gene_embeddings(
        args.scgpt_model_dir, hvg_gene_names
    )
    D = gene_emb.shape[1]  # 512
    print(f"  gene_emb shape: {gene_emb.shape}, D={D}")

    # === 3. Open HDF5 cache ===
    h5 = h5py.File(args.sparse_cache_path, "r")
    h5_values = h5["attn_values"]
    h5_indices = h5["attn_indices"]
    cell_names_all = h5["cell_names"].asstr()[:]
    name_to_idx = {name: i for i, name in enumerate(cell_names_all)}
    G_full = h5_values.shape[1]
    K_sparse = h5_values.shape[2]

    print(f"\nCache: {len(name_to_idx)} cells, G_full={G_full}, K_sparse={K_sparse}")

    ctrl_in_cache = [c for c in ctrl_cell_ids if c in name_to_idx]
    print(f"Control cells in cache: {len(ctrl_in_cache)}")

    # === 4. Stratified sampling: collect delta_512d = sparse_delta @ gene_emb ===
    all_delta_512d = []  # list of (chunk_size, D) tensors
    delta_topk = args.delta_topk
    rows_per_pair = args.rows_per_pair if args.rows_per_pair > 0 else G_full
    rng = np.random.RandomState(42)

    for cond_idx, cond in enumerate(train_conditions):
        pert_cell_ids = cond_to_cells.get(cond, [])
        pert_cell_ids = [c for c in pert_cell_ids if c in name_to_idx]
        if not pert_cell_ids or not ctrl_in_cache:
            continue

        n_pairs = min(args.n_pairs_per_condition, len(pert_cell_ids), len(ctrl_in_cache))
        src_sample = [ctrl_in_cache[i] for i in rng.choice(len(ctrl_in_cache), n_pairs, replace=True)]
        tgt_sample = [pert_cell_ids[i] for i in rng.choice(len(pert_cell_ids), n_pairs, replace=True)]

        if rows_per_pair < G_full:
            gene_idx = np.sort(rng.choice(G_full, rows_per_pair, replace=False))
        else:
            gene_idx = np.arange(G_full)

        sv, si, tv, ti = _read_sparse_batch(
            h5_values, h5_indices, name_to_idx,
            src_sample, tgt_sample, gene_idx)

        for p in range(n_pairs):
            for chunk_start in range(0, len(gene_idx), 100):
                chunk_end = min(chunk_start + 100, len(gene_idx))

                s_v = torch.from_numpy(sv[p, chunk_start:chunk_end].astype(np.float32))
                s_i = torch.from_numpy(si[p, chunk_start:chunk_end].astype(np.int64))
                t_v = torch.from_numpy(tv[p, chunk_start:chunk_end].astype(np.float32))
                t_i = torch.from_numpy(ti[p, chunk_start:chunk_end].astype(np.int64))

                c_len = chunk_end - chunk_start

                # Scatter to dense
                src_dense = torch.zeros(c_len, G_full)
                tgt_dense = torch.zeros(c_len, G_full)
                src_dense.scatter_(-1, s_i, s_v)
                tgt_dense.scatter_(-1, t_i, t_v)

                delta = tgt_dense - src_dense  # (c_len, G_full)

                # Per-row top-K (same sparsification as SVD dict)
                _, topk_idx = delta.abs().topk(delta_topk, dim=-1)
                topk_vals = delta.gather(-1, topk_idx)  # (c_len, delta_topk)

                # Project through gene_emb: delta_512d = sparse_delta @ gene_emb
                # Equivalent to: sum_k topk_vals[r,k] * gene_emb[topk_idx[r,k]]
                delta_512d = torch.zeros(c_len, D)
                for k in range(delta_topk):
                    col_idx = topk_idx[:, k]             # (c_len,)
                    val = topk_vals[:, k:k+1]             # (c_len, 1)
                    emb_k = gene_emb[col_idx]             # (c_len, D)
                    delta_512d = delta_512d + val * emb_k  # (c_len, D)

                all_delta_512d.append(delta_512d)

        if (cond_idx + 1) % 10 == 0:
            n_rows = sum(t.shape[0] for t in all_delta_512d)
            print(f"  Processed {cond_idx + 1}/{len(train_conditions)} conditions, {n_rows} rows")

    h5.close()

    # === 5. Concatenate and fit PCA ===
    X = torch.cat(all_delta_512d, dim=0).numpy()  # (N_rows, 512)
    print(f"\nTotal delta_512d samples: {X.shape[0]} x {X.shape[1]}")

    print("Fitting PCA (with centering)...")
    pca = PCA(n_components=1, random_state=42)
    pca.fit(X)

    v = pca.components_[0]  # (512,) — first principal component
    explained = pca.explained_variance_ratio_[0]
    print(f"  Explained variance ratio: {explained:.4f} ({explained * 100:.1f}%)")
    print(f"  PC1 norm: {np.linalg.norm(v):.6f}")
    print(f"  Data mean norm: {np.linalg.norm(pca.mean_):.4f}")

    # === 6. Compute combined projection weight: w = gene_emb @ v ===
    v_tensor = torch.from_numpy(v.astype(np.float32))             # (512,)
    w = (gene_emb @ v_tensor).unsqueeze(1)                         # (G_full, 1)
    print(f"\n  w = gene_emb @ v: shape={w.shape}")
    print(f"  w stats: mean={w.mean():.6f}, std={w.std():.6f}, "
          f"range=[{w.min():.4f}, {w.max():.4f}]")

    # === 7. Global scalar scaling ===
    # Project all sampled data through w to compute global std
    # z_1d = delta_sparse @ w, but we already have delta_512d, so z_1d = X @ v
    z_1d = torch.from_numpy((X @ v).astype(np.float32))  # (N_rows,)

    z_std = z_1d.std().item()
    global_scale = 1.0 / z_std
    print(f"\n  Pre-scaling z_1d stats: mean={z_1d.mean():.4f}, std={z_std:.4f}")

    # Apply scaling to W (same convention as compute_svd_dict.py)
    W_scaled = w * global_scale

    # Verify
    z_scaled = z_1d * global_scale
    print(f"  Post-scaling z_1d stats: mean={z_scaled.mean():.4f}, std={z_scaled.std():.4f}")
    print(f"  Post-scaling range: [{z_scaled.min():.2f}, {z_scaled.max():.2f}]")

    # Robust scaling if needed
    extreme_ratio = (z_scaled.abs() > 5.0).float().mean().item()
    print(f"  |z| > 5.0: {extreme_ratio:.4%}")

    if extreme_ratio > 0.01:
        q99 = z_scaled.abs().quantile(0.99).item()
        robust_factor = q99 / 3.0
        W_scaled = W_scaled / robust_factor
        global_scale = global_scale / robust_factor
        z_robust = z_1d * global_scale
        print(f"  Robust scaling applied: 99th={q99:.2f} -> +/-3.0")
        print(f"  After robust: std={z_robust.std():.4f}, "
              f"range=[{z_robust.min():.2f}, {z_robust.max():.2f}]")

    # Zero invalid gene rows
    W_scaled[~torch.from_numpy(valid_gene_mask)] = 0.0

    # === 8. Save (compatible with grn_svd dict format) ===
    os.makedirs(os.path.dirname(args.output_path) or ".", exist_ok=True)
    save_dict = {
        "W": W_scaled,                                        # (G_full, 1) float32
        "global_scale": global_scale,                         # float scalar
        "valid_gene_mask": valid_gene_mask,                   # (G_full,) bool
        "explained_variance_ratio": pca.explained_variance_ratio_,  # (1,)
        "singular_values": np.sqrt(pca.explained_variance_),  # (1,)
        "n_components": 1,
        "delta_topk": args.delta_topk,
        "data_name": args.data_name,
        "fold": args.fold,
        "n_pairs_per_condition": args.n_pairs_per_condition,
        "n_rows": X.shape[0],
        # PCA-emb specific metadata
        "pca_component": v,                                   # (512,) PC direction
        "pca_mean": pca.mean_,                                # (512,) centering vector
        "gene_emb_shape": list(gene_emb.shape),               # [5035, 512]
    }
    torch.save(save_dict, args.output_path)

    print(f"\nSaved PCA-emb dictionary to {args.output_path}")
    print(f"  W: {W_scaled.shape}, global_scale: {global_scale:.6f}")
    print(f"  Explained variance: {explained:.4f}")


if __name__ == "__main__":
    main()