File size: 10,326 Bytes
ad424e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Label variance audit for PIMT pyramid targets.

Computes per-tier (Top/Mid/Base) and per-descriptor variance and positive-label
frequency across the full dataset.  Flags tiers whose mean label variance is
below a threshold and descriptors with <5 positive examples.

Additionally computes and caches training-set mean/variance of intensity scalars
(log₁₀ΣOAV per tier snapshot, Σx_liquid) to artifacts/scalar_stats_v1.json.

Usage:
    python scripts/audit_labels.py [--data data/empirical_dataset_v4.jsonl]
"""
from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np


VARIANCE_THRESHOLD = 0.01
MIN_POSITIVE_EXAMPLES = 5

# Step→tier mapping for 49-step trajectories (~3600s total):
#   top: 0-12 (~0-15min), mid: 13-33 (~15min-1hr), base: 34-48 (1hr+)
STEP_RANGES = {"top": (0, 13), "mid": (13, 34), "base": (34, 49)}
TIER_NAMES = ["top", "mid", "base"]


def load_dataset(path: str) -> list[dict]:
    with open(path) as f:
        return [json.loads(line) for line in f]


def load_vocabulary(path: str = "data/pyrfume_vocabulary.json") -> list[str]:
    with open(path) as f:
        data = json.load(f)
    return data["vocabulary"] if isinstance(data, dict) else data


def audit_pyramid_labels(
    records: list[dict], vocab: list[str], variance_threshold: float = VARIANCE_THRESHOLD
) -> dict:
    """Compute per-tier variance, positive-label frequency, and descriptor stats."""
    mixtures = [r for r in records if not r.get("is_control")]
    pyramids = []
    for r in mixtures:
        if "pyramid_targets" in r:
            pt = np.array(r["pyramid_targets"], dtype=np.float32)
            if pt.shape == (3, 138):
                pyramids.append(pt)

    if not pyramids:
        raise ValueError("No records with pyramid_targets found in dataset")

    all_pyramids = np.stack(pyramids)  # (N, 3, 138)
    N = len(all_pyramids)
    report = {"N": N, "tiers": {}}

    for i, name in enumerate(TIER_NAMES):
        tier = all_pyramids[:, i, :]  # (N, 138)
        positive_freq = tier.mean(axis=0)
        per_desc_var = tier.var(axis=0)
        mean_var = float(per_desc_var.mean())
        records_positive = int((tier.sum(axis=1) > 0).sum())
        descs_active = int(np.count_nonzero(positive_freq))
        descs_below_min = int(np.sum(positive_freq * N < MIN_POSITIVE_EXAMPLES))

        tier_report = {
            "records_with_any_positive": records_positive,
            "records_with_any_positive_pct": round(100 * records_positive / N, 2),
            "descriptors_active": descs_active,
            "descriptors_active_pct": round(100 * descs_active / 138, 2),
            "mean_variance": round(mean_var, 6),
            "variance_threshold": variance_threshold,
            "passes_variance_threshold": mean_var >= variance_threshold,
            "descriptors_below_min_examples": descs_below_min,
            "mean_label_frequency": round(float(tier.mean()), 6),
            "top_descriptors": [],
        }

        top_idx = np.argsort(positive_freq)[::-1][:20]
        for idx in top_idx:
            n_pos = int(positive_freq[idx] * N)
            desc_name = vocab[idx] if idx < len(vocab) else f"desc_{idx}"
            tier_report["top_descriptors"].append({
                "idx": int(idx),
                "name": desc_name,
                "positive_count": n_pos,
                "frequency": round(float(positive_freq[idx]), 6),
                "variance": round(float(per_desc_var[idx]), 6),
            })

        report["tiers"][name] = tier_report

    return report


def compute_scalar_stats(records: list[dict]) -> dict:
    """Compute training-set mean/variance of intensity scalars per tier."""
    mixtures = [r for r in records if not r.get("is_control")]
    log_oav = {t: [] for t in TIER_NAMES}
    x_liq = {t: [] for t in TIER_NAMES}

    for r in mixtures:
        traj = r.get("trajectory", [])
        for tier_name, (start, end) in STEP_RANGES.items():
            for step in traj[start:end]:
                oavs = step.get("OAV", {})
                xliqs = step.get("x_liquid", {})
                log_oav[tier_name].append(
                    sum(np.log10(max(v, 1e-10)) for v in oavs.values())
                )
                x_liq[tier_name].append(sum(xliqs.values()))

    stats = {}
    for tier_name in TIER_NAMES:
        lo = np.array(log_oav[tier_name])
        xl = np.array(x_liq[tier_name])
        stats[f"log10_oav_sum_{tier_name}"] = {
            "mean": round(float(lo.mean()), 6),
            "std": round(float(lo.std()), 6),
            "min": round(float(lo.min()), 6),
            "max": round(float(lo.max()), 6),
            "count": len(lo),
        }
        stats[f"x_liquid_sum_{tier_name}"] = {
            "mean": round(float(xl.mean()), 6),
            "std": round(float(xl.std()), 6),
            "min": round(float(xl.min()), 6),
            "max": round(float(xl.max()), 6),
            "count": len(xl),
        }

    all_lo = np.concatenate([np.array(log_oav[t]) for t in TIER_NAMES])
    all_xl = np.concatenate([np.array(x_liq[t]) for t in TIER_NAMES])
    stats["log10_oav_sum_overall"] = {
        "mean": round(float(all_lo.mean()), 6),
        "std": round(float(all_lo.std()), 6),
        "min": round(float(all_lo.min()), 6),
        "max": round(float(all_lo.max()), 6),
    }
    stats["x_liquid_sum_overall"] = {
        "mean": round(float(all_xl.mean()), 6),
        "std": round(float(all_xl.std()), 6),
        "min": round(float(all_xl.min()), 6),
        "max": round(float(all_xl.max()), 6),
    }
    return stats


def generate_histograms(report: dict, output_dir: Path) -> None:
    """Generate histogram plots of per-descriptor positive-label frequency."""
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    output_dir.mkdir(parents=True, exist_ok=True)

    fig, axes = plt.subplots(1, 3, figsize=(18, 5))
    fig.suptitle("Per-Descriptor Positive-Label Frequency by Tier", fontsize=14)

    for ax, tier_name in zip(axes, TIER_NAMES):
        tier_data = report["tiers"][tier_name]
        freqs = [d["frequency"] for d in tier_data["top_descriptors"]]
        names = [d["name"] for d in tier_data["top_descriptors"]]

        status = "PASS" if tier_data["passes_variance_threshold"] else "FAIL"
        ax.barh(range(len(freqs)), freqs, color="steelblue")
        ax.set_yticks(range(len(names)))
        ax.set_yticklabels(names, fontsize=8)
        ax.set_xlabel("Frequency")
        ax.set_title(f"{tier_name.upper()} ({status}, var={tier_data['mean_variance']:.4f})")
        ax.invert_yaxis()

    plt.tight_layout()
    path = output_dir / "label_frequency_histograms.png"
    fig.savefig(path, dpi=150)
    plt.close(fig)
    print(f"📊 Histogram saved to {path}")


def main():
    parser = argparse.ArgumentParser(description="Label variance audit for PIMT pyramid targets")
    parser.add_argument("--data", default="data/empirical_dataset_v4.jsonl")
    parser.add_argument("--variance-threshold", type=float, default=VARIANCE_THRESHOLD)
    parser.add_argument("--output", default="reports/label_variance_audit_v4.json")
    args = parser.parse_args()

    print(f"Loading dataset from {args.data}...")
    records = load_dataset(args.data)
    vocab = load_vocabulary()

    print(f"Auditing pyramid labels ({len(records)} records)...")
    label_report = audit_pyramid_labels(records, vocab, args.variance_threshold)

    print("Computing scalar statistics...")
    scalar_stats = compute_scalar_stats(records)

    # Build full report
    report = {
        "dataset": args.data,
        "total_records": len(records),
        "controls": sum(1 for r in records if r.get("is_control")),
        "mixtures": sum(1 for r in records if not r.get("is_control")),
        "variance_threshold": args.variance_threshold,
        "min_positive_examples": MIN_POSITIVE_EXAMPLES,
        **label_report,
        "scalar_stats": scalar_stats,
    }

    # Save JSON report
    report_path = Path(args.output)
    report_path.parent.mkdir(parents=True, exist_ok=True)
    report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False))
    print(f"📄 Report saved to {report_path}")

    # Save scalar stats artifact
    scalar_artifact = {
        "version": "v1",
        "dataset": args.data,
        "description": "Training-set statistics for standardization in ConcentrationAwarePyramidHead",
        "log10_oav_sum": scalar_stats["log10_oav_sum_overall"],
        "x_liquid_sum": scalar_stats["x_liquid_sum_overall"],
        "per_tier": {
            t: {
                "log10_oav_sum": scalar_stats[f"log10_oav_sum_{t}"],
                "x_liquid_sum": scalar_stats[f"x_liquid_sum_{t}"],
            }
            for t in TIER_NAMES
        },
    }
    scalar_path = Path("artifacts/scalar_stats_v1.json")
    scalar_path.parent.mkdir(parents=True, exist_ok=True)
    scalar_path.write_text(json.dumps(scalar_artifact, indent=2, ensure_ascii=False))
    print(f"📄 Scalar stats artifact saved to {scalar_path}")

    # Generate histogram plots
    generate_histograms(report, Path("reports/figures"))

    # Print verdict
    print(f"\n{'='*60}")
    print("VARIANCE AUDIT VERDICT")
    print(f"{'='*60}")
    all_pass = True
    for name in TIER_NAMES:
        t = report["tiers"][name]
        status = "✅ PASS" if t["passes_variance_threshold"] else "❌ FAIL"
        print(f"  {name}: {status} (variance={t['mean_variance']:.6f}, threshold={args.variance_threshold})")
        print(f"    Records with any positive: {t['records_with_any_positive']}/{report['N']} ({t['records_with_any_positive_pct']}%)")
        print(f"    Active descriptors: {t['descriptors_active']}/138 ({t['descriptors_active_pct']}%)")
        if not t["passes_variance_threshold"]:
            all_pass = False

    if not all_pass:
        print(f"\n⚠️  STOP CONDITION TRIGGERED")
        print(f"One or more tiers fail the variance threshold ({args.variance_threshold}).")
        print(f"The top/mid tier labels are too sparse for reliable training.")
        print(f"Recommended: enrich tier labels before proceeding to Phase 1.")
    else:
        print(f"\n✅ All tiers pass variance threshold.")


if __name__ == "__main__":
    main()