Dhruv1000 commited on
Commit
ea96e35
·
verified ·
1 Parent(s): 5cd330e

TraceGRPO research update 20261010T001256Z (Review 21-23)

Browse files
.gitattributes CHANGED
@@ -105,3 +105,6 @@ results/phase6/scale_review21_step324_lr5e6/training_curves.png filter=lfs diff=
105
  results/phase6/scale_review21_step324_lr5e6/sampled_generated_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
106
  results/phase6/scale_review21_step324_lr5e6/sampled_training_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
107
  results/phase6/scale_review21_step324_lr5e6/sampled_verified_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
 
 
 
 
105
  results/phase6/scale_review21_step324_lr5e6/sampled_generated_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
106
  results/phase6/scale_review21_step324_lr5e6/sampled_training_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
107
  results/phase6/scale_review21_step324_lr5e6/sampled_verified_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
108
+ results/phase6/review23/e2/grpo200_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
109
+ results/phase6/review23/e2/grpo324_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
110
+ results/phase6/review23/e2/sft500_rollouts.jsonl filter=lfs diff=lfs merge=lfs -text
DECISIONS.md CHANGED
@@ -2684,3 +2684,9 @@ The stop watchdog originally recorded an error because its success condition req
2684
  The resumed segment consumed 10.444 GPU-hours; cumulative GRPO use is 52.237 GPU-hours, below the 250-hour ceiling. `TEST` remains sealed. Full evidence and limitations: `results/phase6/review23/step400_stop_report.md` and the machine-readable run files listed there.
2685
 
2686
  The 5% retained rollout sample over steps 340–400 further showed 50.75% VULNERABLE predictions and 51.61% non-empty statement emission on SAFE-target rollouts (400/775), contradicting the pre-registered <5% prediction. Correctly predicted SAFE rows with eligible R2 averaged 0.971; correctly predicted VULNERABLE rows averaged 0.141 (380 eligible, 2 ineligible). Sampled accuracy was 49.77%, not VALID accuracy. The step-400 VALID accuracy/Wilson interval and greedy class gap remain unmeasured because the tripwire preempted that evaluation.
 
 
 
 
 
 
 
2684
  The resumed segment consumed 10.444 GPU-hours; cumulative GRPO use is 52.237 GPU-hours, below the 250-hour ceiling. `TEST` remains sealed. Full evidence and limitations: `results/phase6/review23/step400_stop_report.md` and the machine-readable run files listed there.
2685
 
2686
  The 5% retained rollout sample over steps 340–400 further showed 50.75% VULNERABLE predictions and 51.61% non-empty statement emission on SAFE-target rollouts (400/775), contradicting the pre-registered <5% prediction. Correctly predicted SAFE rows with eligible R2 averaged 0.971; correctly predicted VULNERABLE rows averaged 0.141 (380 eligible, 2 ineligible). Sampled accuracy was 49.77%, not VALID accuracy. The step-400 VALID accuracy/Wilson interval and greedy class gap remain unmeasured because the tripwire preempted that evaluation.
2687
+
2688
+ ### Review #23 E3 preflight and deterministic holdout quarantine — 2026-10-09
2689
+
2690
+ Before E3 training, reconstructed the registered 7,370 pre-2021 TRAIN / 862 2021 TRAIN split using the frozen SecVulEval date cache; the corpus `commit_date` column alone is incomplete and would have produced an incorrect split. Pair IDs are disjoint across chronological TRAIN and VALID. A normalized-function hash audit found 8 code collisions between pre-2021 TRAIN and the 2021 selection holdout, 6 between the 2021 holdout and 2022 VALID, and none between pre-2021 TRAIN and VALID. To prevent holdout leakage from either model training or final evaluation, deterministically quarantine all 14 affected 2021 pairs before model selection. E3 therefore uses 7,370 training pairs and 848 clean holdout pairs; VALID remains the frozen 1,104-pair split. This is a data-integrity exclusion only: no labels, model settings, loss weights, or registered thresholds were changed. Exact IDs and hashes are frozen in `results/phase6/review23/e3/frozen_pair_splits.json` and `data_preflight.json`.
2691
+
2692
+ The pre-2021 line-target audit found 38,349 positive and 1,485,357 negative lines (2.5168% positive), with zero invalid or missing vulnerable patch-line targets. The E3 machine-readable configuration and protocol were frozen before training at `configs/review23/e3.json` and `results/phase6/review23/e3/PROTOCOL.md`. TEST remains sealed. The matched classical holdout baseline is being measured CPU-only before the first E3 update; no E3 model training has started.
RECOVERY_CURRENT.md CHANGED
@@ -1,9 +1,13 @@
1
  # TraceGRPO Disaster Recovery Snapshot
2
 
3
- Updated 2026-10-09 UTC. Private recovery copy: `Dhruv1000/tracegrpo`.
4
- The exact verified snapshot revision is recorded in
5
- `results/hf_sync_20261009_review23_status.json` (`final_remote_revision`). Restore that
6
- revision for a fixed recovery point, or omit `--revision` to fetch the latest snapshot.
 
 
 
 
7
 
8
  ## Recovery point
9
 
@@ -26,8 +30,11 @@ downloaded from the private Hugging Face repo and their hashes matched that mani
26
  `Qwen/Qwen3-4B@1cfa9a7208912126459214e8b04321603b3df60c`.
27
 
28
  The private snapshot also contains the terminal step-400 status, tripwire evidence, logs,
29
- step-399 inference-only adapter, Review 22/23 analyses, and the in-progress E2 evaluation
30
- artifacts. The step-399 adapter predates the final optimizer update. Restoring training,
 
 
 
31
  if later authorized, means restoring the full state at step 324 and replaying; it cannot
32
  reproduce the final step-400 optimizer update. E2 has no resumable process checkpoint, so
33
  after machine loss, rerun its frozen evaluation from the saved config and script.
 
1
  # TraceGRPO Disaster Recovery Snapshot
2
 
3
+ Updated 2026-10-10 UTC. Private recovery copy: `Dhruv1000/tracegrpo`.
4
+ The latest independently verified Hugging Face base revision is
5
+ `f2e9530ff32958ebcd187180f778e9e2ebe539b7`. It contains the full project snapshot,
6
+ data, checkpoints, and results available before the 2026-10-10 delta. A recovery delta
7
+ for subsequent work is stored on `/data/tracegrpo_recovery/20261010/`; its manifest
8
+ contains file hashes and restoration instructions. HF synchronization on 2026-10-10
9
+ was attempted but could not connect (`No route to host`), so this delta is not yet
10
+ verified on HF. The two-hour sync daemon remains active and will retry.
11
 
12
  ## Recovery point
13
 
 
30
  `Qwen/Qwen3-4B@1cfa9a7208912126459214e8b04321603b3df60c`.
31
 
32
  The private snapshot also contains the terminal step-400 status, tripwire evidence, logs,
33
+ step-399 inference-only adapter, Review 22/23 analyses, and the E2 evaluation artifacts.
34
+ E2 is now complete: AUC was 0.5092 for SFT-500, 0.5163 for GRPO-200, and 0.5098 for
35
+ GRPO-324; paired confidence intervals for both GRPO comparisons include zero. No 400-step
36
+ checkpoint was substituted. E3 data/config preflight and the matched classical holdout
37
+ baseline are frozen; neural E3 training has not started. Restoring training,
38
  if later authorized, means restoring the full state at step 324 and replaying; it cannot
39
  reproduce the final step-400 optimizer update. E2 has no resumable process checkpoint, so
40
  after machine loss, rerun its frozen evaluation from the saved config and script.
RELEASE_INFO.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "project": "TraceGRPO",
3
- "snapshot_date_utc": "2026-10-09",
4
  "source_git_commit": "e0827e42112f3bd8f24dc72427a6f8ebcd71877d",
5
  "huggingface_repo": "Dhruv1000/tracegrpo",
6
  "repo_type": "model",
 
1
  {
2
  "project": "TraceGRPO",
3
+ "snapshot_date_utc": "2026-10-10",
4
  "source_git_commit": "e0827e42112f3bd8f24dc72427a6f8ebcd71877d",
5
  "huggingface_repo": "Dhruv1000/tracegrpo",
6
  "repo_type": "model",
configs/review23/e3.json ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "protocol": "Review #23 E3 / Review #22 Section 4.2",
3
+ "status": "frozen_before_training",
4
+ "model": {
5
+ "id": "Qwen/Qwen3-4B",
6
+ "revision": "1cfa9a7208912126459214e8b04321603b3df60c",
7
+ "input": "raw function source only; no CVE, CWE, patch, commit, pair ID, or label metadata",
8
+ "max_sequence_length": 8192,
9
+ "truncation": "right",
10
+ "precision": "bfloat16",
11
+ "attention": "flash_attention_2 when importable; otherwise sdpa",
12
+ "gradient_checkpointing": true
13
+ },
14
+ "architecture": {
15
+ "encoder": "Qwen3-4B with one shared LoRA adapter",
16
+ "lora": {
17
+ "rank": 64,
18
+ "alpha": 128,
19
+ "dropout": 0.05,
20
+ "target_modules": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
21
+ },
22
+ "line_representation": "mean of final-layer hidden states for source-code tokens on each visible source line",
23
+ "line_score": "one learned linear head per visible line",
24
+ "function_score": "logsumexp of line scores over visible source lines; no length normalization",
25
+ "prediction": "VULNERABLE iff function_score >= threshold selected on clean 2021 TRAIN holdout",
26
+ "top_k_evidence": 5
27
+ },
28
+ "data": {
29
+ "corpus": "data/processed/corpus.parquet",
30
+ "train_split": "results/phase6/review23/e3/frozen_pair_splits.json:train_pre_2021_pair_ids",
31
+ "selection_holdout": "results/phase6/review23/e3/frozen_pair_splits.json:selection_holdout_2021_pair_ids",
32
+ "valid_split": "data/splits/chronological/valid.json",
33
+ "train_pairs": 7370,
34
+ "holdout_pairs_original": 862,
35
+ "holdout_duplicate_code_quarantine": 14,
36
+ "holdout_pairs_used": 848,
37
+ "valid_pairs": 1104,
38
+ "pair_integrity": "both original pair members remain together in TRAIN or holdout",
39
+ "line_targets": "diff-derived patch_lines_vuln, 1-based; vulnerable changed lines positive; patched and unchanged lines negative",
40
+ "split_dates": "commit_date merged with frozen SecVulEval commit-date cache"
41
+ },
42
+ "objective": {
43
+ "pointwise": "equal-weight binary cross-entropy for SAFE and VULNERABLE; batches contain complete pairs",
44
+ "line": "binary cross-entropy averaged within each function then across rows; positive weight is the TRAIN negative/positive line ratio",
45
+ "line_positive_weight": 38.73261362747399,
46
+ "line_loss_weight": 1.0,
47
+ "total": "L_pointwise + 1.0 * L_line",
48
+ "pairwise_margin_loss": false
49
+ },
50
+ "training": {
51
+ "seeds": [42, 43, 44],
52
+ "epochs": 2,
53
+ "optimizer": "AdamW",
54
+ "learning_rate": 0.0001,
55
+ "weight_decay": 0.01,
56
+ "scheduler": "cosine",
57
+ "warmup_ratio": 0.03,
58
+ "gradient_clip_norm": 1.0,
59
+ "pair_microbatch_size": 1,
60
+ "gradient_accumulation_pair_batches": 32,
61
+ "effective_batch": "32 pairs / 64 rows",
62
+ "checkpoint_each_epoch": true,
63
+ "model_selection": "highest row ROC-AUC on the clean 2021 TRAIN holdout; tie selects earlier epoch"
64
+ },
65
+ "ablations": {
66
+ "no_line_loss": {"line_loss_weight": 0.0, "seed": 42},
67
+ "no_pair_batching": {"pair_batching": false, "seed": 42},
68
+ "shuffled_label_control": {
69
+ "seed": 42,
70
+ "labels": "randomly swap SAFE/VULNERABLE assignment within each training pair",
71
+ "line_loss_weight": 0.0,
72
+ "purpose": "negative control; prevent true diff-line targets from leaking the original label"
73
+ }
74
+ },
75
+ "evaluation": {
76
+ "primary_metric": "row ROC-AUC",
77
+ "confidence_interval": "5000 pair-cluster bootstrap replicates, seed 42",
78
+ "length_bands_lines": {"short": "<=30", "medium": "31-100", "long": ">100"},
79
+ "holdout_threshold": "balanced accuracy maximization; threshold used only for secondary accuracy",
80
+ "valid": "one final evaluation after holdout checkpoint selection; TEST is never read",
81
+ "report": ["row AUC", "pair-cluster CI", "paired difference CI vs matched classical baseline", "long-function AUC", "balanced accuracy", "train-valid accuracy gap", "line localization metrics", "truncation/positive-line coverage"]
82
+ },
83
+ "classical_control": {
84
+ "features": "character TF-IDF 3-5 grams, min_df=2, max_features=300000, sublinear_tf=true",
85
+ "classifier": "averaged SGD logistic loss, alpha=1e-5, max_iter=200, tol=1e-3, random_state=42",
86
+ "fit_split": "same pre-2021 TRAIN pairs as E3",
87
+ "early_gate_evaluation": "clean 2021 TRAIN holdout only",
88
+ "final_comparison_evaluation": "chronological VALID after E3 model selection"
89
+ },
90
+ "gates_from_review22": {
91
+ "early_stop_after_seed_1_if_holdout_auc_delta_below": 0.01,
92
+ "stage_holdout_auc_delta_go": 0.02,
93
+ "valid_auc_go": 0.6,
94
+ "valid_auc_difference_ci_must_exclude_zero": true,
95
+ "valid_long_function_auc_go": 0.56,
96
+ "train_valid_accuracy_gap_max": 0.03,
97
+ "classical_valid_auc_reference": 0.57,
98
+ "failure_if_valid_auc_within": [0.55, 0.59]
99
+ },
100
+ "provenance": {
101
+ "test_read": false,
102
+ "corpus_sha256": "fda8efe71d0d74e9f0ca8d7b2f050481972363dbed80d364cc9271d83ea3435b",
103
+ "train_split_sha256": "a365b114eecfb33fc9e08bda82e11c075530acb4db573cd8a4a29b9281503e4a",
104
+ "valid_split_sha256": "1b2f9ba17b1ce9853ef7628575c45bc07ccd0a89301254be9542d2729fa8d51d",
105
+ "date_cache_sha256": "ef914835991298957438343e76f11a77f928d1df67e8636953788e0df6fcada7",
106
+ "frozen_pair_splits_sha256": "594fbe05245bb553c9de9dd62cf2a23bf0b706302b0347fa9901de5b392261b4"
107
+ }
108
+ }
results/hf_sync_20261009_review23_status.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "created_at_utc": "2026-10-09T23:42:36.705159+00:00",
3
  "repo_id": "Dhruv1000/tracegrpo",
