File size: 9,309 Bytes
d3fc8af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Experiment runners for UGIES reproduction.
"""

import numpy as np
import json
import os
from typing import Dict, List
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from src.ugies import (
    UGIESPruner,
    compute_intrinsic_entropy,
    cosine_distance_matrix,
    g_sigmoid_nonpositive,
    g_linear_nonpositive,
    g_positive_violation,
    verify_submodularity,
    exact_mwcp_solver,
    compute_objective,
)


def generate_synthetic_data(
    n_samples: int = 200,
    n_features: int = 10,
    n_classes: int = 5,
    seed: int = 42,
) -> tuple:
    """Generate synthetic classification data."""
    np.random.seed(seed)
    data = np.random.randn(n_samples, n_features)
    labels = np.random.randint(0, n_classes, n_samples)
    # Add class structure
    for c in range(n_classes):
        mask = labels == c
        data[mask] += np.random.randn(n_features) * 2
    return data, labels


def experiment_a_submodularity() -> Dict:
    """Experiment A: Verify submodularity property computationally."""
    print("=" * 60)
    print("EXPERIMENT A: Submodularity Verification")
    print("=" * 60)
    
    data, labels = generate_synthetic_data(n_samples=100, n_features=10, n_classes=5)
    
    # Compute intrinsic importance (use random values for generality)
    probs = np.random.dirichlet(np.ones(5), size=100)
    intrinsic = compute_intrinsic_entropy(probs)
    distances = cosine_distance_matrix(data, data)
    
    results = {}
    
    # Test 1: Valid conditions (sigmoid non-positive)
    print("\n[Test 1] Valid conditions: g(z) = sigmoid(z) - 1")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=g_sigmoid_nonpositive, n_trials=100
    )
    print("\n[Test 1] Valid conditions: g(z) = sigmoid(z) - 1")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=g_sigmoid_nonpositive, n_trials=200
    )
    print(f"  Pass rate: {rate*100:.1f}%")
    print(f"  Result: {'PASS' if passed else 'FAIL'}")
    results['valid_sigmoid'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)}
    
    # Test 2: Valid conditions (linear non-positive)
    print("\n[Test 2] Valid conditions: g(z) = -z / max_dist")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=lambda d: g_linear_nonpositive(d, max_dist=2.0), n_trials=100
    )
    print("\n[Test 2] Valid conditions: g(z) = -z / max_dist")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=lambda d: g_linear_nonpositive(d, max_dist=2.0), n_trials=200
    )
    print(f"  Pass rate: {rate*100:.1f}%")
    print(f"  Result: {'PASS' if passed else 'FAIL'}")
    results['valid_linear'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)}
    
    # Test 3: Invalid conditions (positive mapping - negative control)
    print("\n[Test 3] INVALID conditions: g(z) = +0.5 (should FAIL)")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=g_positive_violation, n_trials=100
    )
    print("\n[Test 3] INVALID conditions: g(z) = +0.5 (should FAIL)")
    passed, rate, violations = verify_submodularity(
        intrinsic, distances, alpha=1.0, g_fn=g_positive_violation, n_trials=200
    )
    print(f"  Pass rate: {rate*100:.1f}%")
    print(f"  Result: {'PASS (unexpected!)' if passed else 'FAIL (expected)'}")
    results['invalid_positive'] = {'passed': passed, 'pass_rate': rate, 'n_violations': len(violations)}
    
    # Overall result
    results['overall_pass'] = (
        results['valid_sigmoid']['passed'] and
        results['valid_linear']['passed'] and
        not results['invalid_positive']['passed']
    )
    
    print(f"\n{'='*60}")
    print(f"OVERALL: {'PASS' if results['overall_pass'] else 'FAIL'}")
    print(f"{'='*60}")
    
    return results


def experiment_b_greedy_quality() -> Dict:
    """Experiment B: Greedy solver approximation quality vs exact solution."""
    print("\n" + "=" * 60)
    print("EXPERIMENT B: Greedy Solver Approximation Quality")
    print("=" * 60)
    
    results = {'instances': []}
    
    for seed in [42, 123, 456, 789, 101112]:
        np.random.seed(seed)
        N = 15  # Small enough for brute force
        n_classes = 3
        
        data = np.random.randn(N, 8)
        labels = np.random.randint(0, n_classes, N)
        probs = np.random.dirichlet(np.ones(n_classes), size=N)
        intrinsic = compute_intrinsic_entropy(probs)
        distances = cosine_distance_matrix(data, data)
        
        b = N // 2
        alpha = 1.0
        g_fn = g_sigmoid_nonpositive
        
        # Exact solution
        exact_subset, exact_obj = exact_mwcp_solver(intrinsic, distances, alpha, g_fn, b)
        
        # Greedy solution
        pruner = UGIESPruner(
            intrinsic_fn=lambda d: intrinsic,
            distance_fn=cosine_distance_matrix,
            g_fn=g_fn,
            alpha=alpha,
            use_sparsification=False,
        )
        # Manually run greedy
        edge_weights = g_fn(distances)
        selected = []
        remaining = set(range(N))
        extrinsic_sum = np.zeros(N)
        
        for _ in range(b):
            unified = np.full(N, -np.inf)
            for i in remaining:
                unified[i] = alpha * intrinsic[i] + extrinsic_sum[i]
            best_idx = int(np.argmax(unified))
            selected.append(best_idx)
            remaining.remove(best_idx)
            for i in remaining:
                extrinsic_sum[i] += edge_weights[i, best_idx]
        
        greedy_subset = np.array(selected)
        greedy_obj = compute_objective(greedy_subset, intrinsic, distances, alpha, g_fn)
        
        ratio = greedy_obj / exact_obj if exact_obj > 0 else 0.0
        theoretical_bound = 1.0 - 1.0 / np.e
        
        print(f"\n  Instance seed={seed}:")
        print(f"    Exact objective:  {exact_obj:.4f}")
        print(f"    Greedy objective: {greedy_obj:.4f}")
        print(f"    Ratio:            {ratio:.4f}")
        print(f"    Theoretical bound:{theoretical_bound:.4f}")
        print(f"    Meets bound:      {'YES' if ratio >= theoretical_bound - 1e-6 else 'NO'}")
        
        results['instances'].append({
            'seed': seed,
            'N': N,
            'b': b,
            'exact_obj': float(exact_obj),
            'greedy_obj': float(greedy_obj),
            'ratio': float(ratio),
            'meets_bound': bool(ratio >= theoretical_bound - 1e-6),
        })
    
    all_meet = all(inst['meets_bound'] for inst in results['instances'])
    results['overall_pass'] = all_meet
    
    print(f"\n{'='*60}")
    print(f"OVERALL: {'PASS' if all_meet else 'FAIL'}")
    print(f"{'='*60}")
    
    return results


def experiment_d_toy_scale() -> Dict:
    """Experiment D: Toy-scale pruning on synthetic data."""
    print("\n" + "=" * 60)
    print("EXPERIMENT D: Toy-Scale Pruning Verification")
    print("=" * 60)
    
    np.random.seed(42)
    N = 50
    n_features = 8
    n_classes = 3
    
    data = np.random.randn(N, n_features)
    labels = np.random.randint(0, n_classes, N)
    
    # Add class structure
    for c in range(n_classes):
        mask = labels == c
        data[mask] += np.random.randn(n_features) * 2
    
    # Intrinsic: entropy of pseudo-probabilities
    probs = np.random.dirichlet(np.ones(n_classes), size=N)
    
    def intrinsic_fn(d):
        return compute_intrinsic_entropy(probs)
    
    pruner = UGIESPruner(
        intrinsic_fn=intrinsic_fn,
        distance_fn=cosine_distance_matrix,
        g_fn=g_sigmoid_nonpositive,
        alpha=1.0,
        n_clusters=2,
        use_sparsification=True,
    )
    
    pruning_ratios = [0.3, 0.5, 0.7]
    results = {'pruning_ratios': {}}
    
    for p in pruning_ratios:
        selected = pruner.prune(data, labels, pruning_ratio=p)
        print(f"\n  Pruning ratio {p*100:.0f}%:")
        print(f"    Selected {len(selected)} / {N} samples")
        print(f"    Class distribution in selected: {dict(zip(*np.unique(labels[selected], return_counts=True)))}")
        
        results['pruning_ratios'][f'{int(p*100)}%'] = {
            'n_selected': int(len(selected)),
            'n_total': int(N),
            'class_distribution': {int(k): int(v) for k, v in zip(*np.unique(labels[selected], return_counts=True))},
        }
    
    results['overall_pass'] = True
    print(f"\n{'='*60}")
    print(f"OVERALL: PASS")
    print(f"{'='*60}")
    
    return results


def run_all_experiments():
    """Run all CPU-scale experiments."""
    os.makedirs('outputs', exist_ok=True)
    
    results = {}
    results['A_submodularity'] = experiment_a_submodularity()
    results['B_greedy_quality'] = experiment_b_greedy_quality()
    results['D_toy_scale'] = experiment_d_toy_scale()
    
    # Save results
    with open('outputs/cpu_experiments.json', 'w') as f:
        json.dump(results, f, indent=2)
    
    print("\n" + "=" * 60)
    print("ALL CPU EXPERIMENTS COMPLETE")
    print("=" * 60)
    print(f"Results saved to: outputs/cpu_experiments.json")
    
    return results


if __name__ == '__main__':
    run_all_experiments()