nur-dev commited on
Commit
fe71d54
·
verified ·
1 Parent(s): 84675d4

Correct author attribution and publish independent audit source

Browse files
LICENSE.md CHANGED
@@ -4,7 +4,7 @@ The licensing below applies to this prepared release; it does not relicense unre
4
 
5
  ## Original code: MIT
6
 
7
- Copyright (c) 2026 Nurgali Kadyrbek, Madina Mansurova, Balzhan Akhmetova, Birlik Sagitzhanov and Roza Sabirova.
8
 
9
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
 
@@ -14,15 +14,15 @@ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR I
14
 
15
  ## Original models, generated data, metrics and documentation: CC BY 4.0
16
 
17
- These assets are licensed under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/legalcode). Attribute the five article authors and preserve the source notices. The synthetic probability laws are researcher-generated; the physical recordings remain attributable to their original creators.
18
 
19
  ## Third-party sensor features: CC BY 4.0
20
 
21
- Processed hydraulic and temperature-modulated sensor arrays are adaptations of the UCI datasets identified in `THIRD_PARTY_NOTICES.md`. The original creators retain attribution. No ownership of their original recordings is claimed.
22
 
23
- ## Gas-drift source restriction
24
 
25
- No raw or processed UCI 224 gas-drift records are redistributed. Reproduction code retrieves that source separately. Its legacy description limits use to research despite newer repository CC BY metadata; that notice remains applicable to any separately obtained copy. This release does not grant rights beyond those offered by the source creators.
26
 
27
  # Source attribution
28
 
@@ -31,3 +31,4 @@ No raw or processed UCI 224 gas-drift records are redistributed. Reproduction co
31
  | Condition monitoring of hydraulic systems | Nikolai Helwig, Eliseo Pignanelli, Andreas Schütze | 10.24432/C5CW21 | Four within-cycle means per physical sensor, categorical condition indices, masks and fitted models; CC BY 4.0 |
32
  | Gas sensor array temperature modulation | Javier Burgués | 10.24432/C5S302 | Four within-episode resistance means, reference-derived condition labels, day/binding masks and fitted models; CC BY 4.0 |
33
  | Gas sensor array drift | Alexander Vergara | 10.24432/C5RP6W | Aggregate evaluation metrics and source adapters only; no source records; preserve legacy research-only notice when retrieving data |
 
 
4
 
5
  ## Original code: MIT
6
 
7
+ Copyright (c) 2026 Nurgali Kadyrbek, Madina Mansurova, Nazgul Toiganbayeva, Balzhan Akhmetova, Birlik Sagitzhanov and Roza Sabirova.
8
 
9
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
10
 
 
14
 
15
  ## Original models, generated data, metrics and documentation: CC BY 4.0
16
 
17
+ These assets are licensed under the [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/legalcode). Attribute the six article authors and preserve the source notices. The synthetic probability laws are researcher-generated; the physical recordings remain attributable to their original creators.
18
 
19
  ## Third-party sensor features: CC BY 4.0
20
 