4
  "repo_type": "model",
5
  "private": true,
@@ -18,8 +18,8 @@
18
  },
19
  {
20
  "path": "DECISIONS.md",
21
- "sha256": "7305b72afd265bf57421888c10168f5759633806a58bcffa613e417cb882a359",
22
- "size_bytes": 189155,
23
  "change": "updated"
24
  },
25
  {
@@ -36,13 +36,13 @@
36
  },
37
  {
38
  "path": "RECOVERY_CURRENT.md",
39
- "sha256": "a7e4acc2f29d67d4d42362fd42c90fcb5a100df26acfaee0a8ba980f84af3967",
40
- "size_bytes": 4934,
41
  "change": "new"
42
  },
43
  {
44
  "path": "RELEASE_INFO.json",
45
- "sha256": "8608deb9bb15c8ea55ed956892dfc90800d6128849be22a30a415161869987ad",
46
  "size_bytes": 1485,
47
  "change": "updated"
48
  },
@@ -58,6 +58,12 @@
58
  "size_bytes": 4445816,
59
  "change": "new"
60
  },
 
 
 
 
 
 
61
  {
62
  "path": "docs/PROJECT_HISTORY.md",
63
  "sha256": "e2d2f01b06921f113bd75ee40e2b7f2f7207e5806a90fd2a38fd9fb47fe8afa5",
@@ -144,8 +150,32 @@
144
  },
145
  {
146
  "path": "results/phase6/review23/e2/e2.log",
147
- "sha256": "bce5c01352871c0a110937a996ce8af9f322fc36d09805c2a41cbf071066d712",
148
- "size_bytes": 238510,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  "change": "new"
150
  },
151
  {
@@ -154,6 +184,36 @@
154
  "size_bytes": 677,
155
  "change": "new"
156
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  {
158
  "path": "results/phase6/review23/equilibrium_predictions_interim.json",
159
  "sha256": "cfeb0bf3c42f251e41cefa138447e1858c9a5074e28e0a4e063f93dec79f413c",
@@ -448,12 +508,30 @@
448
  "size_bytes": 9697,
449
  "change": "new"
450
  },
 
 
 
 
 
 
 
 
 
 
 
 
451
  {
452
  "path": "scripts/hf_sync_snapshot.py",
453
  "sha256": "f05a0f9371e575b271df6eb6aa385aad521612d3ae609c03abe0396f013ab9df",
454
  "size_bytes": 12722,
455
  "change": "new"
456
  },
 
 
 
 
 
 
457
  {
458
  "path": "scripts/run_review23_e1_predicted_slices.py",
459
  "sha256": "d75d364de9717ca0e45f427b016cc69594e35c419323960116bfcc90abf26ae8",
@@ -472,6 +550,12 @@
472
  "size_bytes": 4531,
473
  "change": "new"
474
  },
 
 
 
 
 
 
475
  {
476
  "path": "scripts/watch_step400_hf_backup.py",
477
  "sha256": "93c7596c1ce84e3bd2349aa842a8259752c13c86bce87556da4890dcf0e74214",
@@ -496,6 +580,12 @@
496
  "size_bytes": 1088,
497
  "change": "new"
498
  },
 
 
 
 
 
 
499
  {
500
  "path": "tests/test_reward_counterfactual.py",
501
  "sha256": "ef8340b7738c404353d570fee40a9a8fc38b9336eec5d6779871a0bcf4c33112",
@@ -515,9 +605,5 @@
515
  "step400_valid_evaluation_available": false,
516
  "last_full_state_step": 324,
517
  "latest_serialized_adapter_step": 399,
518
- "parent_remote_revision": "a7297b170297bce146c939a2457365af47705d54",
519
- "upload_commit": "f2e9530ff32958ebcd187180f778e9e2ebe539b7",
520
- "remote_revision_after": "f2e9530ff32958ebcd187180f778e9e2ebe539b7",
521
- "verified_remote_paths": 83,
522
- "final_remote_revision": "f2e9530ff32958ebcd187180f778e9e2ebe539b7"
523
  }
 
1
  {
2
+ "created_at_utc": "2026-10-10T00:12:56.585577+00:00",
3
  "repo_id": "Dhruv1000/tracegrpo",
4
  "repo_type": "model",
5
  "private": true,
 
18
  },
19
  {
20
  "path": "DECISIONS.md",
21
+ "sha256": "412e3809343c90423a570c2fced7fb6770671d302878593bb44821194bdc001a",
22
+ "size_bytes": 190693,
23
  "change": "updated"
24
  },
25
  {
 
36
  },
37
  {
38
  "path": "RECOVERY_CURRENT.md",
39
+ "sha256": "4208751ce662f848f8fa5ef9f37bb808c9b3cdc7cb76170d24b033a279f1d25f",
40
+ "size_bytes": 5511,
41
  "change": "new"
42
  },
43
  {
44
  "path": "RELEASE_INFO.json",
45
+ "sha256": "c18b8f909c8cf430bd8a19574523a00d33424c9112130908d11662b77be88af0",
46
  "size_bytes": 1485,
47
  "change": "updated"
48
  },
 
58
  "size_bytes": 4445816,
59
  "change": "new"
60
  },
61
+ {
62
+ "path": "configs/review23/e3.json",
63
+ "sha256": "ec1f02d3d7ff6b86ecc6e11fd789ec40969f9d3750ebb9aef37eebd08056f2e6",
64
+ "size_bytes": 5269,
65
+ "change": "new"
66
+ },
67
  {
68
  "path": "docs/PROJECT_HISTORY.md",
69
  "sha256": "e2d2f01b06921f113bd75ee40e2b7f2f7207e5806a90fd2a38fd9fb47fe8afa5",
 
150
  },
151
  {
152
  "path": "results/phase6/review23/e2/e2.log",
153
+ "sha256": "36a20b560e14104b4dbfda294c0527a4d801404dfdd2a3ae5be4a75c38af2c34",
154
+ "size_bytes": 702194,
155
+ "change": "new"
156
+ },
157
+ {
158
+ "path": "results/phase6/review23/e2/grpo200_rollouts.jsonl",
159
+ "sha256": "95617a324cc948a4d9431db86ed2de39bbebd84efac28f0471658b6bc07be38b",
160
+ "size_bytes": 12464278,
161
+ "change": "new"
162
+ },
163
+ {
164
+ "path": "results/phase6/review23/e2/grpo324_rollouts.jsonl",
165
+ "sha256": "0c61c16f1391061f62e3df1da238886aa0e9445e4acbca08f7d0871326e0b69a",
166
+ "size_bytes": 12240355,
167
+ "change": "new"
168
+ },
169
+ {
170
+ "path": "results/phase6/review23/e2/metrics.json",
171
+ "sha256": "abd6181b713d344f3a7f1313c00e0a02705f5140c33ca1228c5542e9e01fb745",
172
+ "size_bytes": 5771,
173
+ "change": "new"
174
+ },
175
+ {
176
+ "path": "results/phase6/review23/e2/sft500_rollouts.jsonl",
177
+ "sha256": "1f61d5ef59037a9311b5a21e3ab810a1370122799a70c6b1441322bf3efb0c6f",
178
+ "size_bytes": 13687701,
179
  "change": "new"
180
  },
181
  {
 
184
  "size_bytes": 677,
185
  "change": "new"
186
  },
187
+ {
188
+ "path": "results/phase6/review23/e3/PROTOCOL.md",
189
+ "sha256": "9e9c6dd4ca4737248f7b578fd3ac3c771f17efd1f222e176c7402b8f20e6640d",
190
+ "size_bytes": 4492,
191
+ "change": "new"
192
+ },
193
+ {
194
+ "path": "results/phase6/review23/e3/classical_baseline.log",
195
+ "sha256": "475474dccb400def636afabe826e1833f52540249727102a29cf2ac60cb37f0e",
196
+ "size_bytes": 1259,
197
+ "change": "new"
198
+ },
199
+ {
200
+ "path": "results/phase6/review23/e3/classical_holdout_baseline.json",
201
+ "sha256": "475474dccb400def636afabe826e1833f52540249727102a29cf2ac60cb37f0e",
202
+ "size_bytes": 1259,
203
+ "change": "new"
204
+ },
205
+ {
206
+ "path": "results/phase6/review23/e3/data_preflight.json",
207
+ "sha256": "09c780b6b96e9b1cdd218031c03ca9ad16b1556bd9a3a692ea52478f133d9e99",
208
+ "size_bytes": 1587,
209
+ "change": "new"
210
+ },
211
+ {
212
+ "path": "results/phase6/review23/e3/frozen_pair_splits.json",
213
+ "sha256": "594fbe05245bb553c9de9dd62cf2a23bf0b706302b0347fa9901de5b392261b4",
214
+ "size_bytes": 526500,
215
+ "change": "new"
216
+ },
217
  {
218
  "path": "results/phase6/review23/equilibrium_predictions_interim.json",
219
  "sha256": "cfeb0bf3c42f251e41cefa138447e1858c9a5074e28e0a4e063f93dec79f413c",
 
508
  "size_bytes": 9697,
509
  "change": "new"
510
  },
511
+ {
512
+ "path": "scripts/evaluate_review23_e3_final.py",
513
+ "sha256": "17e738192f479c62ceecd6fa01d5275a19f7ba7a07bb1df46fc55e9a94c1e085",
514
+ "size_bytes": 14974,
515
+ "change": "new"
516
+ },
517
+ {
518
+ "path": "scripts/evaluate_review23_e3_holdout_baseline.py",
519
+ "sha256": "2f95fd2ca9dc68d23d813afd0cfeb67f4f44d667b00446b1c02596932718ee03",
520
+ "size_bytes": 4477,
521
+ "change": "new"
522
+ },
523
  {
524
  "path": "scripts/hf_sync_snapshot.py",
525
  "sha256": "f05a0f9371e575b271df6eb6aa385aad521612d3ae609c03abe0396f013ab9df",
526
  "size_bytes": 12722,
527
  "change": "new"
528
  },
529
+ {
530
+ "path": "scripts/prepare_review23_e3.py",
531
+ "sha256": "109b3eabb4f1114706b197aa2730e839a2444a34bf7b66ea1e345acbecddd79b",
532
+ "size_bytes": 8665,
533
+ "change": "new"
534
+ },
535
  {
536
  "path": "scripts/run_review23_e1_predicted_slices.py",
537
  "sha256": "d75d364de9717ca0e45f427b016cc69594e35c419323960116bfcc90abf26ae8",
 
550
  "size_bytes": 4531,
551
  "change": "new"
552
  },
553
+ {
554
+ "path": "scripts/train_review23_e3.py",
555
+ "sha256": "840cf8cf5b96a9b469c368737181a8ee366bcb712d3d64555ba35f1868098c55",
556
+ "size_bytes": 28953,
557
+ "change": "new"
558
+ },
559
  {
560
  "path": "scripts/watch_step400_hf_backup.py",
561
  "sha256": "93c7596c1ce84e3bd2349aa842a8259752c13c86bce87556da4890dcf0e74214",
 
580
  "size_bytes": 1088,
581
  "change": "new"
582
  },
583
+ {
584
+ "path": "tests/test_review23_e3.py",
585
+ "sha256": "1d4709cce9a7fc229aa2084cf2e9a24847ae4868527c07090cd5de3c9ac04b4e",
586
+ "size_bytes": 1762,
587
+ "change": "new"
588
+ },
589
  {
590
  "path": "tests/test_reward_counterfactual.py",
591
  "sha256": "ef8340b7738c404353d570fee40a9a8fc38b9336eec5d6779871a0bcf4c33112",
 
605
  "step400_valid_evaluation_available": false,
606
  "last_full_state_step": 324,
607
  "latest_serialized_adapter_step": 399,
608
+ "parent_remote_revision": "5cd330eafa520bd057b71d48389fb99cb17be7c1"
 
 
 
 
609
  }
results/phase6/review23/e2/e2.log CHANGED
The diff for this file is too large to render. See raw diff
 
