File size: 3,933 Bytes
fe8202e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Script to find best cases for different visualizations.
"""
import os
import sys
import glob
import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src"))

def main():
    # Setup
    ckpt_path = "/root/githubs/gliomasam3_moe/logs/segmamba/model/ckpt_step600.pt"
    data_path = "/data/yty/brats23_segmamba_processed"
    
    # Get all cases
    npz_files = sorted(glob.glob(os.path.join(data_path, "*.npz")))
    case_ids = [os.path.basename(f).replace(".npz", "") for f in npz_files]
    
    print(f"Found {len(case_ids)} cases")
    
    # Use ModelRunner from vis_publication
    from vis_publication import ModelRunner
    import yaml
    
    with open("visualizations/vis_config.yaml", "r") as f:
        vis_cfg = yaml.safe_load(f)
    
    runner = ModelRunner(vis_cfg, "configs/train.yaml", ckpt_path, "cuda")
    model = runner.model
    
    print("Model loaded")
    
    # Scan cases for best examples
    et_absent_candidates = []
    moe_routing_candidates = []
    
    test_cases = case_ids[:50]  # Test first 50
    
    for case_id in test_cases:
        try:
            # Load data using runner
            img_t, _ = runner.load_case_tensor(case_id)
            
            # Run model
            with torch.no_grad():
                out = runner.forward_intermediate(img_t)
            
            pi_et = float(out["pi_et"].cpu().numpy().reshape(-1)[0])
            et_pre = out["et_pre"].cpu().numpy()[0, 0]
            et_post = out["et_post"].cpu().numpy()[0, 0]
            moe_gamma = out["moe_gamma"].cpu().numpy()[0]  # [3, n_experts]
            
            # Check ET-absent: want low pi_et AND difference between pre/post
            pre_sum = (et_pre > 0.5).sum()
            post_sum = (et_post > 0.5).sum()
            diff_ratio = abs(pre_sum - post_sum) / max(pre_sum, 1)
            
            et_absent_candidates.append({
                "case_id": case_id,
                "pi_et": pi_et,
                "pre_sum": int(pre_sum),
                "post_sum": int(post_sum),
                "diff_ratio": diff_ratio,
                "score": (1 - pi_et) * diff_ratio  # High score = low pi_et + big diff
            })
            
            # Check MoE routing: want non-zero and diverse weights
            gamma_mean = moe_gamma.mean(axis=0)  # Average over regions
            nonzero_count = (gamma_mean > 0.05).sum()
            gamma_std = gamma_mean.std()
            
            moe_routing_candidates.append({
                "case_id": case_id,
                "gamma_mean": gamma_mean.tolist(),
                "nonzero_count": int(nonzero_count),
                "gamma_std": float(gamma_std),
                "score": nonzero_count * gamma_std  # High score = diverse weights
            })
            
            print(f"{case_id}: pi_et={pi_et:.3f}, pre={pre_sum}, post={post_sum}, diff={diff_ratio:.2f}, moe_nonzero={nonzero_count}")
            
        except Exception as e:
            print(f"Error on {case_id}: {e}")
            continue
    
    # Sort and report
    print("\n" + "="*60)
    print("Best ET-absent candidates (high score = low pi_et + big diff):")
    et_absent_candidates.sort(key=lambda x: x["score"], reverse=True)
    for c in et_absent_candidates[:10]:
        print(f"  {c['case_id']}: pi_et={c['pi_et']:.3f}, pre={c['pre_sum']}, post={c['post_sum']}, score={c['score']:.3f}")
    
    print("\n" + "="*60)
    print("Best MoE routing candidates (high score = diverse weights):")
    moe_routing_candidates.sort(key=lambda x: x["score"], reverse=True)
    for c in moe_routing_candidates[:10]:
        print(f"  {c['case_id']}: nonzero={c['nonzero_count']}, std={c['gamma_std']:.3f}, weights={[f'{w:.2f}' for w in c['gamma_mean']]}")

if __name__ == "__main__":
    main()