21
+ Processed hydraulic and temperature-modulated sensor arrays are adaptations of the UCI datasets identified in the [Source attribution](#source-attribution) section below. The original creators retain attribution. No ownership of their original recordings is claimed.
22
 
23
+ ## Restricted source recordings
24
 
25
+ No raw or processed UCI 224 gas-drift records are redistributed. Reproduction code retrieves that source separately. Its legacy description limits use to research despite newer repository CC BY metadata; that notice remains applicable to any separately obtained copy. This release does not grant rights beyond those offered by the source creators. The Air Quality archive likewise has a legacy research-only/no-commercial notice alongside newer CC BY metadata; its raw and processed records remain excluded, and reproduction retrieves it separately under those source terms.
26
 
27
  # Source attribution
28
 
 
31
  | Condition monitoring of hydraulic systems | Nikolai Helwig, Eliseo Pignanelli, Andreas Schütze | 10.24432/C5CW21 | Four within-cycle means per physical sensor, categorical condition indices, masks and fitted models; CC BY 4.0 |
32
  | Gas sensor array temperature modulation | Javier Burgués | 10.24432/C5S302 | Four within-episode resistance means, reference-derived condition labels, day/binding masks and fitted models; CC BY 4.0 |
33
  | Gas sensor array drift | Alexander Vergara | 10.24432/C5RP6W | Aggregate evaluation metrics and source adapters only; no source records; preserve legacy research-only notice when retrieving data |
34
+ | Air Quality | Saverio Vito | 10.24432/C59K5F | Aggregate evaluation results, protocols and reconstruction/audit code only; no raw or processed recordings or fresh fitted states; retain the legacy research-only notice alongside the newer repository CC BY metadata |
SHA256SUMS.json CHANGED
@@ -1,7 +1,7 @@
1
  {
2
  ".gitattributes": "0aad2046ff3535fdb3750ad77100b4f6aed80009c097ffc8a9e264a5d1b0c4e7",
3
  "ENVIRONMENT.json": "786e73bb84b1300d1b5062961af74aacbab2bbfe1e12675ba6ceebd12d26b0eb",
4
- "LICENSE.md": "4a8b21f5c8ee1383fdf12d8622df51066334d446513d7318ab8a31763f435813",
5
  "README.md": "6b3e9c66bdec04283c3367d84dae7622e50f377db050354694acfd193a7e3e21",
6
  "analyze.py": "3e2ee19da7cdec5b735db55a368132977d8aa6cfe4cfd8e49dbe86019a56a444",
7
  "data/controlled/manifest.json": "2b50155e7f4d198449e2499dad21ba82d51e94423a1711eca8de4a01ab9ca156",
@@ -473,8 +473,8 @@
473
  "revision_r1/sensor/objective_extension_01/temperature_n64_s20853.json": "398edf09511ff818a3bb2e77829b121e5b1af9b1646eb29507556f6d756a5cba",
474
  "revision_r1/sensor/objective_extension_01/hydraulic_n64_s20751.safetensors": "3e5a56962a870d83d2cd4037f8ec1c0aa39fe0b20111579bda7d435a98683f28",
475
  "validation_20261110/LOCK_RELOCATION.json": "8564ce91313b53a9902b19da0c6d196397d5110b682a601418e43fcdbe39ded1",
476
- "validation_20261110/README.md": "4ad51c8c0459a8f99a40bcdd25c433427051f2a3bd9acc5a7c883fe6c6e9deec",
477
- "validation_20261110/SHA256SUMS.json": "dacde5953048392ff7cb06a87e6e15c1c7f67935436eec1e1d68dfca27b87a88",
478
  "validation_20261110/calibration/analysis_spec.json": "067136bd17de8451ea925120767326930ebbc91a300fd6926d31ff5461f80221",
479
  "validation_20261110/calibration/analyze_replay.py": "19b4e7b9d1a7da4cdb1f3b3ffd561114959cb24907b4c88ac527f1d35e710598",
480
  "validation_20261110/calibration/cell_compute.json": "2a4af1c9f3ca719090fb54f6b997f62540a41a16da3d26a90e5c3901a218b611",
@@ -546,5 +546,8 @@
546
  "validation_20261110/fresh/validation_fresh_source.py": "d36088ba86bce053346f4e04d68646fbe621f6515aa7d7ca5b41f4bb611e0714",
547
  "validation_20261110/fresh/validation_fresh_study.py": "f382af13f783d06b4ca64b67081b033577524d62bdaead3965dd1a96e85c9553",
548
  "validation_20261110/portable_preflight.json": "55ea9fc3b4d870186f8909c9ea0d4211e63f9214083a3589bd71ec5f2e18abda",
549
- "validation_20261110/reproduce.py": "3efa11f23f8b26a1a7c21203d93b1b03b46bc388a69b23dfb11e468993a390a2"
 
 
 
550
  }
 
1
  {
2
  ".gitattributes": "0aad2046ff3535fdb3750ad77100b4f6aed80009c097ffc8a9e264a5d1b0c4e7",
3
  "ENVIRONMENT.json": "786e73bb84b1300d1b5062961af74aacbab2bbfe1e12675ba6ceebd12d26b0eb",
4
+ "LICENSE.md": "c61d10e351da6b418485dac97ab5a3b419260552c4c10344d1621928bbb35908",
5
  "README.md": "6b3e9c66bdec04283c3367d84dae7622e50f377db050354694acfd193a7e3e21",
6
  "analyze.py": "3e2ee19da7cdec5b735db55a368132977d8aa6cfe4cfd8e49dbe86019a56a444",
7
  "data/controlled/manifest.json": "2b50155e7f4d198449e2499dad21ba82d51e94423a1711eca8de4a01ab9ca156",
 
473
  "revision_r1/sensor/objective_extension_01/temperature_n64_s20853.json": "398edf09511ff818a3bb2e77829b121e5b1af9b1646eb29507556f6d756a5cba",
474
  "revision_r1/sensor/objective_extension_01/hydraulic_n64_s20751.safetensors": "3e5a56962a870d83d2cd4037f8ec1c0aa39fe0b20111579bda7d435a98683f28",
475
  "validation_20261110/LOCK_RELOCATION.json": "8564ce91313b53a9902b19da0c6d196397d5110b682a601418e43fcdbe39ded1",
476
+ "validation_20261110/README.md": "e5e244efab5fab77bb54601b36268820a958994d7fbfaad73e9acddcf008ba85",
477
+ "validation_20261110/SHA256SUMS.json": "b42844aa4df9d9499b122d2653466c390cc4bd4a6816a1e3ba635b03bf6a053c",
478
  "validation_20261110/calibration/analysis_spec.json": "067136bd17de8451ea925120767326930ebbc91a300fd6926d31ff5461f80221",
479
  "validation_20261110/calibration/analyze_replay.py": "19b4e7b9d1a7da4cdb1f3b3ffd561114959cb24907b4c88ac527f1d35e710598",
480
  "validation_20261110/calibration/cell_compute.json": "2a4af1c9f3ca719090fb54f6b997f62540a41a16da3d26a90e5c3901a218b611",
 
546
  "validation_20261110/fresh/validation_fresh_source.py": "d36088ba86bce053346f4e04d68646fbe621f6515aa7d7ca5b41f4bb611e0714",
547
  "validation_20261110/fresh/validation_fresh_study.py": "f382af13f783d06b4ca64b67081b033577524d62bdaead3965dd1a96e85c9553",
548
  "validation_20261110/portable_preflight.json": "55ea9fc3b4d870186f8909c9ea0d4211e63f9214083a3589bd71ec5f2e18abda",
549
+ "validation_20261110/reproduce.py": "3efa11f23f8b26a1a7c21203d93b1b03b46bc388a69b23dfb11e468993a390a2",
550
+ "validation_20261110/fresh/independent/README.md": "15186973333c6ed558128f94268df47ec785aabcb2cc10f60f037c37dc8a629a",
551
+ "validation_20261110/fresh/independent/portable_audit.py": "8d7a90fe29c3e9a7be20348ae1e563f12db59a2e3d87f5c1dba5f8c148244014",
552
+ "validation_20261110/fresh/independent/original_fresh_independent_validation.py": "169014bbae37f5e6f47ef938b6d724ee6ad17ef9fe6c3e9f3ee648c7d2817820"
553
  }
validation_20261110/README.md CHANGED
@@ -19,6 +19,13 @@ python validation_20261110/reproduce.py nested-refit --release /path/to/hf-check
19
  python validation_20261110/reproduce.py nested-replay --release /path/to/hf-checkout --prior /path/to/hf-checkout/revision_r1/sensor/run_01 --local-run /path/to/local-nested-reproduction/nested_run --work /path/to/local-nested-analysis --device cuda:0
20
  ```
21
 
22
- The earlier nested calibration uses temperatures `{1,2,4,8,16,32,64}`; fresh-study calibration uses `{0.5,1,2,4,8}`. `calibration/fitted_state.*` retains weights, covariance, normalizers, source fold indices and aggregate calibration losses. Per-record residuals, posteriors, truth and target indices are omitted. Exact per-record replay therefore uses a locally regenerated run, not this minimal public state bundle. Cost commands and specifications are under `cost/`.
 
 
 
 
 
 
 
23
 
24
  Fresh source: **Saverio Vito, UCI Air Quality**, DOI [10.24432/C59K5F](https://doi.org/10.24432/C59K5F). The official CC BY 4.0 banner coexists with legacy research-only/no-commercial terms. We apply the conservative research-only restriction and redistribute no raw or processed Air Quality records, record-level predictions or KDE training centers. This is an existing 2004–2005 archive, not data newly collected in 2026. Code and original research-artifact terms follow the checkout's `LICENSE.md`.
 
19
  python validation_20261110/reproduce.py nested-replay --release /path/to/hf-checkout --prior /path/to/hf-checkout/revision_r1/sensor/run_01 --local-run /path/to/local-nested-reproduction/nested_run --work /path/to/local-nested-analysis --device cuda:0
20
  ```
21
 
22
+ The earlier nested calibration uses temperatures `{1,2,4,8,16,32,64}`; fresh-study calibration uses `{0.5,1,2,4,8}`. `calibration/fitted_state.*` retains weights, covariance, normalizers, source fold indices and aggregate calibration losses. Per-record residuals, posteriors, truth and target indices are omitted. Exact per-record replay therefore uses a locally regenerated run, not this minimal public state bundle. Cost specifications and recorded results are under `cost/`. For a new output directory, run preparation followed by the complete verification, ranking, refitting, seven-repetition benchmark and aggregation sequence. Timings depend on hardware and host workload; original receipts remain unchanged.
23
+
24
+ ```bash
25
+ python validation_20261110/cost/validation_inference_cost.py --prepare --release /path/to/hf-checkout --output /path/to/new-cost-run --device cuda:0
26
+ python validation_20261110/cost/validation_inference_cost.py --stage all --release /path/to/hf-checkout --output /path/to/new-cost-run --device cuda:0
27
+ ```
28
+
29
+ The [independent audit source and portable command](fresh/independent/README.md) reproduce the separate no-fit statistical checks of completed fresh-study results. The historical source is preserved exactly; its adapter changes only path, lock and recorded-access checks and labels reproductions explicitly. No new confirmation is claimed.
30
 
31
  Fresh source: **Saverio Vito, UCI Air Quality**, DOI [10.24432/C59K5F](https://doi.org/10.24432/C59K5F). The official CC BY 4.0 banner coexists with legacy research-only/no-commercial terms. We apply the conservative research-only restriction and redistribute no raw or processed Air Quality records, record-level predictions or KDE training centers. This is an existing 2004–2005 archive, not data newly collected in 2026. Code and original research-artifact terms follow the checkout's `LICENSE.md`.
validation_20261110/SHA256SUMS.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "LOCK_RELOCATION.json": "8564ce91313b53a9902b19da0c6d196397d5110b682a601418e43fcdbe39ded1",
3
- "README.md": "4ad51c8c0459a8f99a40bcdd25c433427051f2a3bd9acc5a7c883fe6c6e9deec",
4
  "calibration/analysis_spec.json": "067136bd17de8451ea925120767326930ebbc91a300fd6926d31ff5461f80221",
5
  "calibration/analyze_replay.py": "19b4e7b9d1a7da4cdb1f3b3ffd561114959cb24907b4c88ac527f1d35e710598",
6
  "calibration/cell_compute.json": "2a4af1c9f3ca719090fb54f6b997f62540a41a16da3d26a90e5c3901a218b611",
@@ -72,5 +72,8 @@
72
  "fresh/validation_fresh_source.py": "d36088ba86bce053346f4e04d68646fbe621f6515aa7d7ca5b41f4bb611e0714",
73
  "fresh/validation_fresh_study.py": "f382af13f783d06b4ca64b67081b033577524d62bdaead3965dd1a96e85c9553",
74
  "portable_preflight.json": "55ea9fc3b4d870186f8909c9ea0d4211e63f9214083a3589bd71ec5f2e18abda",
75
- "reproduce.py": "3efa11f23f8b26a1a7c21203d93b1b03b46bc388a69b23dfb11e468993a390a2"
 
 
 
76
  }
 
1
  {
2
  "LOCK_RELOCATION.json": "8564ce91313b53a9902b19da0c6d196397d5110b682a601418e43fcdbe39ded1",
3
+ "README.md": "e5e244efab5fab77bb54601b36268820a958994d7fbfaad73e9acddcf008ba85",
4
  "calibration/analysis_spec.json": "067136bd17de8451ea925120767326930ebbc91a300fd6926d31ff5461f80221",
5
  "calibration/analyze_replay.py": "19b4e7b9d1a7da4cdb1f3b3ffd561114959cb24907b4c88ac527f1d35e710598",
6
  "calibration/cell_compute.json": "2a4af1c9f3ca719090fb54f6b997f62540a41a16da3d26a90e5c3901a218b611",
 
72
  "fresh/validation_fresh_source.py": "d36088ba86bce053346f4e04d68646fbe621f6515aa7d7ca5b41f4bb611e0714",
73
  "fresh/validation_fresh_study.py": "f382af13f783d06b4ca64b67081b033577524d62bdaead3965dd1a96e85c9553",
74
  "portable_preflight.json": "55ea9fc3b4d870186f8909c9ea0d4211e63f9214083a3589bd71ec5f2e18abda",
75
+ "reproduce.py": "3efa11f23f8b26a1a7c21203d93b1b03b46bc388a69b23dfb11e468993a390a2",
76
+ "fresh/independent/README.md": "15186973333c6ed558128f94268df47ec785aabcb2cc10f60f037c37dc8a629a",
77
+ "fresh/independent/portable_audit.py": "8d7a90fe29c3e9a7be20348ae1e563f12db59a2e3d87f5c1dba5f8c148244014",
78
+ "fresh/independent/original_fresh_independent_validation.py": "169014bbae37f5e6f47ef938b6d724ee6ad17ef9fe6c3e9f3ee648c7d2817820"
79
  }
validation_20261110/fresh/independent/README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Independent audit of a completed fresh-study run
2
+
3
+ `original_fresh_independent_validation.py` is the exact historical independent auditor (SHA256 `169014bbae37f5e6f47ef938b6d724ee6ad17ef9fe6c3e9f3ee648c7d2817820`). Its original workspace and pre-access guards are preserved. `portable_audit.py` replaces only that guard block during execution; its statistical calculations are unchanged.
4
+
5
+ First complete the existing `validation_20261110/reproduce.py fresh` command in a separate local work directory. It creates the relocated lock, prepared records and all model results used below. The independent audit fits no models and downloads nothing. Restricted records and per-record outputs stay local. The output directory must not exist.
6
+
7
+ ```bash
8
+ python validation_20261110/fresh/independent/portable_audit.py --protocol validation_20261110/fresh/protocol.json --lock /path/to/local-fresh-reproduction/relocated_lock.json --prepared /path/to/local-fresh-reproduction/fresh_prepared --results /path/to/local-fresh-reproduction/fresh_results --release /path/to/hf-checkout --output /path/to/local-fresh-reproduction/independent-audit --device cuda:0
9
+ ```
10
+
11
+ The adapter verifies every original locked digest at the relocated paths, the selected source checkout, the actual frozen study source, prepared-data hash and the execution receipt. It supports a completed local reproduction or the original archived run. For an original run, acquisition time is checked against the original recorded lock; it is not compared with the later audit/relocation time. A relocated run is explicitly recognized as reproduction of opened research. Neither case supplies new prospective confirmation or third-party preregistration.
12
+
13
+ The new receipt records the original auditor, adapted executed source and adapter SHA256 hashes, the selected and original lock digests, the recorded access time and the execution context. Original input files and historical receipts are never rewritten. Existing summary, contrast and weekly-output calculations are preserved.
validation_20261110/fresh/independent/original_fresh_independent_validation.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent no-fit fresh-study eligibility, weighting and decision audit."""
2
+ from pathlib import Path
3
+ import argparse,csv,datetime,hashlib,json,sys,time
4
+ import torch
5
+ from safetensors.torch import load_file
6
+
7
+
8
+ def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
9
+ def write(p,x):Path(p).write_text(json.dumps(x,indent=2,allow_nan=False)+'\n')
10
+ def readcsv(p):return list(csv.DictReader(Path(p).open()))
11
+ def csvout(p,rows):
12
+ keys=list(dict.fromkeys(k for r in rows for k in r))
13
+ with Path(p).open('w',newline='') as f:
14
+ w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(rows)
15
+
16
+
17
+ def tree(base,device):
18
+ base=Path(base);t=load_file(str(base.with_suffix('.safetensors')),device=device)
19
+ def walk(x):
20
+ if not isinstance(x,dict):return x
21
+ if 'tensor' in x:return t[x['tensor']]
22
+ if 'dict' in x:return {walk(k):walk(v) for k,v in x['dict']}
23
+ if 'list' in x:return [walk(v) for v in x['list']]
24
+ if 'tuple' in x:return tuple(walk(v) for v in x['tuple'])
25
+ if 'float' in x:return float(x['float'])
26
+ raise ValueError(x)
27
+ return walk(json.loads(base.with_suffix('.json').read_text()))
28
+
29
+
30
+ def credits(p,true,k):
31
+ threshold=p.sort(-1,descending=True).values[:,k-1];above=p>threshold[:,None]+1e-12;equal=(p-threshold[:,None]).abs()<=1e-12
32
+ target=p.gather(1,true[:,None]).squeeze(-1);tie=(k-above.sum(-1)).double()/equal.sum(-1).clamp_min(1)
33
+ return torch.where(target>threshold+1e-12,1.,torch.where((target-threshold).abs()<=1e-12,tie,0.))
34
+
35
+
36
+ def metrics(p,true):
37
+ target=p.gather(1,true[:,None]).squeeze(-1)
38
+ return dict(top1=credits(p,true,1),top3=credits(p,true,3),nll=-target.clamp_min(1e-300).log(),
39
+ brier=p.square().sum(-1)-2*target+1,confidence=p.max(-1).values)
40
+
41
+
42
+ def weekmeans(values,days,mask,anchor):
43
+ # Aggregate unique days first, then map their means to calendar weeks.
44
+ unique=days[mask].unique(sorted=True);daily=torch.stack([values[mask&(days==d)].mean() for d in unique]);week=(unique-anchor)//7
45
+ weeks=week.unique(sorted=True);return weeks,torch.stack([daily[week==w].mean() for w in weeks])
46
+
47
+
48
+ def simple(h,n,name):
49
+ count=torch.bincount(h[:,0]*4+h[:,1],minlength=16).double()
50
+ weight=torch.ones_like(count) if name=='uniform' else count+.5 if name=='source_frequency' else (count==0).double()
51
+ if not bool(weight.sum()>0):weight=torch.ones_like(weight)
52
+ return (weight/weight.sum())[None].expand(n,-1)
53
+
54
+
55
+ @torch.no_grad()
56
+ def main():
57
+ parser=argparse.ArgumentParser();parser.add_argument('--protocol',type=Path,required=True);parser.add_argument('--lock',type=Path,required=True);parser.add_argument('--prepared',type=Path,required=True);parser.add_argument('--results',type=Path,required=True);parser.add_argument('--release',type=Path,required=True);parser.add_argument('--output',type=Path,required=True);parser.add_argument('--device',default='cuda:4');parser.add_argument('--repo',type=Path,default=Path(__file__).resolve().parents[4]);a=parser.parse_args()
58
+ assert not a.output.exists();a.output.mkdir(parents=True);start=time.perf_counter();torch.cuda.set_device(a.device);torch.backends.cuda.matmul.allow_tf32=False
59
+ protocol=json.loads(a.protocol.read_text());lock=json.loads(a.lock.read_text());manifest=json.loads((a.prepared/'manifest.json').read_text());decision=json.loads((a.results/'decision.json').read_text())
60
+ assert lock['status']=='LOCKED' and lock['raw_access_authorized'] and not lock['raw_data_accessed_before_lock']
61
+ locked={str((Path(p) if Path(p).is_absolute() else a.repo/p).resolve()):h for p,h in lock['files'].items()}
62
+ assert str(a.protocol.resolve()) in locked and str((a.repo/'articles/make_1/reproduce/validation_fresh_study.py').resolve()) in locked
63
+ for p,h in locked.items():assert sha(p)==h,p
64
+ assert sha(a.prepared/'prepared.safetensors')==manifest['prepared_sha256']
65
+ execution=json.loads((a.results/'execution_start.json').read_text());assert execution['protocol_sha256']==sha(a.protocol) and execution['lock_sha256']==sha(a.lock)
66
+ access=datetime.datetime.fromisoformat(manifest['source_provenance']['access_utc']);locked_at=datetime.datetime.fromisoformat(lock['created_utc']);assert access>locked_at
67
+ p=load_file(str(a.prepared/'prepared.safetensors'),device=a.device);source=torch.where(p['source'])[0];held=torch.where(p['target'])[0];days=p['day_id'][held];anchor=days.min();true=p['h'][held,0]*4+p['h'][held,1]
68
+ held_codes=torch.tensor([x*4+y for x,y in protocol['ontology']['held_bindings']],device=a.device);assert not bool(torch.isin(p['h'][source,0]*4+p['h'][source,1],held_codes).any())
69
+ unseen=torch.isin(true,held_codes);seen=~unseen;assert torch.equal(unseen,p['unseen'][held]) and torch.equal(seen,p['seen'][held]) and not bool((p['source']&p['target']).any())
70
+ eligible_checks=dict(strict_clock=manifest['clock']['primary_clock_valid'],source_seen_at_least128=len(source)>=protocol['split']['min_source_records'],
71
+ target_unseen_at_least120=int(unseen.sum())>=protocol['split']['min_unseen_target_records'],target_unseen_at_least30days=int(days[unseen].unique().numel())>=protocol['split']['min_unseen_target_days'],
72
+ target_unseen_at_least16weeks=int(((days[unseen]-anchor)//7).unique().numel())>=protocol['split']['min_unseen_week_blocks'],target_all_at_least60days=int(days.unique().numel())>=protocol['split']['min_target_days'])
73
+ assert set(eligible_checks)==set(manifest['support_checks']) and all(bool(manifest['support_checks'][k])==v for k,v in eligible_checks.items())
74
+ sys.path.insert(0,str(a.release.resolve()));from unionmind.continuous_decision.factor_study import predict
75
+ prefixes=json.loads((a.results/'prefixes.json').read_text());allprefix=True;orders={};vectors={};summary=[];week_rows=[];normalization_error=0.;posterior_error=0.;metric_error=0.;temp_error=0.;source_oof_simple_error=0.;additive_pairs=[];cellcount=0
76
+ strata={'all':torch.ones_like(unseen),'unseen':unseen,'seen':seen}
77
+ for seed in protocol['seeds']:
78
+ gen=torch.Generator(device=a.device).manual_seed(seed);orders[seed]=source[torch.randperm(len(source),generator=gen,device=a.device)]
79
+ for n in protocol['budgets']:
80
+ for name in protocol['models']:
81
+ byseed=[]
82
+ for seed in protocol['seeds']:
83
+ artifact=tree(a.results/'models'/f'n{n}_s{seed}'/name,a.device);cellcount+=1;ids=artifact['saved']['fit_ids'];assert torch.equal(ids,orders[seed][:n]);assert torch.equal(held,artifact['held_rows']) and torch.equal(true,artifact['truth'])
84
+ counts=[torch.bincount(p['h'][ids,f],minlength=4) for f in range(2)];supported=all(bool((c>0).all()) for c in counts)
85
+ prefix=next(x for x in prefixes if x['seed']==seed and x['labels']==n);assert prefix['all_levels_supported']==supported
86
+ if n==64:allprefix &= supported
87
+ day=p['day_id'][ids];fold=torch.tensor([int(hashlib.sha256(('fresh_outer_day:'+str(int(d))).encode()).hexdigest(),16)%4 for d in day],device=a.device);assert prefix['outer_fold']==fold.tolist()
88
+ for rec in artifact['saved']['outer_folds']:
89
+ f=rec['fold'];it=ids[fold!=f];iv=ids[fold==f];assert torch.equal(it,rec['training_ids']) and torch.equal(iv,rec['validation_ids']) and not bool(torch.isin(p['day_id'][it],p['day_id'][iv]).any())
90
+ if 'fitted_mean' in rec:
91
+ normalization_error=max(normalization_error,float((p['x'][it].mean(0)-rec['fitted_mean']).abs().max()),float((p['x'][it].std(0).clamp_min(1e-6)-rec['fitted_scale']).abs().max()))
92
+ if 'simple' in artifact['saved']:
93
+ native=simple(p['h'][ids],len(held),name);oof=torch.empty((n,16),device=a.device,dtype=torch.float64)
94
+ for f in range(4):oof[fold==f]=simple(p['h'][ids[fold!=f]],int((fold==f).sum()),name)
95
+ source_oof_simple_error=max(source_oof_simple_error,float((oof-artifact['outer_oof']).abs().max()))
96
+ else:
97
+ final=artifact['saved']['final'];normalization_error=max(normalization_error,float((p['x'][ids].mean(0)-final['mean']).abs().max()),float((p['x'][ids].std(0).clamp_min(1e-6)-final['scale']).abs().max()))
98
+ native=predict(final['model'],(p['x'][held]-final['mean'])/final['scale'],range(20))
99
+ posterior_error=max(posterior_error,float((native-artifact['prob']).abs().max()));assert native.shape==(len(held),16) and bool(torch.isfinite(native).all()) and float((native.sum(-1)-1).abs().max())<1e-10
100
+ loss=torch.stack([-((artifact['outer_oof'].clamp_min(1e-300).log()/t).log_softmax(-1)).gather(1,artifact['source_truth'][:,None]).mean() for t in [.5,1.,2.,4.,8.]])
101
+ temperature=[.5,1.,2.,4.,8.][int(loss.argmin())];assert temperature==artifact['saved']['temperature'];temp_error=max(temp_error,float((loss-artifact['temperature_losses']).abs().max()))
102
+ calibrated=(native.clamp_min(1e-300).log()/temperature).softmax(-1);posterior_error=max(posterior_error,float((calibrated-artifact['calibrated_prob']).abs().max()))
103
+ vm=metrics(native,true);cm=metrics(calibrated,true)
104
+ for k,v in vm.items():metric_error=max(metric_error,float((v-artifact['metrics'][k]).abs().max()))
105
+ for k,v in cm.items():metric_error=max(metric_error,float((v-artifact['calibrated_metrics'][k]).abs().max()))
106
+ byseed.append((vm,cm))
107
+ for stratum,mask in strata.items():
108
+ row=dict(labels=n,model=name,stratum=stratum,unique_records=int(mask.sum()),unique_days=int(days[mask].unique().numel()))
109
+ for metric in ['top1','top3','nll','brier','confidence']:
110
+ v=torch.stack([m[0][metric] for m in byseed]).mean(0);weeks,blocks=weekmeans(v,days,mask,anchor);row[metric]=float(blocks.mean());vectors[n,name,stratum,metric]=(weeks,blocks)
111
+ if metric in ['nll','brier','confidence']:
112
+ v=torch.stack([m[1][metric] for m in byseed]).mean(0);_,b=weekmeans(v,days,mask,anchor);row['calibrated_'+metric]=float(b.mean())
113
+ if metric=='top3':
114
+ for w,b in zip(weeks,blocks):week_rows.append(dict(labels=n,model=name,stratum=stratum,week=int(w),top3=float(b)))
115
+ row['week_blocks']=len(weeks);summary.append(row)
116
+ # Analytic additive full/diagonal models must share the exact fitted mean.
117
+ for n in protocol['budgets']:
118
+ for seed in protocol['seeds']:
119
+ full=tree(a.results/'models'/f'n{n}_s{seed}'/'additive_full',a.device);diag=tree(a.results/'models'/f'n{n}_s{seed}'/'additive_diag',a.device)
120
+ for key in ['mean','scale','fit_ids']:
121
+ av=full['saved']['final'][key] if key!='fit_ids' else full['saved'][key];bv=diag['saved']['final'][key] if key!='fit_ids' else diag['saved'][key];assert torch.equal(av,bv)
122
+ fm=full['saved']['final']['model']['mean'];dm=diag['saved']['final']['model']['mean'];assert torch.equal(fm,dm)
123
+ additive_pairs.append(dict(labels=n,seed=seed,fitted_mean_max_error=float((fm-dm).abs().max()),normalization_and_ids_equal=True))
124
+ original_summary=readcsv(a.results/'summary.csv');aggregation_error=0.
125
+ for row in summary:
126
+ old=next(x for x in original_summary if all(x[k]==str(row[k]) for k in ['labels','model','stratum']))
127
+ for k in ['top1','top3','nll','brier','confidence','calibrated_nll','calibrated_brier','calibrated_confidence']:aggregation_error=max(aggregation_error,abs(float(old[k])-row[k]))
128
+ gen=torch.Generator(device=a.device).manual_seed(protocol['bootstrap_seed']);contrasts=[];interval_error=0.;old_contrasts=readcsv(a.results/'contrasts.csv')
129
+ for n in protocol['budgets']:
130
+ for stratum in ['all','unseen']:
131
+ cw,cv=vectors[n,protocol['candidate'],stratum,'top3']
132
+ for control in protocol['models']:
133
+ if control==protocol['candidate']:continue
134
+ ow,ov=vectors[n,control,stratum,'top3'];assert torch.equal(cw,ow);delta=cv-ov
135
+ index=torch.randint(len(delta),(protocol['bootstrap_draws'],len(delta)),generator=gen,device=a.device);draws=delta[index].mean(1)
136
+ primary=n==protocol['primary_budget'] and control in protocol['primary_controls'];tail=.05/(2*4) if primary else .025
137
+ ci=torch.quantile(draws,draws.new_tensor([tail,1-tail]));row=dict(labels=n,stratum=stratum,control=control,difference=float(delta.mean()),lower=float(ci[0]),upper=float(ci[1]),primary=primary,week_blocks=len(delta));contrasts.append(row)
138
+ old=next(x for x in old_contrasts if x['labels']==str(n) and x['stratum']==stratum and x['control']==control)
139
+ for k in ['difference','lower','upper']:interval_error=max(interval_error,abs(float(old[k])-row[k]))
140
+ primary=[r for r in contrasts if r['primary']];eligible=all(eligible_checks.values()) and allprefix
141
+ superiority=all(r['difference']>=.03 and r['lower']>0 for r in primary if r['stratum']=='unseen');noninferiority=all(r['lower']>-.03 for r in primary if r['stratum']=='all')
142
+ point=all(r['difference']>=0 for r in contrasts if r['labels']==64 and r['stratum']=='unseen');promoted=eligible and len(primary)==4 and superiority and noninferiority and point
143
+ assert decision['source_eligible']==eligible and decision['all_primary_source_levels_supported']==allprefix and decision['point_dominance_all_unseen_controls']==point
144
+ assert decision['status']==('confirmation_pass' if promoted else 'confirmation_not_passed') and not decision['calibration_claim_promoted'] and not decision['computation_superiority_claim_promoted']
145
+ assert posterior_error<1e-10 and metric_error<1e-8 and temp_error<1e-10 and normalization_error<1e-10 and source_oof_simple_error==0 and aggregation_error<1e-10 and interval_error<1e-10,(posterior_error,metric_error,temp_error,normalization_error,aggregation_error,interval_error)
146
+ csvout(a.output/'summary.csv',summary);csvout(a.output/'weekly_top3.csv',week_rows);csvout(a.output/'contrasts.csv',contrasts)
147
+ report=dict(status='passed',refitted_models=0,model_cells=cellcount,locked_files_unchanged=True,access_after_lock=True,prepared_digest_matches=True,
148
+ eligibility_checks=eligible_checks,all64prefix_factor_levels_present=allprefix,primary_eligible=eligible,primary_superiority_gate=superiority,primary_noninferiority_gate=noninferiority,all_control_point_gate=point,
149
+ primary_decision=('confirmation_pass' if promoted else 'confirmation_not_passed'),primary_contrasts=primary,
150
+ errors=dict(posterior=posterior_error,metric=metric_error,normalization=normalization_error,source_temperature_loss=temp_error,simple_oof=source_oof_simple_error,equal_day_week_aggregation=aggregation_error,bootstrap_interval=interval_error),
151
+ additive_full_diag_pairs=additive_pairs,
152
+ inferential_units=dict(new_physical_platforms=1,unseen_unique_records=int(unseen.sum()),unseen_unique_days=int(days[unseen].unique().numel()),unseen_nonempty_week_blocks=int(((days[unseen]-anchor)//7).unique().numel()),source_fits_per_cell=3,source_fits_averaged_before_bootstrap=True,source_fits_are_not_extra_independent_observations=True),
153
+ interpretation='Only64label native scores govern confirmation.128label,calibrated,betterseed orsubset outcomes cannot replace a failed gate. Weekly intervals condition on one platform and the fitted source prefixes; selective pooled seed predictions do not constitute independent episode observations. Native NLL is floored at1e-300, with floor frequency separately reported.',seconds=time.perf_counter()-start,device=a.device)
154
+ write(a.output/'receipt.json',report);print(json.dumps(report,indent=2))
155
+
156
+
157
+ if __name__=='__main__':main()
validation_20261110/fresh/independent/portable_audit.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """No-fit audit adapter; only historical lock/path/access guards are relocated."""
2
+ from collections import Counter
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ import hashlib
6
+ import json
7
+ import sys
8
+
9
+ HERE = Path(__file__).resolve().parent
10
+ ORIGINAL = HERE / "original_fresh_independent_validation.py"
11
+ ORIGINAL_SHA = "169014bbae37f5e6f47ef938b6d724ee6ad17ef9fe6c3e9f3ee648c7d2817820"
12
+ LOCK_SHA = "0c89831fe35f29a66d5c36b570954ed855069fb270e2e0864fc03238835415d7"
13
+ CONTEXT = {}
14
+
15
+
16
+ def sha(path):
17
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
18
+
19
+
20
+ def require(condition, message):
21
+ if not condition:
22
+ raise ValueError(message)
23
+
24
+
25
+ def validate_context(a, lock, manifest):
26
+ original_path = HERE.parent / "original_lock.json"
27
+ require(sha(original_path) == LOCK_SHA, "Original lock digest differs")
28
+ original = json.loads(original_path.read_text())
29
+ require(lock.get("status") == "LOCKED" and lock.get("raw_access_authorized") is True,
30
+ "A valid acquisition-authorized recorded lock is required")
31
+ relocated = lock.get("reproducibility_relocation") is True
32
+ current_sha = sha(a.lock)
33
+ if relocated:
34
+ require(lock.get("raw_data_accessed_before_lock") is True,
35
+ "Relocation must acknowledge already opened research")
36
+ require(lock.get("original_lock_sha256") == LOCK_SHA and
37
+ lock.get("original_created_utc") == original["created_utc"] and
38
+ lock.get("original_raw_data_accessed_before_lock") is False,
39
+ "Relocation does not preserve original lock history")
40
+ else:
41
+ require(current_sha == LOCK_SHA and lock.get("raw_data_accessed_before_lock") is False,
42
+ "Only the exact original lock or an explicit relocation is supported")
43
+ require(Counter(lock["files"].values()) == Counter(original["files"].values()),
44
+ "Relocation must preserve every original locked-file digest")
45
+ locked = {str(Path(p).resolve()): h for p, h in lock["files"].items()}
46
+ require(all(Path(p).is_absolute() for p in lock["files"]), "Lock paths must be absolute")
47
+ require(locked.get(str(a.protocol.resolve())) == sha(a.protocol), "Protocol absent from lock")
48
+ studies = [h for p, h in original["files"].items() if Path(p).name == "validation_fresh_study.py"]
49
+ require(len(studies) == 1 and any(Path(p).name == "validation_fresh_study.py" and h == studies[0]
50
+ for p, h in locked.items()), "Actual frozen study source absent from lock")
51
+ for p, h in locked.items():
52
+ require(Path(p).is_file() and sha(p) == h, "Locked input differs: " + p)
53
+ for p, h in original["files"].items():
54
+ marker = "/release/huggingface-revised/"
55
+ if marker in p:
56
+ mapped = str((a.release / p.split(marker, 1)[1]).resolve())
57
+ require(locked.get(mapped) == h, "Selected checkout is not the locked checkout: " + mapped)
58
+ require(sha(a.prepared / "prepared.safetensors") == manifest["prepared_sha256"],
59
+ "Prepared-data digest differs")
60
+ execution = json.loads((a.results / "execution_start.json").read_text())
61
+ require(execution["protocol_sha256"] == sha(a.protocol), "Recorded protocol differs")
62
+ access = datetime.fromisoformat(manifest["source_provenance"]["access_utc"])
63
+ if execution["lock_sha256"] == LOCK_SHA:
64
+ mode = "audit_of_original_recorded_run"
65
+ access_lock_time = original["created_utc"]
66
+ else:
67
+ require(relocated and execution["lock_sha256"] == current_sha,
68
+ "Recorded execution cites neither original nor selected relocation lock")
69
+ mode = "audit_of_local_reproduction_run"
70
+ access_lock_time = lock["created_utc"]
71
+ require(access > datetime.fromisoformat(access_lock_time), "Recorded access predates its execution lock")
72
+ CONTEXT.update(mode=mode, new_confirmation=False, new_preregistration=False,
73
+ original_lock_sha256=LOCK_SHA, selected_lock_sha256=current_sha,
74
+ selected_lock_is_relocation=relocated,
75
+ original_created_utc=original["created_utc"],
76
+ recorded_access_utc=manifest["source_provenance"]["access_utc"],
77
+ recorded_execution_lock_sha256=execution["lock_sha256"],
78
+ access_after_lock_scope="Recorded acquisition versus its recorded execution lock; not versus audit time",
79
+ prepared=str(a.prepared.resolve()), results=str(a.results.resolve()),
80
+ release=str(a.release.resolve()), output=str(a.output.resolve()),
81
+ statistical_calculations_changed=False, refits=0, downloads=0)
82
+
83
+
84
+ OLD = ''' assert lock['status']=='LOCKED' and lock['raw_access_authorized'] and not lock['raw_data_accessed_before_lock']
85
+ locked={str((Path(p) if Path(p).is_absolute() else a.repo/p).resolve()):h for p,h in lock['files'].items()}
86
+ assert str(a.protocol.resolve()) in locked and str((a.repo/'articles/make_1/reproduce/validation_fresh_study.py').resolve()) in locked
87
+ for p,h in locked.items():assert sha(p)==h,p
88
+ assert sha(a.prepared/'prepared.safetensors')==manifest['prepared_sha256']
89
+ execution=json.loads((a.results/'execution_start.json').read_text());assert execution['protocol_sha256']==sha(a.protocol) and execution['lock_sha256']==sha(a.lock)
90
+ access=datetime.datetime.fromisoformat(manifest['source_provenance']['access_utc']);locked_at=datetime.datetime.fromisoformat(lock['created_utc']);assert access>locked_at
91
+ '''
92
+ NEW = " _validate_context(a, lock, manifest)\n"
93
+
94
+
95
+ def main():
96
+ require(sha(ORIGINAL) == ORIGINAL_SHA, "Original auditor source changed")
97
+ source = ORIGINAL.read_text()
98
+ require(source.count(OLD) == 1, "Exact historical guard block is not unique")
99
+ adapted = source.replace(OLD, NEW, 1)
100
+ adapted_sha = hashlib.sha256(adapted.encode()).hexdigest()
101
+ namespace = {"__name__": "__main__", "__file__": str(ORIGINAL), "_validate_context": validate_context}
102
+ exec(compile(adapted, str(ORIGINAL), "exec"), namespace)
103
+ # Original calculations and CSVs are untouched. Add provenance to its new receipt.
104
+ receipt_path = Path(CONTEXT["output"]) / "receipt.json"
105
+ receipt = json.loads(receipt_path.read_text())
106
+ receipt["portable_audit_context"] = dict(CONTEXT, original_audit_source_sha256=ORIGINAL_SHA,
107
+ adapted_executed_source_sha256=adapted_sha, adapter_sha256=sha(__file__),
108
+ changed_source_scope="Only the historical lock/path/access guard block; all statistical code is byte-preserved")
109
+ receipt_path.write_text(json.dumps(receipt, indent=2, allow_nan=False) + "\n")
110
+ print(json.dumps({"portable_audit_context": receipt["portable_audit_context"]}, indent=2))
111
+
112
+
113
+ if __name__ == "__main__":
114
+ main()