results/phase6/review23/e2/grpo200_rollouts.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:95617a324cc948a4d9431db86ed2de39bbebd84efac28f0471658b6bc07be38b
3
+ size 12464278
results/phase6/review23/e2/grpo324_rollouts.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c61c16f1391061f62e3df1da238886aa0e9445e4acbca08f7d0871326e0b69a
3
+ size 12240355
results/phase6/review23/e2/metrics.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "models": {
4
+ "sft500": {
5
+ "adapter": "/home/ubuntu/ib_connect_research/project/tracegrpo/checkpoints/sft-contract-v2/checkpoint-500",
6
+ "adapter_sha256": "552aa1705ea462072e558ed55fce48677b458f00abab6fecf0b03ff9f73b7adc",
7
+ "step": 500
8
+ },
9
+ "grpo200": {
10
+ "adapter": "/home/ubuntu/ib_connect_research/project/tracegrpo/results/phase6/scale_20261007_v5/checkpoints/step-000200/adapter",
11
+ "adapter_sha256": "e542a13c3b3c07bb9bed6f8c424e2962dcd3064ae2672d3f69c1755eb9e69c56",
12
+ "step": 200
13
+ },
14
+ "grpo324": {
15
+ "adapter": "/home/ubuntu/ib_connect_research/project/tracegrpo/results/phase6/scale_20261007_v5/checkpoints/step-000324/adapter",
16
+ "adapter_sha256": "90ee18642fe528f3d83bdee39623bffc32cc523f65514676debfc6ceb751a421",
17
+ "step": 324
18
+ }
19
+ },
20
+ "optional_checkpoint_status": {
21
+ "grpo400": "unavailable: Review #14 tripwire stopped after step 400 before checkpoint save; no substitution"
22
+ },
23
+ "n_valid_rows": 2208,
24
+ "n_pairs": 1104,
25
+ "function_line_count_sha256": "293481a8b922250bd96cb2be71d44c520f0117cde24d423240251f493778c482",
26
+ "prompt_hashes_sha256": "b66cdb391f46bba6bbc6f35b9f831cd226ca4edf7444884b02b3096b736a1de8",
27
+ "temperature": 0.8,
28
+ "max_tokens": 1536,
29
+ "samples_per_row": 8,
30
+ "seed": 42,
31
+ "primary_score": "fraction of all 8 generations predicting VULNERABLE; invalid parse counts 0",
32
+ "sensitivity": "fraction among parseable generations only",
33
+ "bootstrap": "5000 resamples of VALID pair ids, keeping both row members together",
34
+ "test_touched": false
35
+ },
36
+ "models": {
37
+ "sft500": {
38
+ "parse_rate": 0.986129981884058,
39
+ "auc_all8_invalid_as_safe": {
40
+ "auc": 0.5091995018115942,
41
+ "pair_cluster_bootstrap_95_ci": [
42
+ 0.49581894436896135,
43
+ 0.522509396414225
44
+ ],
45
+ "n_rows": 2208,
46
+ "n_pairs": 1104
47
+ },
48
+ "auc_parseable_only": {
49
+ "auc": 0.5096146588164251,
50
+ "pair_cluster_bootstrap_95_ci": [
51
+ 0.4963549973909104,
52
+ 0.5230093898504778
53
+ ],
54
+ "n_rows": 2208,
55
+ "n_pairs": 1104
56
+ }
57
+ },
58
+ "grpo200": {
59
+ "parse_rate": 0.9916779891304348,
60
+ "auc_all8_invalid_as_safe": {
61
+ "auc": 0.5162604527672758,
62
+ "pair_cluster_bootstrap_95_ci": [
63
+ 0.5030741514715922,
64
+ 0.5293498977696388
65
+ ],
66
+ "n_rows": 2208,
67
+ "n_pairs": 1104
68
+ },
69
+ "auc_parseable_only": {
70
+ "auc": 0.5164302897237975,
71
+ "pair_cluster_bootstrap_95_ci": [
72
+ 0.5033621974112581,
73
+ 0.5295853516855702
74
+ ],
75
+ "n_rows": 2208,
76
+ "n_pairs": 1104
77
+ }
78
+ },
79
+ "grpo324": {
80
+ "parse_rate": 0.9919044384057971,
81
+ "auc_all8_invalid_as_safe": {
82
+ "auc": 0.5098300317685359,
83
+ "pair_cluster_bootstrap_95_ci": [
84
+ 0.4973178785805241,
85
+ 0.5231682427864419
86
+ ],
87
+ "n_rows": 2208,
88
+ "n_pairs": 1104
89
+ },
90
+ "auc_parseable_only": {
91
+ "auc": 0.5088138816687671,
92
+ "pair_cluster_bootstrap_95_ci": [
93
+ 0.49630752303875236,
94
+ 0.522023125311778
95
+ ],
96
+ "n_rows": 2208,
97
+ "n_pairs": 1104
98
+ }
99
+ }
100
+ },
101
+ "comparisons_vs_sft": {
102
+ "grpo200": {
103
+ "auc_delta": 0.0070609509556816,
104
+ "pair_cluster_bootstrap_95_ci": [
105
+ -0.0084293281348457,
106
+ 0.022801062670657516
107
+ ],
108
+ "n_pairs": 1104
109
+ },
110
+ "grpo324": {
111
+ "auc_delta": 0.0006305299569416833,
112
+ "pair_cluster_bootstrap_95_ci": [
113
+ -0.015576684667743115,
114
+ 0.016923945041745294
115
+ ],
116
+ "n_pairs": 1104
117
+ }
118
+ },
119
+ "length_strata": {
120
+ "sft500": {
121
+ "le30": {
122
+ "auc": 0.5140409778657269,
123
+ "pair_cluster_bootstrap_95_ci": [
124
+ 0.48545373196926833,
125
+ 0.5437758777479221
126
+ ],
127
+ "n_rows": 600,
128
+ "n_pairs": 314
129
+ },
130
+ "31_100": {
131
+ "auc": 0.4948893936401343,
132
+ "pair_cluster_bootstrap_95_ci": [
133
+ 0.47467455745578646,
134
+ 0.5156451697499819
135
+ ],
136
+ "n_rows": 986,
137
+ "n_pairs": 512
138
+ },
139
+ "gt100": {
140
+ "auc": 0.5293846996908507,
141
+ "pair_cluster_bootstrap_95_ci": [
142
+ 0.5050641596909369,
143
+ 0.5542084363522486
144
+ ],
145
+ "n_rows": 622,
146
+ "n_pairs": 316
147
+ }
148
+ },
149
+ "grpo200": {
150
+ "le30": {
151
+ "auc": 0.5191771075363254,
152
+ "pair_cluster_bootstrap_95_ci": [
153
+ 0.4905740929128406,
154
+ 0.5472669014772544
155
+ ],
156
+ "n_rows": 600,
157
+ "n_pairs": 314
158
+ },
159
+ "31_100": {
160
+ "auc": 0.5177081275923365,
161
+ "pair_cluster_bootstrap_95_ci": [
162
+ 0.49770023793340473,
163
+ 0.5382370629459297
164
+ ],
165
+ "n_rows": 986,
166
+ "n_pairs": 512
167
+ },
168
+ "gt100": {
169
+ "auc": 0.5068395421694221,
170
+ "pair_cluster_bootstrap_95_ci": [
171
+ 0.48144603204624065,
172
+ 0.5319300813206864
173
+ ],
174
+ "n_rows": 622,
175
+ "n_pairs": 316
176
+ }
177
+ },
178
+ "grpo324": {
179
+ "le30": {
180
+ "auc": 0.5136463185512112,
181
+ "pair_cluster_bootstrap_95_ci": [
182
+ 0.4849384563954837,
183
+ 0.5424573319587573
184
+ ],
185
+ "n_rows": 600,
186
+ "n_pairs": 314
187
+ },
188
+ "31_100": {
189
+ "auc": 0.5058204127987359,
190
+ "pair_cluster_bootstrap_95_ci": [
191
+ 0.4845144253224206,
192
+ 0.5269618065416541
193
+ ],
194
+ "n_rows": 986,
195
+ "n_pairs": 512
196
+ },
197
+ "gt100": {
198
+ "auc": 0.5105875905993775,
199
+ "pair_cluster_bootstrap_95_ci": [
200
+ 0.4837444471601296,
201
+ 0.5362243862147521
202
+ ],
203
+ "n_rows": 622,
204
+ "n_pairs": 316
205
+ }
206
+ }
207
+ },
208
+ "test_touched": false
209
+ }
results/phase6/review23/e2/sft500_rollouts.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1f61d5ef59037a9311b5a21e3ab810a1370122799a70c6b1441322bf3efb0c6f
3
+ size 13687701
results/phase6/review23/e3/PROTOCOL.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Review #23 E3 — Frozen experiment protocol
2
+
3
+ **Status:** configuration frozen before any E3 model training. The exact machine-readable
4
+ configuration is `configs/review23/e3.json`; split IDs and source hashes are in
5
+ `frozen_pair_splits.json` and `data_preflight.json`. TEST was not opened.
6
+
7
+ ## Data and leakage controls
8
+
9
+ Date assignment uses the corpus `commit_date` plus the frozen
10
+ `data/processed/secvuleval_commit_dates.jsonl` cache. This reproduces 7,370 pre-2021 TRAIN
11
+ pairs and 862 2021 TRAIN holdout pairs. The raw corpus date field alone is incomplete and
12
+ must not be used to reconstruct this partition.
13
+
14
+ The code-hash preflight found eight normalized-function collisions between pre-2021 TRAIN
15
+ and the 2021 holdout, and six between the 2021 holdout and 2022 VALID. No collisions were
16
+ found between pre-2021 TRAIN and VALID. To keep the model-selection holdout independent of
17
+ both training inputs and final VALID, 14 affected 2021 pairs are quarantined before fitting;
18
+ the frozen selection holdout contains 848 pairs. Both rows of each retained pair stay
19
+ together. This deterministic leakage-control changes no labels, model, loss, or numerical
20
+ gate. No changes are made to the chronological VALID split.
21
+
22
+ The line-target audit found no invalid/missing diff line targets in pre-2021 TRAIN. The
23
+ positive line fraction is 2.5168%; `pos_weight` is fixed at 38.7326136 from pre-2021 TRAIN
24
+ line counts. Changed vulnerable-source lines are positive; patched-source lines and
25
+ unchanged vulnerable-source lines are negative. Positions are 1-based.
26
+
27
+ ## Frozen model and optimization
28
+
29
+ Qwen3-4B at revision `1cfa9a7208912126459214e8b04321603b3df60c` supplies final-layer token
30
+ representations. Inference inputs are only raw function source. A shared rank-64, alpha-128
31
+ LoRA adapter and a linear line-scoring head produce one score per visible source line;
32
+ the function score is unnormalized `logsumexp` over those scores. No pairwise margin loss
33
+ is used. The right-truncation limit is 8,192 tokens, aligned with the established SFT input
34
+ budget; truncation and lost positive-line coverage will be reported.
35
+
36
+ The pointwise BCE gives equal weight to SAFE and VULNERABLE rows. The line BCE is averaged
37
+ per function and then across rows, with the frozen positive weight above. Total loss is
38
+ `L_pointwise + 1.0 * L_line`. Training uses seeds 42/43/44, two epochs, LoRA dropout 0.05,
39
+ AdamW at 1e-4, cosine decay, 3% warmup, weight decay 0.01, and gradient clipping at 1.0.
40
+ Each microbatch contains one complete pair; accumulation over 32 pair batches yields 32
41
+ pairs / 64 rows per optimizer update. An epoch checkpoint is saved. The selected epoch per
42
+ seed maximizes clean-holdout row AUC; ties select the earlier epoch.
43
+
44
+ ## Controls and gates
45
+
46
+ The two registered ablations are no line loss and no pair batching. Each uses seed 42. The
47
+ shuffled-label negative control randomly swaps the binary labels within each training pair;
48
+ line loss is disabled for this control so original diff-line labels cannot reveal the true
49
+ label. Classical control is the pre-2021-trained character TF-IDF + averaged-SGD model
50
+ specified in the config. The length-only control is a standalone score based on negative
51
+ function line count, not a paired counterpart rule.
52
+
53
+ The clean 2021 holdout selects epoch and threshold. The threshold is chosen by balanced
54
+ accuracy only for secondary accuracy reporting; AUC is primary. Pair-cluster bootstrap CIs
55
+ use 5,000 draws and seed 42. All three primary seeds and both ablations are reported unless
56
+ seed 42's primary holdout AUC is more than 0.01 below the matched classical holdout AUC, in
57
+ which case the registered seed-1 early stop fires.
58
+
59
+ The Review #22 thresholds remain unchanged: stage holdout go at classical +0.02; final
60
+ VALID row AUC at least 0.600, paired-difference 95% CI versus the matched classical control
61
+ excluding zero, >100-line AUC at least 0.56, and train-to-VALID accuracy gap at most 3
62
+ points. A VALID AUC within ±0.02 of the established 0.570 classical reference is a failure.
63
+ VALID is used only for the single final comparison after all checkpoint/threshold choices;
64
+ it is not used for training or model selection. No TEST evaluation is permitted.
65
+
66
+ ## Resource and stop policy
67
+
68
+ E3 is expected to use approximately 9–10 GPU-hours; actual wall/GPU time and peak memory
69
+ will be recorded. E2 currently owns the GPU, so E3 training will start only after E2 exits
70
+ and its outputs are archived. No GRPO continuation, E4, or hyperparameter sweep is included.
results/phase6/review23/e3/classical_baseline.log ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "complete",
3
+ "control": "character TF-IDF 3-5 grams + averaged SGD logistic; fitted on pre-2021 TRAIN only",
4
+ "holdout": "clean 2021 TRAIN holdout after deterministic code-hash quarantine",
5
+ "row_auc": 0.5292975703097187,
6
+ "pair_cluster_bootstrap_95_ci": [
7
+ 0.5227328557482644,
8
+ 0.5362473821589089
9
+ ],
10
+ "length_bands_by_row_lines": {
11
+ "<=30": {
12
+ "n_rows": 431,
13
+ "row_auc": 0.5307017543859649,
14
+ "pair_cluster_bootstrap_95_ci": [
15
+ 0.5085753929979397,
16
+ 0.5529441893809033
17
+ ]
18
+ },
19
+ "31-100": {
20
+ "n_rows": 752,
21
+ "row_auc": 0.5251175950486295,
22
+ "pair_cluster_bootstrap_95_ci": [
23
+ 0.5126718551753621,
24
+ 0.5382221391834694
25
+ ]
26
+ },
27
+ ">100": {
28
+ "n_rows": 513,
29
+ "row_auc": 0.5296675891852438,
30
+ "pair_cluster_bootstrap_95_ci": [
31
+ 0.5172081433266134,
32
+ 0.5436165573705852
33
+ ]
34
+ }
35
+ },
36
+ "n_train_pairs": 7370,
37
+ "n_holdout_pairs": 848,
38
+ "n_holdout_rows": 1696,
39
+ "provenance": {
40
+ "corpus_sha256": "fda8efe71d0d74e9f0ca8d7b2f050481972363dbed80d364cc9271d83ea3435b",
41
+ "frozen_pair_splits_sha256": "594fbe05245bb553c9de9dd62cf2a23bf0b706302b0347fa9901de5b392261b4",
42
+ "test_read": false,
43
+ "valid_metrics_read": false
44
+ }
45
+ }
results/phase6/review23/e3/classical_holdout_baseline.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "complete",
3
+ "control": "character TF-IDF 3-5 grams + averaged SGD logistic; fitted on pre-2021 TRAIN only",
4
+ "holdout": "clean 2021 TRAIN holdout after deterministic code-hash quarantine",
5
+ "row_auc": 0.5292975703097187,
6
+ "pair_cluster_bootstrap_95_ci": [
7
+ 0.5227328557482644,
8
+ 0.5362473821589089
9
+ ],
10
+ "length_bands_by_row_lines": {
11
+ "<=30": {
12
+ "n_rows": 431,
13
+ "row_auc": 0.5307017543859649,
14
+ "pair_cluster_bootstrap_95_ci": [
15
+ 0.5085753929979397,
16
+ 0.5529441893809033
17
+ ]
18
+ },
19
+ "31-100": {
20
+ "n_rows": 752,
21
+ "row_auc": 0.5251175950486295,
22
+ "pair_cluster_bootstrap_95_ci": [
23
+ 0.5126718551753621,
24
+ 0.5382221391834694
25
+ ]
26
+ },
27
+ ">100": {
28
+ "n_rows": 513,
29
+ "row_auc": 0.5296675891852438,
30
+ "pair_cluster_bootstrap_95_ci": [
31
+ 0.5172081433266134,
32
+ 0.5436165573705852
33
+ ]
34
+ }
35
+ },
36
+ "n_train_pairs": 7370,
37
+ "n_holdout_pairs": 848,
38
+ "n_holdout_rows": 1696,
39
+ "provenance": {
40
+ "corpus_sha256": "fda8efe71d0d74e9f0ca8d7b2f050481972363dbed80d364cc9271d83ea3435b",
41
+ "frozen_pair_splits_sha256": "594fbe05245bb553c9de9dd62cf2a23bf0b706302b0347fa9901de5b392261b4",
42
+ "test_read": false,
43
+ "valid_metrics_read": false
44
+ }
45
+ }
results/phase6/review23/e3/data_preflight.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "status": "preflight_pass_with_deterministic_holdout_quarantine",
3
+ "date_resolution": "commit_date plus data/processed/secvuleval_commit_dates.jsonl",
4
+ "pair_counts": {
5
+ "chronological_train": 8232,
6
+ "pre_2021_train": 7370,
7
+ "2021_holdout_original": 862,
8
+ "2021_holdout_after_quarantine": 848,
9
+ "holdout_quarantined": 14,
10
+ "chronological_valid": 1104
11
+ },
12
+ "normalized_code_leakage": {
13
+ "normalization": "normalize CRLF via splitlines and remove trailing whitespace per line; preserve internal whitespace",
14
+ "pre2021_train_vs_2021_holdout_hashes": 8,
15
+ "2021_holdout_vs_valid_hashes": 6,
16
+ "pre2021_train_vs_valid_hashes": 0,
17
+ "post_quarantine_train_or_valid_overlap": 0,
18
+ "quarantine_rule": "exclude a 2021 pair from model selection if either function hash occurs in pre-2021 TRAIN or chronological VALID"
19
+ },
20
+ "line_target_audit_pre_2021": {
21
+ "positive_lines": 38349,
22
+ "negative_lines": 1485357,
23
+ "positive_fraction": 0.02516824111738091,
24
+ "invalid_targets": 0,
25
+ "line_numbering": "1-based source lines"
26
+ },
27
+ "provenance": {
28
+ "corpus_sha256": "fda8efe71d0d74e9f0ca8d7b2f050481972363dbed80d364cc9271d83ea3435b",
29
+ "train_split_sha256": "a365b114eecfb33fc9e08bda82e11c075530acb4db573cd8a4a29b9281503e4a",
30
+ "valid_split_sha256": "1b2f9ba17b1ce9853ef7628575c45bc07ccd0a89301254be9542d2729fa8d51d",
31
+ "date_cache_sha256": "ef914835991298957438343e76f11a77f928d1df67e8636953788e0df6fcada7",
32
+ "frozen_pair_splits_sha256": "594fbe05245bb553c9de9dd62cf2a23bf0b706302b0347fa9901de5b392261b4",
33
+ "test_read": false
34
+ }
35
+ }
results/phase6/review23/e3/frozen_pair_splits.json ADDED
The diff for this file is too large to render. See raw diff
 
scripts/evaluate_review23_e3_final.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Final, single-use VALID evaluation for the frozen Review #23 E3 runs."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ import random
7
+ import time
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ from sklearn.feature_extraction.text import TfidfVectorizer
14
+ from sklearn.linear_model import SGDClassifier
15
+ from sklearn.metrics import balanced_accuracy_score, roc_auc_score
16
+ from transformers import AutoModel, AutoTokenizer
17
+ from peft import PeftModel
18
+
19
+ from scripts.train_review23_e3 import (ROOT, BOOTSTRAPS, CONFIG_PATH, CORPUS_PATH,
20
+ SPLIT_PATH, TRAIN_SPLIT_PATH, VALID_SPLIT_PATH, OUT, Example, audit_token_coverage,
21
+ build_pairs, choose_threshold, collect_rows, metrics, pair_bootstrap_ci,
22
+ paired_auc_delta_ci)
23
+
24
+
25
+ def ci_by_pair(rows: list[dict], mask: np.ndarray | None = None) -> list[float]:
26
+ if mask is None:
27
+ use = rows
28
+ else:
29
+ use = [r for r, keep in zip(rows, mask, strict=True) if keep]
30
+ return pair_bootstrap_ci(use)
31
+
32
+
33
+ def summarize_rows(rows: list[dict], threshold: float) -> dict:
34
+ out = metrics(rows, threshold)
35
+ out["pair_cluster_bootstrap_95_ci"] = pair_bootstrap_ci(rows)
36
+ bands = {
37
+ "<=30": np.asarray([r["function_line_count"] <= 30 for r in rows]),
38
+ "31-100": np.asarray([30 < r["function_line_count"] <= 100 for r in rows]),
39
+ ">100": np.asarray([r["function_line_count"] > 100 for r in rows]),
40
+ }
41
+ out["by_function_length_lines"] = {}
42
+ for name, mask in bands.items():
43
+ subset = [r for r, keep in zip(rows, mask, strict=True) if keep]
44
+ if subset and len({int(r["target"]) for r in subset}) == 2:
45
+ out["by_function_length_lines"][name] = {
46
+ "n_rows": len(subset), "row_auc": float(roc_auc_score(
47
+ [int(r["target"]) for r in subset], [float(r["score"]) for r in subset])),
48
+ "pair_cluster_bootstrap_95_ci": ci_by_pair(rows, mask),
49
+ }
50
+ out["truncation"] = {
51
+ "rows": len(rows), "truncated_rows": sum(bool(r["truncated"]) for r in rows),
52
+ "positive_line_targets": sum(int(r["positive_lines_total"]) for r in rows),
53
+ "visible_positive_line_targets": sum(int(r["positive_lines_visible"]) for r in rows),
54
+ "vulnerable_rows_losing_all_positive_lines": sum(
55
+ int(r["target"]) == 1 and int(r["positive_lines_total"]) > 0 and
56
+ int(r["positive_lines_visible"]) == 0 for r in rows),
57
+ }
58
+ return out
59
+
60
+
61
+ def line_metrics(rows: list[dict], *, seed: int = 42, reps: int = BOOTSTRAPS) -> dict:
62
+ by_pair: dict[str, list[dict]] = {}
63
+ for row in rows:
64
+ if "line_scores" in row:
65
+ by_pair.setdefault(str(row["pair_id"]), []).append(row)
66
+
67
+ def auc_for(pairs: list[str]):
68
+ targets, scores = [], []
69
+ for pid in pairs:
70
+ for row in by_pair[pid]:
71
+ for line in row["line_scores"]:
72
+ targets.append(int(line["target"]))
73
+ scores.append(float(line["score"]))
74
+ if len(set(targets)) != 2:
75
+ return None
76
+ return float(roc_auc_score(targets, scores))
77
+
78
+ pair_ids = sorted(by_pair)
79
+ point = auc_for(pair_ids)
80
+ rng = np.random.default_rng(seed)
81
+ vals = []
82
+ for draw in rng.choice(pair_ids, size=(reps, len(pair_ids)), replace=True):
83
+ value = auc_for(list(draw))
84
+ if value is not None:
85
+ vals.append(value)
86
+ return {"line_auc_vs_diff_derived_targets": point,
87
+ "pair_cluster_bootstrap_95_ci": [float(x) for x in np.quantile(vals, [0.025, 0.975])],
88
+ "n_pairs": len(pair_ids),
89
+ "warning": "diff-derived changed lines are a proxy target, not adjudicated vulnerability evidence"}
90
+
91
+
92
+ def load_selected(config: dict, checkpoint: Path, device: torch.device):
93
+ model_cfg = config["model"]
94
+ try:
95
+ import flash_attn # noqa: F401
96
+ attention = "flash_attention_2"
97
+ except ImportError:
98
+ attention = "sdpa"
99
+ base = AutoModel.from_pretrained(model_cfg["id"], revision=model_cfg["revision"],
100
+ torch_dtype=torch.bfloat16, attn_implementation=attention, local_files_only=True)
101
+ encoder = PeftModel.from_pretrained(base, checkpoint / "adapter", is_trainable=False)
102
+ encoder.to(device); encoder.eval()
103
+ head = torch.nn.Linear(base.config.hidden_size, 1, dtype=torch.float32)
104
+ head.load_state_dict(torch.load(checkpoint / "line_head.pt", map_location="cpu", weights_only=True))
105
+ head.to(device); head.eval()
106
+ return encoder, head, attention
107
+
108
+
109
+ def matched_classical(pre_pairs: list[tuple[Example, Example]], eval_pairs: list[tuple[Example, Example]]) -> list[dict]:
110
+ train_rows = [x for pair in pre_pairs for x in pair]
111
+ eval_rows = [x for pair in eval_pairs for x in pair]
112
+ vec = TfidfVectorizer(analyzer="char", ngram_range=(3, 5), min_df=2,
113
+ max_features=300_000, sublinear_tf=True, dtype=np.float32)
114
+ xtr = vec.fit_transform([x.code for x in train_rows])
115
+ model = SGDClassifier(loss="log_loss", alpha=1e-5, max_iter=200, tol=1e-3,
116
+ random_state=42, average=True)
117
+ model.fit(xtr, np.asarray([x.target for x in train_rows], dtype=np.int8))
118
+ scores = model.decision_function(vec.transform([x.code for x in eval_rows]))
119
+ return [{"sample_id": x.sample_id, "pair_id": x.pair_id, "target": x.target,
120
+ "score": float(score), "function_line_count": len(x.code.splitlines()),
121
+ "truncated": False, "positive_lines_total": x.n_positive_original,
122
+ "positive_lines_visible": x.n_positive_visible}
123
+ for x, score in zip(eval_rows, scores, strict=True)]
124
+
125
+
126
+ def nested_seed_pair_bootstrap(seed_rows: list[list[dict]], baseline_rows: list[dict],
127
+ reps: int = BOOTSTRAPS, seed: int = 42) -> dict:
128
+ ids = sorted({str(r["pair_id"]) for r in baseline_rows})
129
+ base = {r["sample_id"]: r for r in baseline_rows}
130
+ model_maps = [{r["sample_id"]: r for r in rows} for rows in seed_rows]
131
+ pair_members = {pid: [r["sample_id"] for r in baseline_rows if str(r["pair_id"]) == pid]
132
+ for pid in ids}
133
+ rng = np.random.default_rng(seed)
134
+ auc_means, deltas = [], []
135
+ for _ in range(reps):
136
+ sampled_pairs = rng.choice(ids, size=len(ids), replace=True)
137
+ sampled_seeds = rng.integers(0, len(model_maps), size=len(model_maps))
138
+ idx_ids = [sid for pid in sampled_pairs for sid in pair_members[pid]]
139
+ y = [int(base[sid]["target"]) for sid in idx_ids]
140
+ aucs, diff = [], []
141
+ try:
142
+ base_auc = roc_auc_score(y, [float(base[sid]["score"]) for sid in idx_ids])
143
+ for index in sampled_seeds:
144
+ mapping = model_maps[int(index)]
145
+ score = [float(mapping[sid]["score"]) for sid in idx_ids]
146
+ model_auc = roc_auc_score(y, score)
147
+ aucs.append(model_auc); diff.append(model_auc - base_auc)
148
+ except ValueError:
149
+ continue
150
+ auc_means.append(float(np.mean(aucs))); deltas.append(float(np.mean(diff)))
151
+ point_aucs = [roc_auc_score([r["target"] for r in rows], [r["score"] for r in rows])
152
+ for rows in seed_rows]
153
+ point_base = roc_auc_score([r["target"] for r in baseline_rows], [r["score"] for r in baseline_rows])
154
+ return {"mean_seed_row_auc": float(np.mean(point_aucs)),
155
+ "seedwise_row_auc": [float(x) for x in point_aucs],
156
+ "nested_pair_and_seed_bootstrap_95_ci": [float(x) for x in np.quantile(auc_means, [0.025, 0.975])],
157
+ "mean_auc_delta_vs_matched_classical": float(np.mean(point_aucs) - point_base),
158
+ "nested_pair_and_seed_delta_ci95": [float(x) for x in np.quantile(deltas, [0.025, 0.975])],
159
+ "matched_classical_row_auc": float(point_base)}
160
+
161
+
162
+ def main() -> None:
163
+ config = json.loads(CONFIG_PATH.read_text())
164
+ status_path = OUT / "holdout_training_status.json"
165
+ if not status_path.is_file():
166
+ raise RuntimeError("E3 holdout training has not completed")
167
+ training = json.loads(status_path.read_text())
168
+ if training.get("status") != "training_complete_holdout_selected":
169
+ raise RuntimeError("E3 holdout stage is not terminal")
170
+ if training.get("test_read") is not False:
171
+ raise RuntimeError("TEST provenance check failed")
172
+ splits = json.loads(SPLIT_PATH.read_text())
173
+ all_ids = json.loads(TRAIN_SPLIT_PATH.read_text())
174
+ valid_ids = json.loads(VALID_SPLIT_PATH.read_text())
175
+ frame = pd.read_parquet(CORPUS_PATH, columns=["sample_id", "pair_id", "target", "func_vuln",
176
+ "func_patch", "patch_lines_vuln"])
177
+ frame["pair_id"] = frame.pair_id.astype(str)
178
+ from transformers import AutoTokenizer
179
+ tokenizer = AutoTokenizer.from_pretrained(config["model"]["id"], revision=config["model"]["revision"],
180
+ use_fast=True, local_files_only=True)
181
+ if tokenizer.pad_token_id is None:
182
+ tokenizer.pad_token = tokenizer.eos_token
183
+ max_len = int(config["model"]["max_sequence_length"])
184
+ train_pairs = build_pairs(frame, splits["train_pre_2021_pair_ids"], tokenizer, max_len)
185
+ valid_pairs = build_pairs(frame, sorted(map(str, valid_ids)), tokenizer, max_len)
186
+ device = torch.device("cuda")
187
+ models = []
188
+ for run in training["runs"]:
189
+ selection = run["selected"]
190
+ checkpoint = ROOT / selection["path"]
191
+ encoder, head, attention = load_selected(config, checkpoint, device)
192
+ threshold = choose_threshold([json.loads(line) for line in
193
+ (checkpoint / "holdout_rows.jsonl").read_text().splitlines()])
194
+ train_rows = collect_rows(encoder, head, train_pairs, int(tokenizer.pad_token_id), device)
195
+ valid_rows = collect_rows(encoder, head, valid_pairs, int(tokenizer.pad_token_id), device,
196
+ include_line_evidence=True)
197
+ models.append({"arm": run["arm"], "seed": run["seed"], "checkpoint": str(checkpoint.relative_to(ROOT)),
198
+ "threshold": threshold, "attention": attention,
199
+ "train_rows": train_rows, "valid_rows": valid_rows})
200
+ del encoder, head
201
+ torch.cuda.empty_cache()
202
+ print(json.dumps({"event": "final_model_scored", "arm": run["arm"], "seed": run["seed"]}), flush=True)
203
+
204
+ classical_rows = matched_classical(train_pairs, valid_pairs)
205
+ length_rows = [{"sample_id": x.sample_id, "pair_id": x.pair_id, "target": x.target,
206
+ "score": -float(len(x.code.splitlines())), "function_line_count": len(x.code.splitlines()),
207
+ "truncated": False, "positive_lines_total": x.n_positive_original,
208
+ "positive_lines_visible": x.n_positive_visible}
209
+ for pair in valid_pairs for x in pair]
210
+
211
+ final = {"status": "complete", "protocol": "Review #23 E3; one final VALID evaluation after holdout selection",
212
+ "config_sha256": hashlib.sha256(CONFIG_PATH.read_bytes()).hexdigest(),
213
+ "test_read": False, "valid_pairs": len(valid_pairs), "train_pairs": len(train_pairs),
214
+ "models": {}, "primary_three_seed_aggregate": None,
215
+ "controls": {}, "gates": {},
216
+ "provenance": {"corpus_sha256": hashlib.sha256(CORPUS_PATH.read_bytes()).hexdigest(),
217
+ "train_split_sha256": hashlib.sha256(TRAIN_SPLIT_PATH.read_bytes()).hexdigest(),
218
+ "valid_split_sha256": hashlib.sha256(VALID_SPLIT_PATH.read_bytes()).hexdigest(),
219
+ "frozen_pair_splits_sha256": hashlib.sha256(SPLIT_PATH.read_bytes()).hexdigest()}}
220
+ primary_valid = []
221
+ for model in models:
222
+ tr = summarize_rows(model["train_rows"], model["threshold"])
223
+ va = summarize_rows(model["valid_rows"], model["threshold"])
224
+ entry = {"arm": model["arm"], "seed": model["seed"], "checkpoint": model["checkpoint"],
225
+ "holdout_selected_threshold": model["threshold"], "train": tr, "valid": va,
226
+ "line_localization": line_metrics(model["valid_rows"])}
227
+ entry["valid_vs_classical_auc_delta"] = paired_auc_delta_ci(model["valid_rows"], classical_rows)
228
+ entry["train_valid_accuracy_gap"] = abs(tr["balanced_accuracy"] - va["balanced_accuracy"])
229
+ final["models"][f"{model['arm']}_seed{model['seed']}"] = entry
230
+ save_rows = model["valid_rows"]
231
+ with (OUT / f"valid_{model['arm']}_seed{model['seed']}.jsonl").open("w") as f:
232
+ for row in save_rows:
233
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
234
+ if model["arm"] == "primary":
235
+ primary_valid.append(model["valid_rows"])
236
+
237
+ final["controls"]["matched_classical"] = summarize_rows(classical_rows, 0.0)
238
+ final["controls"]["length_only_negative_line_count"] = summarize_rows(length_rows, 0.0)
239
+ with (OUT / "valid_classical_baseline.jsonl").open("w") as f:
240
+ for row in classical_rows:
241
+ f.write(json.dumps(row) + "\n")
242
+ if len(primary_valid) >= 2:
243
+ final["primary_three_seed_aggregate"] = nested_seed_pair_bootstrap(primary_valid, classical_rows)
244
+
245
+ if primary_valid:
246
+ mean_auc = float(np.mean([roc_auc_score([r["target"] for r in rows], [r["score"] for r in rows])
247
+ for rows in primary_valid]))
248
+ long_aucs = []
249
+ for rows in primary_valid:
250
+ long_rows = [r for r in rows if r["function_line_count"] > 100]
251
+ long_aucs.append(float(roc_auc_score([r["target"] for r in long_rows], [r["score"] for r in long_rows])))
252
+ aggregate = final["primary_three_seed_aggregate"] or {}
253
+ ci = aggregate.get("nested_pair_and_seed_delta_ci95")
254
+ avg_gap = float(np.mean([final["models"][f"primary_seed{m['seed']}"]["train_valid_accuracy_gap"]
255
+ for m in models if m["arm"] == "primary"]))
256
+ final["gates"] = {
257
+ "stage_holdout_go": training["stage_gate"].get("early_stop_fired") is False and
258
+ float(np.mean(training["stage_gate"]["primary_holdout_aucs"])) >=
259
+ float(training["classical_holdout_auc"]) + 0.02,
260
+ "valid_row_auc_at_least_0_600": mean_auc >= 0.600,
261
+ "valid_mean_long_auc_at_least_0_56": float(np.mean(long_aucs)) >= 0.56,
262
+ "paired_auc_delta_ci_excludes_zero": bool(ci and (ci[0] > 0 or ci[1] < 0)),
263
+ "train_valid_accuracy_gap_at_most_0_03": avg_gap <= 0.03,
264
+ "review22_classical_reference_0_570_failure_band": abs(mean_auc - 0.570) <= 0.02,
265
+ "primary_mean_valid_auc": mean_auc,
266
+ "primary_mean_long_valid_auc": float(np.mean(long_aucs)),
267
+ "mean_train_valid_balanced_accuracy_gap": avg_gap,
268
+ "mean_auc_delta_ci95": ci,
269
+ }
270
+ (OUT / "final_metrics.json").write_text(json.dumps(final, indent=2) + "\n")
271
+ print(json.dumps({"event": "e3_final_valid_complete", "gates": final["gates"],
272
+ "test_read": False}, indent=2), flush=True)
273
+
274
+
275
+ if __name__ == "__main__":
276
+ main()
scripts/evaluate_review23_e3_holdout_baseline.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fit E3's matched classical control and score only the clean 2021 holdout."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import json
6
+ from pathlib import Path
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ from sklearn.feature_extraction.text import TfidfVectorizer
11
+ from sklearn.linear_model import SGDClassifier
12
+ from sklearn.metrics import roc_auc_score
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ CORPUS = ROOT / "data/processed/corpus.parquet"
16
+ SPLITS = ROOT / "results/phase6/review23/e3/frozen_pair_splits.json"
17
+ OUT = ROOT / "results/phase6/review23/e3/classical_holdout_baseline.json"
18
+
19
+
20
+ def pair_bootstrap_ci(y: np.ndarray, score: np.ndarray, pair_ids: np.ndarray,
21
+ seed: int = 42, reps: int = 5000) -> list[float]:
22
+ unique = np.unique(pair_ids)
23
+ by_pair = {p: np.flatnonzero(pair_ids == p) for p in unique}
24
+ rng = np.random.default_rng(seed)
25
+ values = []
26
+ for draw in rng.integers(0, len(unique), size=(reps, len(unique))):
27
+ idx = np.concatenate([by_pair[unique[i]] for i in draw])
28
+ if np.unique(y[idx]).size == 2:
29
+ values.append(float(roc_auc_score(y[idx], score[idx])))
30
+ return [float(x) for x in np.quantile(values, [0.025, 0.975])]
31
+
32
+
33
+ def materialize(frame: pd.DataFrame, pair_ids: set[str]):
34
+ texts, labels, pairs, lines = [], [], [], []
35
+ subset = frame[frame.pair_id.astype(str).isin(pair_ids)]
36
+ for pair_id, group in subset.groupby("pair_id", sort=True):
37
+ if len(group) != 2 or set(group.target.astype(int)) != {0, 1}:
38
+ raise ValueError(f"pair integrity failure: {pair_id}")
39
+ for target in (0, 1):
40
+ row = group[group.target.astype(int) == target].iloc[0]
41
+ code = str(row.func_vuln if target else row.func_patch)
42
+ texts.append(code)
43
+ labels.append(target)
44
+ pairs.append(str(pair_id))
45
+ lines.append(len(code.splitlines()))
46
+ return texts, np.asarray(labels, dtype=np.int8), np.asarray(pairs, dtype=object), np.asarray(lines)
47
+
48
+
49
+ def main() -> dict:
50
+ splits = json.loads(SPLITS.read_text())
51
+ train_ids = set(splits["train_pre_2021_pair_ids"])
52
+ hold_ids = set(splits["selection_holdout_2021_pair_ids"])
53
+ if train_ids & hold_ids:
54
+ raise ValueError("TRAIN/holdout pair leakage")
55
+ frame = pd.read_parquet(CORPUS, columns=["pair_id", "target", "func_vuln", "func_patch"])
56
+ frame["pair_id"] = frame.pair_id.astype(str)
57
+ x_train, y_train, _, _ = materialize(frame, train_ids)
58
+ x_hold, y_hold, pairs, line_counts = materialize(frame, hold_ids)
59
+ vec = TfidfVectorizer(analyzer="char", ngram_range=(3, 5), min_df=2,
60
+ max_features=300_000, sublinear_tf=True, dtype=np.float32)
61
+ xtr = vec.fit_transform(x_train)
62
+ model = SGDClassifier(loss="log_loss", alpha=1e-5, max_iter=200, tol=1e-3,
63
+ random_state=42, average=True)
64
+ model.fit(xtr, y_train)
65
+ score = model.decision_function(vec.transform(x_hold))
66
+ result = {
67
+ "status": "complete",
68
+ "control": "character TF-IDF 3-5 grams + averaged SGD logistic; fitted on pre-2021 TRAIN only",
69
+ "holdout": "clean 2021 TRAIN holdout after deterministic code-hash quarantine",
70
+ "row_auc": float(roc_auc_score(y_hold, score)),
71
+ "pair_cluster_bootstrap_95_ci": pair_bootstrap_ci(y_hold, score, pairs),
72
+ "length_bands_by_row_lines": {},
73
+ "n_train_pairs": len(train_ids),
74
+ "n_holdout_pairs": len(hold_ids),
75
+ "n_holdout_rows": len(y_hold),
76
+ "provenance": {
77
+ "corpus_sha256": hashlib.sha256(CORPUS.read_bytes()).hexdigest(),
78
+ "frozen_pair_splits_sha256": hashlib.sha256(SPLITS.read_bytes()).hexdigest(),
79
+ "test_read": False,
80
+ "valid_metrics_read": False
81
+ }
82
+ }
83
+ for name, mask in {
84
+ "<=30": line_counts <= 30,
85
+ "31-100": (line_counts > 30) & (line_counts <= 100),
86
+ ">100": line_counts > 100,
87
+ }.items():
88
+ if np.unique(y_hold[mask]).size == 2:
89
+ result["length_bands_by_row_lines"][name] = {
90
+ "n_rows": int(mask.sum()),
91
+ "row_auc": float(roc_auc_score(y_hold[mask], score[mask])),
92
+ "pair_cluster_bootstrap_95_ci": pair_bootstrap_ci(y_hold[mask], score[mask], pairs[mask]),
93
+ }
94
+ OUT.parent.mkdir(parents=True, exist_ok=True)
95
+ OUT.write_text(json.dumps(result, indent=2) + "\n")
96
+ print(json.dumps(result, indent=2))
97
+ return result
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
scripts/prepare_review23_e3.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Freeze the leakage-checked TRAIN/holdout inputs for Review #23 E3.
2
+
3
+ This preparation reads chronological TRAIN, VALID, the corpus, and the cached
4
+ commit-date mapping. It never opens TEST and performs no model fitting.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ import re
11
+ from collections import defaultdict
12
+ from pathlib import Path
13
+
14
+ import pandas as pd
15
+
16
+ ROOT = Path(__file__).resolve().parents[1]
17
+ CORPUS = ROOT / "data/processed/corpus.parquet"
18
+ TRAIN = ROOT / "data/splits/chronological/train.json"
19
+ VALID = ROOT / "data/splits/chronological/valid.json"
20
+ DATE_CACHE = ROOT / "data/processed/secvuleval_commit_dates.jsonl"
21
+ OUT = ROOT / "results/phase6/review23/e3"
22
+
23
+
24
+ def digest(path: Path) -> str:
25
+ h = hashlib.sha256()
26
+ with path.open("rb") as f:
27
+ for block in iter(lambda: f.read(1024 * 1024), b""):
28
+ h.update(block)
29
+ return h.hexdigest()
30
+
31
+
32
+ def code_hash(code: object) -> str:
33
+ # Normalize line endings and trailing whitespace, preserving all internal
34
+ # token/string whitespace. This errs on the side of removing near-duplicates.
35
+ normalized = "\n".join(line.rstrip() for line in str(code).splitlines()).strip()
36
+ return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
37
+
38
+
39
+ def load_pair_ids() -> tuple[set[str], set[str]]:
40
+ train_ids = set(map(str, json.loads(TRAIN.read_text())))
41
+ valid_ids = set(map(str, json.loads(VALID.read_text())))
42
+ overlap = train_ids & valid_ids
43
+ if overlap:
44
+ raise ValueError(f"chronological TRAIN/VALID pair overlap: {len(overlap)}")
45
+ return train_ids, valid_ids
46
+
47
+
48
+ def main() -> dict:
49
+ train_ids, valid_ids = load_pair_ids()
50
+ dates: dict[str, str] = {}
51
+ for line in DATE_CACHE.read_text().splitlines():
52
+ if line.strip():
53
+ item = json.loads(line)
54
+ if item.get("date"):
55
+ dates[str(item["commit_id"])] = str(item["date"])
56
+
57
+ columns = ["sample_id", "pair_id", "target", "func_vuln", "func_patch",
58
+ "patch_lines_vuln", "commit_date", "commit_id"]
59
+ frame = pd.read_parquet(CORPUS, columns=columns)
60
+ frame["pair_id"] = frame.pair_id.astype(str)
61
+ frame = frame[frame.pair_id.isin(train_ids | valid_ids)].copy()
62
+ missing = frame.commit_date.isna()
63
+ frame.loc[missing, "commit_date"] = frame.loc[missing, "commit_id"].astype(str).map(dates)
64
+ parsed = pd.to_datetime(frame.commit_date, utc=True, format="mixed", errors="coerce")
65
+ frame["year"] = parsed.dt.year
66
+
67
+ by_pair = {}
68
+ for pair_id, group in frame.groupby("pair_id", sort=True):
69
+ if len(group) != 2 or set(group.target.astype(int)) != {0, 1}:
70
+ raise ValueError(f"pair integrity failure: {pair_id}")
71
+ years = set(group.year.dropna().astype(int))
72
+ if len(years) > 1:
73
+ raise ValueError(f"conflicting dates within pair: {pair_id}")
74
+ by_pair[str(pair_id)] = group
75
+
76
+ train_year: dict[str, int] = {}
77
+ missing_train_date = []
78
+ for pair_id in train_ids:
79
+ group = by_pair[pair_id]
80
+ years = group.year.dropna().astype(int).unique()
81
+ if len(years) != 1:
82
+ missing_train_date.append(pair_id)
83
+ else:
84
+ train_year[pair_id] = int(years[0])
85
+ if missing_train_date:
86
+ raise ValueError(f"TRAIN pairs without resolved dates: {len(missing_train_date)}")
87
+ pre_ids = {p for p, y in train_year.items() if y < 2021}
88
+ hold_ids = {p for p, y in train_year.items() if y == 2021}
89
+ unexpected = {p for p, y in train_year.items() if y > 2021}
90
+ if len(pre_ids) != 7370 or len(hold_ids) != 862 or unexpected:
91
+ raise ValueError(f"unexpected forward split: pre={len(pre_ids)}, holdout={len(hold_ids)}, post={len(unexpected)}")
92
+ valid_years = {
93
+ int(year)
94
+ for pair_id in valid_ids
95
+ for year in by_pair[pair_id].year.dropna().astype(int).unique()
96
+ }
97
+ if valid_years != {2022}:
98
+ raise ValueError(f"chronological VALID date years are not exclusively 2022: {sorted(valid_years)}")
99
+
100
+ def codes_for(ids: set[str]):
101
+ for pair_id in ids:
102
+ group = by_pair[pair_id]
103
+ vuln = group[group.target.astype(int) == 1].iloc[0]
104
+ safe = group[group.target.astype(int) == 0].iloc[0]
105
+ yield pair_id, str(vuln.func_vuln), str(safe.func_patch)
106
+
107
+ def hash_index(ids: set[str]) -> dict[str, set[str]]:
108
+ index: dict[str, set[str]] = defaultdict(set)
109
+ for pair_id, vuln, safe in codes_for(ids):
110
+ index[code_hash(vuln)].add(pair_id)
111
+ index[code_hash(safe)].add(pair_id)
112
+ return index
113
+
114
+ pre_hashes = hash_index(pre_ids)
115
+ hold_hashes = hash_index(hold_ids)
116
+ valid_hashes = hash_index(valid_ids)
117
+ pre_hold_collisions = set(pre_hashes) & set(hold_hashes)
118
+ hold_valid_collisions = set(hold_hashes) & set(valid_hashes)
119
+ pre_valid_collisions = set(pre_hashes) & set(valid_hashes)
120
+ if pre_valid_collisions:
121
+ raise ValueError(f"pre-2021 TRAIN has normalized-code overlap with VALID: {len(pre_valid_collisions)}")
122
+
123
+ excluded_holdout = {
124
+ pair_id
125
+ for code_digest in pre_hold_collisions | hold_valid_collisions
126
+ for pair_id in hold_hashes[code_digest]
127
+ }
128
+ clean_holdout = hold_ids - excluded_holdout
129
+ clean_hold_hashes = hash_index(clean_holdout)
130
+ if set(clean_hold_hashes) & (set(pre_hashes) | set(valid_hashes)):
131
+ raise AssertionError("duplicate-code leakage remains after holdout quarantine")
132
+
133
+ pos_lines = neg_lines = line_errors = 0
134
+ for pair_id in pre_ids:
135
+ group = by_pair[pair_id]
136
+ vuln = group[group.target.astype(int) == 1].iloc[0]
137
+ safe = group[group.target.astype(int) == 0].iloc[0]
138
+ for row, code, is_vuln in ((vuln, str(vuln.func_vuln), True),
139
+ (safe, str(safe.func_patch), False)):
140
+ raw = row.patch_lines_vuln
141
+ patches = [] if not is_vuln or raw is None else [int(x) for x in list(raw)]
142
+ n_lines = len(code.splitlines())
143
+ if is_vuln and not patches:
144
+ line_errors += 1
145
+ if any(x < 1 or x > n_lines for x in patches):
146
+ line_errors += 1
147
+ pos_lines += len(patches)
148
+ neg_lines += n_lines - len(patches)
149
+ if line_errors:
150
+ raise ValueError(f"invalid or missing line targets in pre-2021 TRAIN: {line_errors}")
151
+
152
+ split_payload = {
153
+ "protocol": "Review #23 E3 frozen pair splits",
154
+ "train_pre_2021_pair_ids": sorted(pre_ids),
155
+ "selection_holdout_2021_pair_ids": sorted(clean_holdout),
156
+ "holdout_quarantined_duplicate_code_pair_ids": sorted(excluded_holdout),
157
+ }
158
+ OUT.mkdir(parents=True, exist_ok=True)
159
+ split_path = OUT / "frozen_pair_splits.json"
160
+ split_path.write_text(json.dumps(split_payload, indent=2) + "\n")
161
+ audit = {
162
+ "status": "preflight_pass_with_deterministic_holdout_quarantine",
163
+ "date_resolution": "commit_date plus data/processed/secvuleval_commit_dates.jsonl",
164
+ "pair_counts": {"chronological_train": len(train_ids), "pre_2021_train": len(pre_ids),
165
+ "2021_holdout_original": len(hold_ids), "2021_holdout_after_quarantine": len(clean_holdout),
166
+ "holdout_quarantined": len(excluded_holdout), "chronological_valid": len(valid_ids)},
167
+ "normalized_code_leakage": {
168
+ "normalization": "normalize CRLF via splitlines and remove trailing whitespace per line; preserve internal whitespace",
169
+ "pre2021_train_vs_2021_holdout_hashes": len(pre_hold_collisions),
170
+ "2021_holdout_vs_valid_hashes": len(hold_valid_collisions),
171
+ "pre2021_train_vs_valid_hashes": len(pre_valid_collisions),
172
+ "post_quarantine_train_or_valid_overlap": 0,
173
+ "quarantine_rule": "exclude a 2021 pair from model selection if either function hash occurs in pre-2021 TRAIN or chronological VALID",
174
+ },
175
+ "line_target_audit_pre_2021": {"positive_lines": pos_lines, "negative_lines": neg_lines,
176
+ "positive_fraction": pos_lines / (pos_lines + neg_lines),
177
+ "invalid_targets": line_errors, "line_numbering": "1-based source lines"},
178
+ "provenance": {"corpus_sha256": digest(CORPUS), "train_split_sha256": digest(TRAIN),
179
+ "valid_split_sha256": digest(VALID), "date_cache_sha256": digest(DATE_CACHE),
180
+ "frozen_pair_splits_sha256": digest(split_path), "test_read": False},
181
+ }
182
+ (OUT / "data_preflight.json").write_text(json.dumps(audit, indent=2) + "\n")
183
+ print(json.dumps(audit, indent=2))
184
+ return audit
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()
scripts/train_review23_e3.py ADDED
@@ -0,0 +1,553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Review #23 E3 pair-balanced, evidence-first line detector.
2
+
3
+ Training and checkpoint selection use pre-2021 TRAIN and the clean 2021 TRAIN
4
+ holdout only. Chronological VALID is opened only in the final evaluation block;
5
+ TEST is never read. See configs/review23/e3.json and its frozen protocol.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import bisect
11
+ import hashlib
12
+ import json
13
+ import math
14
+ import random
15
+ import time
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ from sklearn.metrics import balanced_accuracy_score, roc_auc_score
25
+ from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ CONFIG_PATH = ROOT / "configs/review23/e3.json"
29
+ SPLIT_PATH = ROOT / "results/phase6/review23/e3/frozen_pair_splits.json"
30
+ PREFLIGHT_PATH = ROOT / "results/phase6/review23/e3/data_preflight.json"
31
+ BASELINE_PATH = ROOT / "results/phase6/review23/e3/classical_holdout_baseline.json"
32
+ CORPUS_PATH = ROOT / "data/processed/corpus.parquet"
33
+ TRAIN_SPLIT_PATH = ROOT / "data/splits/chronological/train.json"
34
+ VALID_SPLIT_PATH = ROOT / "data/splits/chronological/valid.json"
35
+ OUT = ROOT / "results/phase6/review23/e3"
36
+ BOOTSTRAPS = 5000
37
+
38
+
39
+ def sha(path: Path) -> str:
40
+ h = hashlib.sha256()
41
+ with path.open("rb") as stream:
42
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
43
+ h.update(block)
44
+ return h.hexdigest()
45
+
46
+
47
+ @dataclass
48
+ class Example:
49
+ sample_id: str
50
+ pair_id: str
51
+ target: int
52
+ code: str
53
+ input_ids: np.ndarray
54
+ token_lines: np.ndarray
55
+ line_numbers: np.ndarray # 1-based physical source lines
56
+ line_targets: np.ndarray
57
+ n_original_tokens: int
58
+ n_positive_original: int
59
+ n_positive_visible: int
60
+
61
+
62
+ def encode_example(tokenizer, sample_id: str, pair_id: str, target: int,
63
+ code: str, positive_lines: set[int], max_length: int) -> Example:
64
+ enc = tokenizer(code, add_special_tokens=False, truncation=False,
65
+ return_offsets_mapping=True)
66
+ original_ids = enc["input_ids"]
67
+ offsets = enc["offset_mapping"]
68
+ if not original_ids:
69
+ raise ValueError(f"empty token sequence: {sample_id}")
70
+ visible_ids = original_ids[:max_length]
71
+ visible_offsets = offsets[:max_length]
72
+ newline_positions = [i for i, char in enumerate(code) if char == "\n"]
73
+ token_physical = []
74
+ for start, end in visible_offsets:
75
+ if end <= start:
76
+ token_physical.append(-1)
77
+ else:
78
+ token_physical.append(bisect.bisect_left(newline_positions, start))
79
+ physical_lines = sorted(set(token_physical) - {-1})
80
+ if not physical_lines:
81
+ raise ValueError(f"no source-line tokens after tokenization: {sample_id}")
82
+ compact = {line: index for index, line in enumerate(physical_lines)}
83
+ token_lines = np.asarray([compact.get(line, -1) for line in token_physical], dtype=np.int32)
84
+ line_numbers = np.asarray([line + 1 for line in physical_lines], dtype=np.int32)
85
+ positives = positive_lines if target == 1 else set()
86
+ line_targets = np.asarray([int(int(line) in positives) for line in line_numbers], dtype=np.float32)
87
+ return Example(
88
+ sample_id=sample_id, pair_id=pair_id, target=int(target), code=code,
89
+ input_ids=np.asarray(visible_ids, dtype=np.int32), token_lines=token_lines,
90
+ line_numbers=line_numbers, line_targets=line_targets,
91
+ n_original_tokens=len(original_ids), n_positive_original=len(positives),
92
+ n_positive_visible=int(line_targets.sum()),
93
+ )
94
+
95
+
96
+ def pool_tokens_to_lines(hidden: torch.Tensor, token_lines: torch.Tensor,
97
+ line_counts: list[int]) -> tuple[torch.Tensor, torch.Tensor]:
98
+ """Mean-pool token states per compact visible line; padding ids are -1."""
99
+ batch, _, width = hidden.shape
100
+ max_lines = max(line_counts)
101
+ valid = token_lines >= 0
102
+ index = token_lines.clamp_min(0)
103
+ expanded = index.unsqueeze(-1).expand(batch, index.shape[1], width)
104
+ source = hidden * valid.unsqueeze(-1).to(hidden.dtype)
105
+ sums = hidden.new_zeros((batch, max_lines, width)).scatter_add_(1, expanded, source)
106
+ counts = hidden.new_zeros((batch, max_lines)).scatter_add_(
107
+ 1, index, valid.to(hidden.dtype))
108
+ means = sums / counts.clamp_min(1).unsqueeze(-1)
109
+ mask = torch.arange(max_lines, device=hidden.device).unsqueeze(0) < torch.tensor(
110
+ line_counts, device=hidden.device).unsqueeze(1)
111
+ return means, mask
112
+
113
+
114
+ def collate(examples: list[Example], pad_id: int, device: torch.device):
115
+ max_tokens = max(len(x.input_ids) for x in examples)
116
+ b = len(examples)
117
+ ids = torch.full((b, max_tokens), pad_id, dtype=torch.long)
118
+ attn = torch.zeros((b, max_tokens), dtype=torch.long)
119
+ line_map = torch.full((b, max_tokens), -1, dtype=torch.long)
120
+ line_counts, targets = [], []
121
+ for i, ex in enumerate(examples):
122
+ n = len(ex.input_ids)
123
+ ids[i, :n] = torch.from_numpy(ex.input_ids.astype(np.int64, copy=False))
124
+ attn[i, :n] = 1
125
+ line_map[i, :n] = torch.from_numpy(ex.token_lines.astype(np.int64, copy=False))
126
+ line_counts.append(len(ex.line_numbers))
127
+ targets.append(ex.line_targets)
128
+ max_lines = max(line_counts)
129
+ line_targets = torch.zeros((b, max_lines), dtype=torch.float32)
130
+ line_mask = torch.zeros((b, max_lines), dtype=torch.bool)
131
+ for i, target in enumerate(targets):
132
+ line_targets[i, :len(target)] = torch.from_numpy(target)
133
+ line_mask[i, :len(target)] = True
134
+ return (ids.to(device), attn.to(device), line_map.to(device), line_counts,
135
+ line_targets.to(device), line_mask.to(device))
136
+
137
+
138
+ def forward_scores(encoder, line_head, batch):
139
+ ids, attn, token_lines, line_counts, line_targets, line_mask = batch
140
+ out = encoder(input_ids=ids, attention_mask=attn, return_dict=True)
141
+ hidden = out.last_hidden_state
142
+ pooled, visible_mask = pool_tokens_to_lines(hidden, token_lines, line_counts)
143
+ line_scores = line_head(pooled.float()).squeeze(-1).float()
144
+ line_scores = line_scores.masked_fill(~visible_mask, float("-inf"))
145
+ function_scores = torch.logsumexp(line_scores, dim=1)
146
+ return function_scores, line_scores, visible_mask, line_targets, line_mask
147
+
148
+
149
+ def loss_for_batch(encoder, line_head, batch, labels: torch.Tensor,
150
+ pos_weight: float, line_weight: float) -> tuple[torch.Tensor, dict]:
151
+ function_scores, line_scores, visible_mask, line_targets, line_mask = forward_scores(
152
+ encoder, line_head, batch)
153
+ point = F.binary_cross_entropy_with_logits(function_scores, labels.float())
154
+ row_losses = []
155
+ pw = torch.tensor(pos_weight, dtype=torch.float32, device=labels.device)
156
+ for i in range(len(labels)):
157
+ n = int(line_mask[i].sum().item())
158
+ row_losses.append(F.binary_cross_entropy_with_logits(
159
+ line_scores[i, :n], line_targets[i, :n], pos_weight=pw))
160
+ line = torch.stack(row_losses).mean()
161
+ total = point + line_weight * line
162
+ return total, {"point": float(point.detach()), "line": float(line.detach())}
163
+
164
+
165
+ def metrics(rows: list[dict], threshold: float | None = None) -> dict:
166
+ y = np.asarray([int(r["target"]) for r in rows], dtype=np.int8)
167
+ s = np.asarray([float(r["score"]) for r in rows], dtype=np.float64)
168
+ pairs = np.asarray([str(r["pair_id"]) for r in rows], dtype=object)
169
+ if np.unique(y).size != 2:
170
+ raise ValueError("AUC requires both classes")
171
+ result = {"row_auc": float(roc_auc_score(y, s)), "n_rows": len(rows),
172
+ "n_pairs": len(np.unique(pairs))}
173
+ if threshold is not None:
174
+ pred = s >= threshold
175
+ result["threshold"] = float(threshold)
176
+ result["balanced_accuracy"] = float(balanced_accuracy_score(y, pred))
177
+ for label, name in ((0, "safe_accuracy"), (1, "vulnerable_accuracy")):
178
+ mask = y == label
179
+ result[name] = float((pred[mask] == y[mask]).mean())
180
+ result["predicted_vulnerable_fraction"] = float(pred.mean())
181
+ return result
182
+
183
+
184
+ def pair_bootstrap_ci(rows: list[dict], score_key: str = "score", *,
185
+ seed: int = 42, reps: int = BOOTSTRAPS) -> list[float]:
186
+ y = np.asarray([int(r["target"]) for r in rows], dtype=np.int8)
187
+ s = np.asarray([float(r[score_key]) for r in rows], dtype=float)
188
+ pair = np.asarray([str(r["pair_id"]) for r in rows], dtype=object)
189
+ unique = np.unique(pair)
190
+ by_pair = {p: np.flatnonzero(pair == p) for p in unique}
191
+ rng = np.random.default_rng(seed)
192
+ vals = []
193
+ for draw in rng.integers(0, len(unique), size=(reps, len(unique))):
194
+ ix = np.concatenate([by_pair[unique[i]] for i in draw])
195
+ if np.unique(y[ix]).size == 2:
196
+ vals.append(float(roc_auc_score(y[ix], s[ix])))
197
+ return [float(x) for x in np.quantile(vals, [0.025, 0.975])]
198
+
199
+
200
+ def paired_auc_delta_ci(rows_a: list[dict], rows_b: list[dict], *, reps: int = BOOTSTRAPS,
201
+ seed: int = 117) -> dict:
202
+ a = {r["sample_id"]: r for r in rows_a}
203
+ b = {r["sample_id"]: r for r in rows_b}
204
+ ids = sorted(set(a) & set(b))
205
+ if len(ids) != len(a) or len(ids) != len(b):
206
+ raise ValueError("paired AUC comparison row sets differ")
207
+ ordered_a, ordered_b = [a[k] for k in ids], [b[k] for k in ids]
208
+ pair_to_idx: dict[str, list[int]] = {}
209
+ for i, row in enumerate(ordered_a):
210
+ pair_to_idx.setdefault(str(row["pair_id"]), []).append(i)
211
+ unique = np.asarray(sorted(pair_to_idx), dtype=object)
212
+ y = np.asarray([int(r["target"]) for r in ordered_a], dtype=np.int8)
213
+ sa = np.asarray([float(r["score"]) for r in ordered_a])
214
+ sb = np.asarray([float(r["score"]) for r in ordered_b])
215
+ point = float(roc_auc_score(y, sb) - roc_auc_score(y, sa))
216
+ rng = np.random.default_rng(seed)
217
+ values = []
218
+ for draw in rng.integers(0, len(unique), size=(reps, len(unique))):
219
+ idx = np.concatenate([pair_to_idx[unique[i]] for i in draw])
220
+ if np.unique(y[idx]).size == 2:
221
+ values.append(float(roc_auc_score(y[idx], sb[idx]) - roc_auc_score(y[idx], sa[idx])))
222
+ return {"auc_delta": point,
223
+ "pair_cluster_bootstrap_95_ci": [float(x) for x in np.quantile(values, [0.025, 0.975])],
224
+ "n_pairs": len(unique)}
225
+
226
+
227
+ def choose_threshold(rows: list[dict]) -> float:
228
+ y = np.asarray([int(r["target"]) for r in rows], dtype=np.int8)
229
+ score = np.asarray([float(r["score"]) for r in rows])
230
+ thresholds = np.concatenate(([-np.inf], np.unique(score), [np.inf]))
231
+ values = [balanced_accuracy_score(y, score >= t) for t in thresholds]
232
+ best = max(values)
233
+ ties = [float(t) for t, value in zip(thresholds, values, strict=True) if value == best]
234
+ return min(ties, key=lambda x: (abs(x), x))
235
+
236
+
237
+ def collect_rows(encoder, head, pairs: list[tuple[Example, Example]], pad_id: int,
238
+ device: torch.device, *, include_line_evidence: bool = False,
239
+ pair_batch_size: int = 4) -> list[dict]:
240
+ rows = []
241
+ encoder.eval(); head.eval()
242
+ with torch.inference_mode():
243
+ for offset in range(0, len(pairs), pair_batch_size):
244
+ pair_batch = pairs[offset:offset + pair_batch_size]
245
+ examples = [ex for pair in pair_batch for ex in pair]
246
+ batch = collate(examples, pad_id, device)
247
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
248
+ funcs, line_scores, line_mask, _, _ = forward_scores(encoder, head, batch)
249
+ vals = funcs.float().cpu().numpy()
250
+ for i, ex in enumerate(examples):
251
+ row = {"sample_id": ex.sample_id, "pair_id": ex.pair_id,
252
+ "target": ex.target, "score": float(vals[i]),
253
+ "function_line_count": len(ex.code.splitlines()),
254
+ "truncated": ex.n_original_tokens > len(ex.input_ids),
255
+ "original_tokens": ex.n_original_tokens,
256
+ "visible_tokens": len(ex.input_ids),
257
+ "positive_lines_total": ex.n_positive_original,
258
+ "positive_lines_visible": ex.n_positive_visible}
259
+ if include_line_evidence:
260
+ n = len(ex.line_numbers)
261
+ line_v = line_scores[i, :n].float().cpu().numpy()
262
+ top = np.argsort(-line_v, kind="stable")[:min(5, n)]
263
+ src_lines = ex.code.splitlines()
264
+ row["top_lines"] = [
265
+ {"line": int(ex.line_numbers[j]), "score": float(line_v[j]),
266
+ "source": src_lines[int(ex.line_numbers[j]) - 1] if int(ex.line_numbers[j]) <= len(src_lines) else ""}
267
+ for j in top]
268
+ row["line_scores"] = [
269
+ {"line": int(line), "score": float(val), "target": int(ex.line_targets[j])}
270
+ for j, (line, val) in enumerate(zip(ex.line_numbers, line_v, strict=True))]
271
+ rows.append(row)
272
+ return rows
273
+
274
+
275
+ def save_jsonl(path: Path, rows: list[dict]) -> None:
276
+ with path.open("w") as f:
277
+ for row in rows:
278
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
279
+
280
+
281
+ def build_pairs(frame: pd.DataFrame, pair_ids: list[str], tokenizer,
282
+ max_length: int) -> list[tuple[Example, Example]]:
283
+ subset = frame[frame.pair_id.astype(str).isin(set(pair_ids))]
284
+ pairs = []
285
+ for pair_id, group in subset.groupby("pair_id", sort=True):
286
+ if len(group) != 2 or set(group.target.astype(int)) != {0, 1}:
287
+ raise ValueError(f"pair integrity failure: {pair_id}")
288
+ v = group[group.target.astype(int) == 1].iloc[0]
289
+ s = group[group.target.astype(int) == 0].iloc[0]
290
+ raw = v.patch_lines_vuln
291
+ positives = set(map(int, raw.tolist() if hasattr(raw, "tolist") else (raw or [])))
292
+ safe = encode_example(tokenizer, str(s.sample_id), str(pair_id), 0,
293
+ str(s.func_patch), set(), max_length)
294
+ vuln = encode_example(tokenizer, str(v.sample_id), str(pair_id), 1,
295
+ str(v.func_vuln), positives, max_length)
296
+ pairs.append((safe, vuln))
297
+ if len(pairs) != len(pair_ids):
298
+ raise ValueError(f"pair count mismatch: expected {len(pair_ids)}, got {len(pairs)}")
299
+ return pairs
300
+
301
+
302
+ def audit_token_coverage(pairs_by_split: dict[str, list[tuple[Example, Example]]]) -> dict:
303
+ out = {}
304
+ for name, pairs in pairs_by_split.items():
305
+ rows = [ex for pair in pairs for ex in pair]
306
+ vuln = [ex for ex in rows if ex.target == 1]
307
+ out[name] = {
308
+ "rows": len(rows),
309
+ "truncated_rows": sum(ex.n_original_tokens > len(ex.input_ids) for ex in rows),
310
+ "truncated_fraction": float(np.mean([ex.n_original_tokens > len(ex.input_ids) for ex in rows])),
311
+ "vulnerable_rows_with_positive_line_targets": len(vuln),
312
+ "vulnerable_rows_with_no_visible_positive_after_truncation": sum(
313
+ ex.n_positive_original > 0 and ex.n_positive_visible == 0 for ex in vuln),
314
+ "positive_line_targets_total": sum(ex.n_positive_original for ex in vuln),
315
+ "positive_line_targets_visible": sum(ex.n_positive_visible for ex in vuln),
316
+ }
317
+ return out
318
+
319
+
320
+ def load_encoder_and_head(config: dict, *, device: torch.device):
321
+ from peft import LoraConfig, get_peft_model
322
+ from transformers import AutoModel, AutoTokenizer
323
+ model_cfg = config["model"]
324
+ tokenizer = AutoTokenizer.from_pretrained(model_cfg["id"], revision=model_cfg["revision"],
325
+ use_fast=True, local_files_only=True)
326
+ if not tokenizer.is_fast:
327
+ raise RuntimeError("fast tokenizer required for source-line offset mapping")
328
+ if tokenizer.pad_token_id is None:
329
+ tokenizer.pad_token = tokenizer.eos_token
330
+ try:
331
+ import flash_attn # noqa: F401
332
+ attention = "flash_attention_2"
333
+ except ImportError:
334
+ attention = "sdpa"
335
+ base = AutoModel.from_pretrained(model_cfg["id"], revision=model_cfg["revision"],
336
+ torch_dtype=torch.bfloat16, attn_implementation=attention, local_files_only=True)
337
+ base.config.use_cache = False
338
+ target = config["architecture"]["lora"]["target_modules"]
339
+ lora = LoraConfig(r=config["architecture"]["lora"]["rank"],
340
+ lora_alpha=config["architecture"]["lora"]["alpha"],
341
+ lora_dropout=config["architecture"]["lora"]["dropout"],
342
+ target_modules=target, bias="none")
343
+ encoder = get_peft_model(base, lora)
344
+ encoder.gradient_checkpointing_enable()
345
+ if hasattr(encoder, "enable_input_require_grads"):
346
+ encoder.enable_input_require_grads()
347
+ encoder.to(device)
348
+ head = nn.Linear(base.config.hidden_size, 1, dtype=torch.float32).to(device)
349
+ return encoder, head, tokenizer, attention
350
+
351
+
352
+ def train_one(config: dict, pairs: list[tuple[Example, Example]], holdout: list[tuple[Example, Example]],
353
+ *, arm: str, seed: int, device: torch.device, output_dir: Path,
354
+ line_weight: float, pair_batching: bool, shuffled_labels: bool,
355
+ pad_id: int) -> dict:
356
+ random.seed(seed); np.random.seed(seed); torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
357
+ encoder, head, _, attention = load_encoder_and_head(config, device=device)
358
+ train_cfg = config["training"]
359
+ micro_pairs = int(train_cfg["pair_microbatch_size"])
360
+ accum = int(train_cfg["gradient_accumulation_pair_batches"])
361
+ updates_per_epoch = math.ceil(len(pairs) / (micro_pairs * accum))
362
+ total_steps = int(train_cfg["epochs"]) * updates_per_epoch
363
+ parameters = [p for p in encoder.parameters() if p.requires_grad] + list(head.parameters())
364
+ optimizer = torch.optim.AdamW(parameters, lr=float(train_cfg["learning_rate"]),
365
+ weight_decay=float(train_cfg["weight_decay"]))
366
+ warmup_steps = max(1, int(total_steps * float(train_cfg["warmup_ratio"])))
367
+ warm = LinearLR(optimizer, start_factor=0.1, end_factor=1.0, total_iters=warmup_steps)
368
+ cosine = CosineAnnealingLR(optimizer, T_max=max(1, total_steps - warmup_steps), eta_min=0.0)
369
+ scheduler = SequentialLR(optimizer, [warm, cosine], milestones=[warmup_steps])
370
+ pos_weight = float(config["objective"]["line_positive_weight"])
371
+ history = []
372
+ selected = None
373
+ started = time.time()
374
+ run_dir = output_dir / "checkpoints" / arm / f"seed-{seed}"
375
+ run_dir.mkdir(parents=True, exist_ok=True)
376
+
377
+ for epoch in range(int(train_cfg["epochs"])):
378
+ encoder.train(); head.train()
379
+ epoch_pairs = list(pairs)
380
+ random.Random(seed + epoch).shuffle(epoch_pairs)
381
+ if shuffled_labels:
382
+ flipped = []
383
+ rng = random.Random(seed + 9000 + epoch)
384
+ for safe, vuln in epoch_pairs:
385
+ if rng.random() < 0.5:
386
+ safe, vuln = replace_target(safe, 1), replace_target(vuln, 0)
387
+ else:
388
+ safe, vuln = replace_target(safe, 0), replace_target(vuln, 1)
389
+ flipped.append((safe, vuln))
390
+ epoch_pairs = flipped
391
+ if pair_batching:
392
+ microbatches = [[*epoch_pairs[i:i + micro_pairs]] for i in range(0, len(epoch_pairs), micro_pairs)]
393
+ microbatches = [[ex for pair in batch for ex in pair] for batch in microbatches]
394
+ else:
395
+ rows = [ex for pair in epoch_pairs for ex in pair]
396
+ random.Random(seed + 5000 + epoch).shuffle(rows)
397
+ microbatches = [rows[i:i + 2 * micro_pairs] for i in range(0, len(rows), 2 * micro_pairs)]
398
+
399
+ epoch_point = epoch_line = 0.0
400
+ optimizer.zero_grad(set_to_none=True)
401
+ for group_start in range(0, len(microbatches), accum):
402
+ group = microbatches[group_start:group_start + accum]
403
+ optimizer.zero_grad(set_to_none=True)
404
+ for examples in group:
405
+ batch = collate(examples, pad_id, device)
406
+ labels = torch.tensor([ex.target for ex in examples], dtype=torch.float32, device=device)
407
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
408
+ loss, components = loss_for_batch(encoder, head, batch, labels,
409
+ pos_weight, line_weight)
410
+ (loss / len(group)).backward()
411
+ epoch_point += components["point"]
412
+ epoch_line += components["line"]
413
+ torch.nn.utils.clip_grad_norm_(parameters, float(train_cfg["gradient_clip_norm"]))
414
+ optimizer.step(); scheduler.step()
415
+ epoch_rows = collect_rows(encoder, head, holdout, pad_id, device)
416
+ hold_metrics = metrics(epoch_rows)
417
+ row = {"arm": arm, "seed": seed, "epoch": epoch + 1,
418
+ "mean_pointwise_loss": epoch_point / max(1, len(microbatches)),
419
+ "mean_line_loss": epoch_line / max(1, len(microbatches)),
420
+ "learning_rate": float(scheduler.get_last_lr()[0]),
421
+ "holdout": hold_metrics, "elapsed_seconds": time.time() - started}
422
+ history.append(row)
423
+ epoch_dir = run_dir / f"epoch-{epoch + 1}"
424
+ epoch_dir.mkdir(parents=True, exist_ok=True)
425
+ encoder.save_pretrained(epoch_dir / "adapter", safe_serialization=True)
426
+ torch.save(head.state_dict(), epoch_dir / "line_head.pt")
427
+ torch.save({"optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(),
428
+ "epoch": epoch + 1, "seed": seed, "torch_rng": torch.get_rng_state(),
429
+ "cuda_rng": torch.cuda.get_rng_state_all(), "python_rng": random.getstate(),
430
+ "numpy_rng": np.random.get_state()}, epoch_dir / "full_state.pt")
431
+ save_jsonl(epoch_dir / "holdout_rows.jsonl", epoch_rows)
432
+ (epoch_dir / "metrics.json").write_text(json.dumps(row, indent=2) + "\n")
433
+ print(json.dumps({"event": "epoch_complete", **row}, separators=(",", ":")), flush=True)
434
+ if selected is None or hold_metrics["row_auc"] > selected["holdout"]["row_auc"]:
435
+ selected = {"epoch": epoch + 1, "path": str(epoch_dir.relative_to(ROOT)),
436
+ "holdout": hold_metrics}
437
+
438
+ result = {"arm": arm, "seed": seed, "selected": selected, "history": history,
439
+ "attention": attention, "elapsed_seconds": time.time() - started,
440
+ "optimizer_steps": total_steps}
441
+ (run_dir / "selection.json").write_text(json.dumps(result, indent=2) + "\n")
442
+ selected_rows_path = ROOT / selected["path"] / "holdout_rows.jsonl"
443
+ selected_rows = [json.loads(line) for line in selected_rows_path.read_text().splitlines()]
444
+ result["selected"]["holdout_pair_cluster_bootstrap_95_ci"] = pair_bootstrap_ci(selected_rows)
445
+ (run_dir / "selection.json").write_text(json.dumps(result, indent=2) + "\n")
446
+ del encoder, head, optimizer, scheduler
447
+ torch.cuda.empty_cache()
448
+ return result
449
+
450
+
451
+ def replace_target(example: Example, target: int) -> Example:
452
+ return Example(**{**example.__dict__, "target": int(target),
453
+ "line_targets": np.zeros_like(example.line_targets)})
454
+
455
+
456
+ def main() -> None:
457
+ parser = argparse.ArgumentParser()
458
+ parser.add_argument("--config", type=Path, default=CONFIG_PATH)
459
+ parser.add_argument("--output-dir", type=Path, default=OUT)
460
+ args = parser.parse_args()
461
+ config = json.loads(args.config.read_text())
462
+ splits = json.loads(SPLIT_PATH.read_text())
463
+ preflight = json.loads(PREFLIGHT_PATH.read_text())
464
+ baseline = json.loads(BASELINE_PATH.read_text())
465
+ if config["status"] != "frozen_before_training":
466
+ raise RuntimeError("E3 config is not frozen")
467
+ if sha(CORPUS_PATH) != config["provenance"]["corpus_sha256"]:
468
+ raise RuntimeError("corpus hash differs from frozen E3 config")
469
+ if sha(SPLIT_PATH) != config["provenance"]["frozen_pair_splits_sha256"]:
470
+ raise RuntimeError("frozen pair split hash mismatch")
471
+ if preflight["status"] != "preflight_pass_with_deterministic_holdout_quarantine":
472
+ raise RuntimeError("E3 data leakage preflight did not pass")
473
+ if baseline["status"] != "complete":
474
+ raise RuntimeError("matched classical holdout baseline is not complete")
475
+ if not torch.cuda.is_available():
476
+ raise RuntimeError("CUDA is required for E3 training")
477
+ device = torch.device("cuda")
478
+ torch.backends.cuda.matmul.allow_tf32 = True
479
+ OUT.mkdir(parents=True, exist_ok=True)
480
+ config_hash = sha(args.config)
481
+ (OUT / "launch_manifest.json").write_text(json.dumps({
482
+ "launched_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
483
+ "config_path": str(args.config.relative_to(ROOT)), "config_sha256": config_hash,
484
+ "corpus_sha256": sha(CORPUS_PATH), "frozen_pair_splits_sha256": sha(SPLIT_PATH),
485
+ "classical_holdout_auc": baseline["row_auc"], "early_stop_threshold": baseline["row_auc"] + 0.01,
486
+ "stage_go_threshold": baseline["row_auc"] + 0.02, "test_read": False
487
+ }, indent=2) + "\n")
488
+
489
+ frame = pd.read_parquet(CORPUS_PATH, columns=["sample_id", "pair_id", "target", "func_vuln",
490
+ "func_patch", "patch_lines_vuln"])
491
+ frame["pair_id"] = frame.pair_id.astype(str)
492
+ from transformers import AutoTokenizer
493
+ tokenizer = AutoTokenizer.from_pretrained(config["model"]["id"],
494
+ revision=config["model"]["revision"], use_fast=True, local_files_only=True)
495
+ if tokenizer.pad_token_id is None:
496
+ tokenizer.pad_token = tokenizer.eos_token
497
+ max_len = int(config["model"]["max_sequence_length"])
498
+ all_pairs = {
499
+ "train": build_pairs(frame, splits["train_pre_2021_pair_ids"], tokenizer, max_len),
500
+ "holdout": build_pairs(frame, splits["selection_holdout_2021_pair_ids"], tokenizer, max_len),
501
+ }
502
+ # VALID code is materialized for final inference only; no model choice or
503
+ # threshold is derived from it. Evaluation is delayed until all training ends.
504
+ valid_ids = set(map(str, json.loads(VALID_SPLIT_PATH.read_text())))
505
+ all_pairs["valid"] = build_pairs(frame, sorted(valid_ids), tokenizer, max_len)
506
+ token_coverage = audit_token_coverage(all_pairs)
507
+ (OUT / "token_coverage.json").write_text(json.dumps(token_coverage, indent=2) + "\n")
508
+ print(json.dumps({"event": "tokenization_complete", "coverage": token_coverage}, separators=(",", ":")), flush=True)
509
+
510
+ runs = []
511
+ primary = config["architecture"]
512
+ main_seeds = list(config["training"]["seeds"])
513
+ for index, seed in enumerate(main_seeds):
514
+ run = train_one(config, all_pairs["train"], all_pairs["holdout"], arm="primary",
515
+ seed=int(seed), device=device, output_dir=args.output_dir,
516
+ line_weight=float(config["objective"]["line_loss_weight"]), pair_batching=True,
517
+ shuffled_labels=False, pad_id=int(tokenizer.pad_token_id))
518
+ runs.append(run)
519
+ auc = run["selected"]["holdout"]["row_auc"]
520
+ delta = auc - float(baseline["row_auc"])
521
+ if index == 0 and delta < 0.01:
522
+ print(json.dumps({"event": "registered_early_stop", "seed": int(seed),
523
+ "holdout_auc": auc, "classical_auc": baseline["row_auc"],
524
+ "delta": delta, "threshold": 0.01}), flush=True)
525
+ break
526
+
527
+ early_stopped = len(runs) == 1 and (runs[0]["selected"]["holdout"]["row_auc"] - baseline["row_auc"] < 0.01)
528
+ if not early_stopped and len(runs) == len(main_seeds):
529
+ for arm, line_weight, pair_batching, shuffled in [
530
+ ("ablation_no_line_loss", 0.0, True, False),
531
+ ("ablation_no_pair_batching", float(config["objective"]["line_loss_weight"]), False, False),
532
+ ("control_shuffled_labels", 0.0, True, True),
533
+ ]:
534
+ runs.append(train_one(config, all_pairs["train"], all_pairs["holdout"], arm=arm,
535
+ seed=42, device=device, output_dir=args.output_dir, line_weight=line_weight,
536
+ pair_batching=pair_batching, shuffled_labels=shuffled,
537
+ pad_id=int(tokenizer.pad_token_id)))
538
+
539
+ results = {"status": "training_complete_holdout_selected",
540
+ "runs": runs, "token_coverage": token_coverage,
541
+ "classical_holdout_auc": baseline["row_auc"],
542
+ "stage_gate": {"primary_holdout_aucs": [x["selected"]["holdout"]["row_auc"] for x in runs if x["arm"] == "primary"],
543
+ "early_stop_fired": early_stopped,
544
+ "go_threshold": baseline["row_auc"] + 0.02},
545
+ "config_sha256": config_hash, "test_read": False,
546
+ "note": "VALID has not been scored by this training stage; run the separate frozen final evaluator only after all training stops."}
547
+ (OUT / "holdout_training_status.json").write_text(json.dumps(results, indent=2) + "\n")
548
+ print(json.dumps({"event": "holdout_training_finished", "status": results["status"],
549
+ "early_stop": early_stopped, "runs": len(runs)}, separators=(",", ":")), flush=True)
550
+
551
+
552
+ if __name__ == "__main__":
553
+ main()
tests/test_review23_e3.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+
4
+ from scripts.train_review23_e3 import encode_example, pool_tokens_to_lines
5
+
6
+
7
+ class _Tokenizer:
8
+ def __call__(self, code, **kwargs):
9
+ assert code == "a\nbc\n"
10
+ return {"input_ids": [10, 11, 12],
11
+ "offset_mapping": [(0, 1), (2, 3), (3, 4)]}
12
+
13
+
14
+ def test_encode_example_aligns_diff_lines_to_one_based_visible_source_lines():
15
+ ex = encode_example(_Tokenizer(), "s1", "p1", 1, "a\nbc\n", {2}, max_length=3)
16
+ assert ex.line_numbers.tolist() == [1, 2]
17
+ assert ex.token_lines.tolist() == [0, 1, 1]
18
+ assert ex.line_targets.tolist() == [0.0, 1.0]
19
+ assert ex.n_positive_visible == 1
20
+
21
+
22
+ def test_encode_example_records_positive_line_lost_to_right_truncation():
23
+ ex = encode_example(_Tokenizer(), "s1", "p1", 1, "a\nbc\n", {2}, max_length=1)
24
+ assert ex.line_numbers.tolist() == [1]
25
+ assert ex.line_targets.tolist() == [0.0]
26
+ assert ex.n_positive_original == 1
27
+ assert ex.n_positive_visible == 0
28
+
29
+
30
+ def test_pool_tokens_to_lines_ignores_padding_and_backpropagates():
31
+ hidden = torch.tensor([[[1.0, 3.0], [3.0, 5.0], [9.0, 7.0], [99.0, 99.0]]],
32
+ requires_grad=True)
33
+ token_lines = torch.tensor([[0, 0, 1, -1]])
34
+ pooled, mask = pool_tokens_to_lines(hidden, token_lines, [2])
35
+ assert torch.equal(mask, torch.tensor([[True, True]]))
36
+ assert torch.allclose(pooled, torch.tensor([[[2.0, 4.0], [9.0, 7.0]]]))
37
+ pooled.sum().backward()
38
+ assert torch.allclose(hidden.grad[0, 3], torch.zeros(2))
39
+ assert torch.allclose(hidden.grad[0, 0], torch.tensor([0.5, 0.5]))
40
+
41
+
42
+ def test_safe_example_never_gets_positive_line_targets():
43
+ ex = encode_example(_Tokenizer(), "s0", "p1", 0, "a\nbc\n", {2}, max_length=3)
44
+ assert np.all(ex.line_targets == 0)