Giuliocc commited on
Commit
49d71ee
·
verified ·
1 Parent(s): c9f07d8

Publish the retrospective Census HTOPS transfer benchmark

Browse files
README.md CHANGED
@@ -14,6 +14,10 @@ configs:
14
  data_files:
15
  - split: test
16
  path: tables/benchmark.parquet
 
 
 
 
17
  ---
18
  # Wind Tunnel response data
19
 
@@ -31,3 +35,9 @@ The public challenge includes 132 unsuppressed item-cell rows. On those rows, de
31
  Source and license details are in source.json. The reproduction package contains the pinned protocol and source transformations. See [benchmark and submission contract](BENCHMARK.md) to score a new model on the same public cells.
32
 
33
  [Official CES source](https://doi.org/10.7910/DVN/X11EP6)
 
 
 
 
 
 
 
14
  data_files:
15
  - split: test
16
  path: tables/benchmark.parquet
17
+ - config_name: htops_transfer
18
+ data_files:
19
+ - split: benchmark
20
+ path: external/htops-transfer-v1/aggregates.csv
21
  ---
22
  # Wind Tunnel response data
23
 
 
35
  Source and license details are in source.json. The reproduction package contains the pinned protocol and source transformations. See [benchmark and submission contract](BENCHMARK.md) to score a new model on the same public cells.
36
 
37
  [Official CES source](https://doi.org/10.7910/DVN/X11EP6)
38
+
39
+ ## External Census HTOPS transfer benchmark
40
+
41
+ The `htops_transfer` configuration contains 12 released answer-category aggregates for four questions in three families, from 7,485 positive-weight Census June 2025 survey records. The frozen CES encoder scored slightly worse than uniform on both mean total variation and expected half multiclass Brier loss. This retrospective, unconditioned transfer comparison leaves the promotion gate closed.
42
+
43
+ [Methods and reproduction](external/htops-transfer-v1/README.md) · [Aggregate evaluation](external/htops-transfer-v1/evaluation.json) · [Frozen predictions](external/htops-transfer-v1/predictions.json) · [Protocol](external/htops-transfer-v1/protocol.json)
external/htops-transfer-v1/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # External HTOPS transfer check
2
+
3
+ The frozen CES 2024 response encoder performed essentially like uniform guessing on four new questions from the U.S. Census Bureau's June 2025 Household Trends and Outlook Pulse Survey. All four items in three families passed the aggregate reporting floor. Mean total variation was 42.0627% for the full adapter and 42.0623% for uniform. The adapter also scored slightly worse than uniform on expected half multiclass Brier loss. The question wording did not improve the average score over the label-only version. [Aggregate evaluation](evaluation.json)
4
+
5
+ | Comparison | Equal-family TV | Expected half Brier | Cross-entropy |
6
+ | --- | ---: | ---: | ---: |
7
+ | Frozen adapter with full instrument | 0.420627 | 0.327794 | 1.133845 |
8
+ | Uniform | 0.420623 | 0.327778 | 1.133732 |
9
+ | Frozen adapter with answer labels only | 0.420601 | 0.327771 | 1.133698 |
10
+
11
+ | Question | Family | Answered / positive-weight rows | Full adapter TV | Uniform TV |
12
+ | --- | --- | ---: | ---: | ---: |
13
+ | AI opt-out | AI behavior | 7,451 / 7,485 | 0.225008 | 0.225086 |
14
+ | Transportation sufficiency | Transport access | 7,453 / 7,485 | 0.647253 | 0.647148 |
15
+ | Foregone basic expenses to pay an energy bill | Household energy hardship | 7,469 / 7,485 | 0.375209 | 0.375245 |
16
+ | Home kept at an unsafe or unhealthy temperature | Household energy hardship | 7,465 / 7,485 | 0.404029 | 0.404027 |
17
+
18
+ The selected closed-choice questions were fielded June 16–25, 2025 and were marked all-respondent in the public-use dictionary. Person-weighted shares use `PWEIGHT` over substantive answers with positive weight. Blank and special nonresponses are excluded. The offered “Not sure” for AI opt-out is substantive. Household conditions are reports by weighted adult respondents. The unit of analysis is the respondent. Each offered category must have at least 10 substantive answers to release an item's aggregate. [Census public-use archive](https://www2.census.gov/programs-surveys/demo/datasets/hhp/2025/topical/HTOPS_HPS_2506_CSV.zip) · [Exact questionnaire](https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/HTOPS_2506_Questionnaire_ENGLISH.pdf) · [June user notes](https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf)
19
+
20
+ ## Model and scope
21
+
22
+ The published MiniLM adapter and its base model are frozen. The test uses a predeclared HTOPS source prefix, the exact question wording and the ordered answer labels. The label-only comparator removes the question wording while retaining the same model, source prefix and answer options. The original CES prompt described 2024 pre-election citizen adults. Applying the weights to HTOPS is a transfer test outside that original setting. [Published adapter](https://huggingface.co/Giuliocc/windtunnel-response-encoder/tree/29973d528b804d3c6564243b96410325f9d62b0b)
23
+
24
+ The demographic fields in the public-use dictionary describe baseline-roster Person 1. The reviewed materials do not establish that Person 1 supplied the topical response. The test therefore averages predictions over the 12 named CES cells with equal weight. This is a fixed arbitrary reference mixture. It uses no HTOPS demographic inputs or inferred HTOPS demographic weights. Subgroup findings are withheld. The report averages items within their declared family and then gives the three families equal weight. Ordinal loss covers the one ordered transport item. The release is a set of point comparisons. It does not use the available replicate weights to estimate sampling uncertainty.
25
+
26
+ The Census cohort and target instruments were outside the published adapter's training and development inputs. The two energy questions count as one family. The test uses already-public outcomes, a single Census cohort, and three expert-classified families. It leaves the ten-family promotion gate closed and supplies no prospective forecast, causal effect, or commercial-pilot validation.
27
+
28
+ ## Reproduce the two-stage evaluation
29
+
30
+ The [protocol](protocol.json) pins data, questionnaire, user notes, dictionary, original adapter and base hashes. The protocol and evaluator were committed before prediction. [Frozen predictions](predictions.json) were separately committed before the evaluator read the four outcome columns. The timestamps document local execution order on an already-published public dataset.
31
+
32
+ Use Python 3.11 or later with the locked research and encoder dependencies. Save the three source files listed in the protocol and obtain the exact adapter and base files named there. Run from the downloaded `reproduction` directory after installing `requirements-encoder-lock.txt`. The archive stays local.
33
+
34
+ ```sh
35
+ export PYTHONPATH=src
36
+ python scripts/htops_transfer.py \
37
+ --archive /path/to/HTOPS_HPS_2506_CSV.zip \
38
+ --questionnaire /path/to/HTOPS_2506_Questionnaire_ENGLISH.pdf \
39
+ --user-notes /path/to/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf \
40
+ --output /tmp/htops-predictions.json freeze \
41
+ --base-dir /path/to/pinned-minilm \
42
+ --adapter /path/to/adapter.safetensors
43
+
44
+ python scripts/htops_transfer.py \
45
+ --archive /path/to/HTOPS_HPS_2506_CSV.zip \
46
+ --questionnaire /path/to/HTOPS_2506_Questionnaire_ENGLISH.pdf \
47
+ --user-notes /path/to/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf \
48
+ --output /tmp/htops-evaluation.json score \
49
+ --predictions ../predictions.json \
50
+ --predictions-sha256 70d9e412444a4a017345a6bc53c0567f0bc665d70d78648891d972e580648d93
51
+ ```
52
+
53
+ Regenerated predictions have a fresh freeze timestamp. The score command above tests the published frozen file and aborts before reading responses if the prediction digest, protocol, instruments, runner or model do not match. Only aggregate results and provenance are stored in the evidence directory. No training or paid provider calls were used.
external/htops-transfer-v1/aggregates.csv ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ question_id,questionnaire_id,family,instrument_sha256,question_text,option_id,option_label,positive_weight_answered,positive_weight_unanswered,observed_pweight_share,adapter_share,uniform_share,label_only_adapter_share
2
+ AI3,AI3,ai_opt_out,021efb8470916d366e8d31f64551b171cefbf932e258d984d5fc819a95e545e6,"In the last 2 months, have you actively opted out of using an AI system? (e.g., disabling facial recognition, turning off a virtual assistant, stopping use of an AI-driven app)",1,Yes,7451,34,0.2407323356091079,0.33331234008073807,0.3333333333333333,0.33353476226329803
3
+ AI3,AI3,ai_opt_out,021efb8470916d366e8d31f64551b171cefbf932e258d984d5fc819a95e545e6,"In the last 2 months, have you actively opted out of using an AI system? (e.g., disabling facial recognition, turning off a virtual assistant, stopping use of an AI-driven app)",2,No,7451,34,0.5584192525110119,0.3334113260110219,0.3333333333333333,0.33342864364385605
4
+ AI3,AI3,ai_opt_out,021efb8470916d366e8d31f64551b171cefbf932e258d984d5fc819a95e545e6,"In the last 2 months, have you actively opted out of using an AI system? (e.g., disabling facial recognition, turning off a virtual assistant, stopping use of an AI-driven app)",3,Not sure,7451,34,0.20084841187988017,0.33327634632587433,0.3333333333333333,0.3330365891257922
5
+ ACCESS_TRANSP,TRANS2,transport_access,0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9,Which one of the following statements best describes your access to transportation in the last 4 weeks:,1,Enough transportation to meet your needs,7453,32,0.8471481010945514,0.19989511370658875,0.2,0.20000363513827324
6
+ ACCESS_TRANSP,TRANS2,transport_access,0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9,Which one of the following statements best describes your access to transportation in the last 4 weeks:,2,"Enough transportation, but not always the kinds you want to use",7453,32,0.09089265202373137,0.19993682205677032,0.2,0.19998866940538088
7
+ ACCESS_TRANSP,TRANS2,transport_access,0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9,Which one of the following statements best describes your access to transportation in the last 4 weeks:,3,Sometimes not enough transportation to meet your needs,7453,32,0.029754360532852294,0.2001804548005263,0.2,0.20019841318329176
8
+ ACCESS_TRANSP,TRANS2,transport_access,0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9,Which one of the following statements best describes your access to transportation in the last 4 weeks:,4,Often not enough transportation to meet your needs,7453,32,0.0185528897553797,0.20015119264523187,0.2,0.20002333323160806
9
+ ACCESS_TRANSP,TRANS2,transport_access,0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9,Which one of the following statements best describes your access to transportation in the last 4 weeks:,5,Always not enough transportation to meet your needs,7453,32,0.013651996593485167,0.19983642175793648,0.2,0.19978594904144606
10
+ HSE14,HSE14,household_energy_hardship,5a855cfd8dabeaa00f5c90fd2fb7664fe811bf2b5aed17e7708af59100ed114f,"In the last 2 months, did your household reduce or forego expenses for basic household necessities, such as medicine or food, in order to pay an energy bill?",1,Yes,7469,16,0.12475535538284471,0.49996401369571686,0.5,0.5000329613685608
11
+ HSE14,HSE14,household_energy_hardship,5a855cfd8dabeaa00f5c90fd2fb7664fe811bf2b5aed17e7708af59100ed114f,"In the last 2 months, did your household reduce or forego expenses for basic household necessities, such as medicine or food, in order to pay an energy bill?",2,No,7469,16,0.8752446446171553,0.5000359962383906,0.5,0.4999670535326004
12
+ HSE15,HSE15,household_energy_hardship,08158766cc36144d94cfba8333e0c7449ecebdfca2afba45e5d1b2f570fa9d7f,"In the last 2 months, did your household keep your home at a temperature that you felt was unsafe or unhealthy?",1,Yes,7465,20,0.09597295374048007,0.5000021333495775,0.5,0.5000329613685608
13
+ HSE15,HSE15,household_energy_hardship,08158766cc36144d94cfba8333e0c7449ecebdfca2afba45e5d1b2f570fa9d7f,"In the last 2 months, did your household keep your home at a temperature that you felt was unsafe or unhealthy?",2,No,7465,20,0.9040270462595199,0.4999978666504224,0.5,0.4999670535326004
external/htops-transfer-v1/evaluation.json ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "windtunnel-htops-transfer-evaluation-v1",
3
+ "benchmark_id": "ces24-to-htops-2506-external-transfer-v1",
4
+ "track": "retrospective_out_of_source",
5
+ "protocol_sha256": "c924081fed15725d1765b3c3a7547557980b63142ddc681ab7a88d4a3c4adf38",
6
+ "predictions_sha256": "70d9e412444a4a017345a6bc53c0567f0bc665d70d78648891d972e580648d93",
7
+ "predictions_frozen_at_utc": "2026-11-28T02:56:11.047413+00:00",
8
+ "scored_at_utc": "2026-11-28T02:56:36.506141+00:00",
9
+ "source": {
10
+ "id": "census-htops-hps-2506",
11
+ "publisher": "United States Census Bureau",
12
+ "field_dates": [
13
+ "2025-06-16",
14
+ "2025-06-25"
15
+ ],
16
+ "rights": "Published U.S. Census Bureau public-use statistical data and federal questionnaire. Release only aggregates, exact instrument excerpts and provenance.",
17
+ "universe": "U.S. adult survey respondents in the June 2025 HTOPS topical public-use release, using each selected question's documented all-respondent routing",
18
+ "estimand": "Person-weighted distribution among recorded substantive answers for each item, retaining offered uncertainty",
19
+ "weight": "PWEIGHT",
20
+ "missing_codes": [
21
+ "",
22
+ "-88",
23
+ "-99"
24
+ ],
25
+ "puf_rows": 7485,
26
+ "puf_member": "HTOPS_HPS_2506_PUF.csv",
27
+ "dictionary_member": "HTOPS_HPS_2506_DATA_DICTIONARY_PUF_CSV.xlsx",
28
+ "dictionary_sha256": "0b1cc357d0c0c83438ae029bd132bd473a50fa689b6c925196b96691d5582c87",
29
+ "archive": {
30
+ "url": "https://www2.census.gov/programs-surveys/demo/datasets/hhp/2025/topical/HTOPS_HPS_2506_CSV.zip",
31
+ "sha256": "8d14cf52f5c3bc4fab5e74e3136cb753ab1195a06314725f00761035158172d4"
32
+ },
33
+ "questionnaire": {
34
+ "url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/HTOPS_2506_Questionnaire_ENGLISH.pdf",
35
+ "sha256": "eabf314ba7d3f943e77658fbd787cecb5f90054c42deee3f25eb66d5764a0ad8"
36
+ },
37
+ "user_notes": {
38
+ "url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf",
39
+ "sha256": "d85eca398268a94d4603c0f7fe62e4249e50babb9b0ce938c0c5d7ea9d143de1"
40
+ },
41
+ "respondent_demographics": "Withheld. TAGE1 and REDUC1 describe baseline-roster Person 1. The reviewed documents do not establish that Person 1 answered these questions. No HTOPS demographic input or subgroup estimates."
42
+ },
43
+ "model": {
44
+ "repository": "Giuliocc/windtunnel-response-encoder",
45
+ "revision": "29973d528b804d3c6564243b96410325f9d62b0b",
46
+ "adapter_sha256": "6b26a64bc2d3c19cd051efaf4fda42ff332dd4e5a74d6a10637acb770240cd9c",
47
+ "base_config_sha256": "571b74b43adead7e559e53ab216b56d8ec7bdf45cd24f1e7be387e9488eba4ed",
48
+ "encoder_runner_sha256": "2052ababa9708b71ee35a74583a6384bb6caab52fd0efdb4ea1445719de0c553",
49
+ "source_helpers_sha256": "08f04b88bc5f994b8a49f3d672f0ab5dec99220d1bb325979a7b335888c48e76",
50
+ "scorer_sha256": "f103271a0c7fd79f5cdc79b11f424c2d90e5438430fb9bd2daa7e988d31e9918",
51
+ "original_prompt_prefix": "2024 CES pre-election survey, US citizen adults, English. ",
52
+ "external_prompt_prefix": "June 2025 U.S. Census Household Trends and Outlook Pulse Survey, U.S. adult respondents, English. ",
53
+ "population_standardization": "Arithmetic mean over the 12 named CES age-by-education cells, a fixed arbitrary reference mixture. These are not HTOPS demographic weights. This unconditioned estimate uses neither the model's unknown-cell embedding nor any HTOPS response or demographic values."
54
+ },
55
+ "population_conditioning": "withheld",
56
+ "puf_rows": 7485,
57
+ "positive_person_weight_rows": 7485,
58
+ "coverage": {
59
+ "items_registered": 4,
60
+ "items_scored": 4,
61
+ "families_registered": 3,
62
+ "families_scored": 3
63
+ },
64
+ "promotion": {
65
+ "minimum_independent_test_families": 10,
66
+ "status": "withheld",
67
+ "reason": "One retrospective external cohort and three held-out expert-classified families. This test does not qualify as prospective evidence or a capability gate."
68
+ },
69
+ "family_mean_metrics": {
70
+ "ai_opt_out": {
71
+ "adapter": {
72
+ "total_variation": 0.22500793270880715,
73
+ "half_multiclass_brier": 0.3333062892499905,
74
+ "cross_entropy": 1.0985311480399016
75
+ },
76
+ "uniform": {
77
+ "total_variation": 0.22508591917767856,
78
+ "half_multiclass_brier": 0.33333333333333337,
79
+ "cross_entropy": 1.0986122886681098
80
+ },
81
+ "label_only_adapter": {
82
+ "total_variation": 0.224990606383629,
83
+ "half_multiclass_brier": 0.3332912875687366,
84
+ "cross_entropy": 1.098486096162415
85
+ }
86
+ },
87
+ "transport_access": {
88
+ "adapter": {
89
+ "total_variation": 0.6472529898714895,
90
+ "half_multiclass_brier": 0.40008870500723415,
91
+ "cross_entropy": 1.609881332612328,
92
+ "conditional_ordinal_brier": 0.27769394583069795
93
+ },
94
+ "uniform": {
95
+ "total_variation": 0.6471481010945515,
96
+ "half_multiclass_brier": 0.4,
97
+ "cross_entropy": 1.6094379124341003,
98
+ "conditional_ordinal_brier": 0.27763229662656286
99
+ },
100
+ "label_only_adapter": {
101
+ "total_variation": 0.6471444659562782,
102
+ "half_multiclass_brier": 0.399994578969822,
103
+ "cross_entropy": 1.609410615472915,
104
+ "conditional_ordinal_brier": 0.2775781946821805
105
+ }
106
+ },
107
+ "household_energy_hardship": {
108
+ "adapter": {
109
+ "total_variation": 0.38961891647745794,
110
+ "half_multiclass_brier": 0.24998735704906774,
111
+ "cross_entropy": 0.6931218896912488
112
+ },
113
+ "uniform": {
114
+ "total_variation": 0.3896358454383376,
115
+ "half_multiclass_brier": 0.25,
116
+ "cross_entropy": 0.6931471805599453
117
+ },
118
+ "label_only_adapter": {
119
+ "total_variation": 0.3896687993563178,
120
+ "half_multiclass_brier": 0.25002568114134616,
121
+ "cross_entropy": 0.6931985279407855
122
+ }
123
+ }
124
+ },
125
+ "equal_family_mean_metrics": {
126
+ "adapter": {
127
+ "total_variation": {
128
+ "mean": 0.4206266130192515,
129
+ "families": 3
130
+ },
131
+ "half_multiclass_brier": {
132
+ "mean": 0.3277941171020975,
133
+ "families": 3
134
+ },
135
+ "cross_entropy": {
136
+ "mean": 1.1338447901144928,
137
+ "families": 3
138
+ },
139
+ "conditional_ordinal_brier": {
140
+ "mean": 0.27769394583069795,
141
+ "families": 1
142
+ }
143
+ },
144
+ "uniform": {
145
+ "total_variation": {
146
+ "mean": 0.4206232885701892,
147
+ "families": 3
148
+ },
149
+ "half_multiclass_brier": {
150
+ "mean": 0.3277777777777778,
151
+ "families": 3
152
+ },
153
+ "cross_entropy": {
154
+ "mean": 1.1337324605540517,
155
+ "families": 3
156
+ },
157
+ "conditional_ordinal_brier": {
158
+ "mean": 0.27763229662656286,
159
+ "families": 1
160
+ }
161
+ },
162
+ "label_only_adapter": {
163
+ "total_variation": {
164
+ "mean": 0.42060129056540835,
165
+ "families": 3
166
+ },
167
+ "half_multiclass_brier": {
168
+ "mean": 0.3277705158933016,
169
+ "families": 3
170
+ },
171
+ "cross_entropy": {
172
+ "mean": 1.1336984131920385,
173
+ "families": 3
174
+ },
175
+ "conditional_ordinal_brier": {
176
+ "mean": 0.2775781946821805,
177
+ "families": 1
178
+ }
179
+ }
180
+ },
181
+ "rows": [
182
+ {
183
+ "question_id": "AI3",
184
+ "family": "ai_opt_out",
185
+ "instrument_sha256": "021efb8470916d366e8d31f64551b171cefbf932e258d984d5fc819a95e545e6",
186
+ "positive_weight_answered": 7451,
187
+ "positive_weight_unanswered": 34,
188
+ "status": "scored",
189
+ "observed_pweight_shares": [
190
+ 0.2407323356091079,
191
+ 0.5584192525110119,
192
+ 0.20084841187988017
193
+ ],
194
+ "comparisons": {
195
+ "adapter": {
196
+ "probabilities": [
197
+ 0.33331234008073807,
198
+ 0.3334113260110219,
199
+ 0.33327634632587433
200
+ ],
201
+ "metrics": {
202
+ "total_variation": 0.22500793270880715,
203
+ "half_multiclass_brier": 0.3333062892499905,
204
+ "cross_entropy": 1.0985311480399016
205
+ }
206
+ },
207
+ "uniform": {
208
+ "probabilities": [
209
+ 0.3333333333333333,
210
+ 0.3333333333333333,
211
+ 0.3333333333333333
212
+ ],
213
+ "metrics": {
214
+ "total_variation": 0.22508591917767856,
215
+ "half_multiclass_brier": 0.33333333333333337,
216
+ "cross_entropy": 1.0986122886681098
217
+ }
218
+ },
219
+ "label_only_adapter": {
220
+ "probabilities": [
221
+ 0.33353476226329803,
222
+ 0.33342864364385605,
223
+ 0.3330365891257922
224
+ ],
225
+ "metrics": {
226
+ "total_variation": 0.224990606383629,
227
+ "half_multiclass_brier": 0.3332912875687366,
228
+ "cross_entropy": 1.098486096162415
229
+ }
230
+ }
231
+ }
232
+ },
233
+ {
234
+ "question_id": "ACCESS_TRANSP",
235
+ "family": "transport_access",
236
+ "instrument_sha256": "0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9",
237
+ "positive_weight_answered": 7453,
238
+ "positive_weight_unanswered": 32,
239
+ "status": "scored",
240
+ "observed_pweight_shares": [
241
+ 0.8471481010945514,
242
+ 0.09089265202373137,
243
+ 0.029754360532852294,
244
+ 0.0185528897553797,
245
+ 0.013651996593485167
246
+ ],
247
+ "comparisons": {
248
+ "adapter": {
249
+ "probabilities": [
250
+ 0.19989511370658875,
251
+ 0.19993682205677032,
252
+ 0.2001804548005263,
253
+ 0.20015119264523187,
254
+ 0.19983642175793648
255
+ ],
256
+ "metrics": {
257
+ "total_variation": 0.6472529898714895,
258
+ "half_multiclass_brier": 0.40008870500723415,
259
+ "cross_entropy": 1.609881332612328,
260
+ "conditional_ordinal_brier": 0.27769394583069795
261
+ }
262
+ },
263
+ "uniform": {
264
+ "probabilities": [
265
+ 0.2,
266
+ 0.2,
267
+ 0.2,
268
+ 0.2,
269
+ 0.2
270
+ ],
271
+ "metrics": {
272
+ "total_variation": 0.6471481010945515,
273
+ "half_multiclass_brier": 0.4,
274
+ "cross_entropy": 1.6094379124341003,
275
+ "conditional_ordinal_brier": 0.27763229662656286
276
+ }
277
+ },
278
+ "label_only_adapter": {
279
+ "probabilities": [
280
+ 0.20000363513827324,
281
+ 0.19998866940538088,
282
+ 0.20019841318329176,
283
+ 0.20002333323160806,
284
+ 0.19978594904144606
285
+ ],
286
+ "metrics": {
287
+ "total_variation": 0.6471444659562782,
288
+ "half_multiclass_brier": 0.399994578969822,
289
+ "cross_entropy": 1.609410615472915,
290
+ "conditional_ordinal_brier": 0.2775781946821805
291
+ }
292
+ }
293
+ }
294
+ },
295
+ {
296
+ "question_id": "HSE14",
297
+ "family": "household_energy_hardship",
298
+ "instrument_sha256": "5a855cfd8dabeaa00f5c90fd2fb7664fe811bf2b5aed17e7708af59100ed114f",
299
+ "positive_weight_answered": 7469,
300
+ "positive_weight_unanswered": 16,
301
+ "status": "scored",
302
+ "observed_pweight_shares": [
303
+ 0.12475535538284471,
304
+ 0.8752446446171553
305
+ ],
306
+ "comparisons": {
307
+ "adapter": {
308
+ "probabilities": [
309
+ 0.49996401369571686,
310
+ 0.5000359962383906
311
+ ],
312
+ "metrics": {
313
+ "total_variation": 0.37520865334581843,
314
+ "half_multiclass_brier": 0.24997299023172737,
315
+ "cross_entropy": 0.693093151089736
316
+ }
317
+ },
318
+ "uniform": {
319
+ "probabilities": [
320
+ 0.5,
321
+ 0.5
322
+ ],
323
+ "metrics": {
324
+ "total_variation": 0.37524464461715534,
325
+ "half_multiclass_brier": 0.25,
326
+ "cross_entropy": 0.6931471805599453
327
+ }
328
+ },
329
+ "label_only_adapter": {
330
+ "probabilities": [
331
+ 0.5000329613685608,
332
+ 0.4999670535326004
333
+ ],
334
+ "metrics": {
335
+ "total_variation": 0.37527759853513554,
336
+ "half_multiclass_brier": 0.25002473264844316,
337
+ "cross_entropy": 0.693196630955005
338
+ }
339
+ }
340
+ }
341
+ },
342
+ {
343
+ "question_id": "HSE15",
344
+ "family": "household_energy_hardship",
345
+ "instrument_sha256": "08158766cc36144d94cfba8333e0c7449ecebdfca2afba45e5d1b2f570fa9d7f",
346
+ "positive_weight_answered": 7465,
347
+ "positive_weight_unanswered": 20,
348
+ "status": "scored",
349
+ "observed_pweight_shares": [
350
+ 0.09597295374048007,
351
+ 0.9040270462595199
352
+ ],
353
+ "comparisons": {
354
+ "adapter": {
355
+ "probabilities": [
356
+ 0.5000021333495775,
357
+ 0.4999978666504224
358
+ ],
359
+ "metrics": {
360
+ "total_variation": 0.40402917960909746,
361
+ "half_multiclass_brier": 0.2500017238664081,
362
+ "cross_entropy": 0.6931506282927615
363
+ }
364
+ },
365
+ "uniform": {
366
+ "probabilities": [
367
+ 0.5,
368
+ 0.5
369
+ ],
370
+ "metrics": {
371
+ "total_variation": 0.4040270462595199,
372
+ "half_multiclass_brier": 0.25,
373
+ "cross_entropy": 0.6931471805599453
374
+ }
375
+ },
376
+ "label_only_adapter": {
377
+ "probabilities": [
378
+ 0.5000329613685608,
379
+ 0.4999670535326004
380
+ ],
381
+ "metrics": {
382
+ "total_variation": 0.4040600001775001,
383
+ "half_multiclass_brier": 0.2500266296342492,
384
+ "cross_entropy": 0.693200424926566
385
+ }
386
+ }
387
+ }
388
+ }
389
+ ]
390
+ }
external/htops-transfer-v1/manifest.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "benchmark_id": "ces24-to-htops-2506-external-transfer-v1",
3
+ "status": "retrospective_out_of_source_research_only",
4
+ "protocol_freeze_commit": "796a2a7b240f436dbe133e71cd2f33162e1aba4e",
5
+ "prediction_freeze_commit": "2ee2690774a83f3bc22739f91a0a092931f25fe4",
6
+ "protocol_sha256": "c924081fed15725d1765b3c3a7547557980b63142ddc681ab7a88d4a3c4adf38",
7
+ "transfer_runner_sha256": "e4f2e62530571914fa7581090a976e2e390f7ada327a2f48f89428af9b2f39c0",
8
+ "files": {
9
+ "predictions.json": "70d9e412444a4a017345a6bc53c0567f0bc665d70d78648891d972e580648d93",
10
+ "evaluation.json": "16131d8bff4f373756fb33d679db6c541d63c8a8d2f5584e379a6716849a3621"
11
+ }
12
+ }
external/htops-transfer-v1/predictions.json ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "windtunnel-htops-transfer-predictions-v1",
3
+ "protocol_sha256": "c924081fed15725d1765b3c3a7547557980b63142ddc681ab7a88d4a3c4adf38",
4
+ "transfer_runner_sha256": "e4f2e62530571914fa7581090a976e2e390f7ada327a2f48f89428af9b2f39c0",
5
+ "model_adapter_sha256": "6b26a64bc2d3c19cd051efaf4fda42ff332dd4e5a74d6a10637acb770240cd9c",
6
+ "base": {
7
+ "repository": "sentence-transformers/all-MiniLM-L6-v2",
8
+ "revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
9
+ "files_sha256": {
10
+ "config.json": "953f9c0d463486b10a6871cc2fd59f223b2c70184f49815e7efbcab5d8908b41",
11
+ "model.safetensors": "53aa51172d142c89d9012cce15ae4d6cc0ca6895895114379cacb4fab128d9db",
12
+ "special_tokens_map.json": "303df45a03609e4ead04bc3dc1536d0ab19b5358db685b6f3da123d05ec200e3",
13
+ "tokenizer.json": "be50c3628f2bf5bb5e3a7f17b1f74611b2561a3a27eeab05e5aa30f411572037",
14
+ "tokenizer_config.json": "acb92769e8195aabd29b7b2137a9e6d6e25c476a4f15aa4355c233426c61576b",
15
+ "vocab.txt": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
16
+ }
17
+ },
18
+ "software": {
19
+ "torch": "2.7.1+cpu",
20
+ "transformers": "4.57.1",
21
+ "safetensors": "0.8.0"
22
+ },
23
+ "frozen_at_utc": "2026-11-28T02:56:11.047413+00:00",
24
+ "rows": [
25
+ {
26
+ "question_id": "AI3",
27
+ "instrument_sha256": "021efb8470916d366e8d31f64551b171cefbf932e258d984d5fc819a95e545e6",
28
+ "probabilities": {
29
+ "adapter": [
30
+ 0.33331234008073807,
31
+ 0.3334113260110219,
32
+ 0.33327634632587433
33
+ ],
34
+ "uniform": [
35
+ 0.3333333333333333,
36
+ 0.3333333333333333,
37
+ 0.3333333333333333
38
+ ],
39
+ "label_only_adapter": [
40
+ 0.33353476226329803,
41
+ 0.33342864364385605,
42
+ 0.3330365891257922
43
+ ]
44
+ }
45
+ },
46
+ {
47
+ "question_id": "ACCESS_TRANSP",
48
+ "instrument_sha256": "0e64614a6a638f0b64c6f81d30a42efd3c8a1fc14e934901a59f49f2f8f8b9d9",
49
+ "probabilities": {
50
+ "adapter": [
51
+ 0.19989511370658875,
52
+ 0.19993682205677032,
53
+ 0.2001804548005263,
54
+ 0.20015119264523187,
55
+ 0.19983642175793648
56
+ ],
57
+ "uniform": [
58
+ 0.2,
59
+ 0.2,
60
+ 0.2,
61
+ 0.2,
62
+ 0.2
63
+ ],
64
+ "label_only_adapter": [
65
+ 0.20000363513827324,
66
+ 0.19998866940538088,
67
+ 0.20019841318329176,
68
+ 0.20002333323160806,
69
+ 0.19978594904144606
70
+ ]
71
+ }
72
+ },
73
+ {
74
+ "question_id": "HSE14",
75
+ "instrument_sha256": "5a855cfd8dabeaa00f5c90fd2fb7664fe811bf2b5aed17e7708af59100ed114f",
76
+ "probabilities": {
77
+ "adapter": [
78
+ 0.49996401369571686,
79
+ 0.5000359962383906
80
+ ],
81
+ "uniform": [
82
+ 0.5,
83
+ 0.5
84
+ ],
85
+ "label_only_adapter": [
86
+ 0.5000329613685608,
87
+ 0.4999670535326004
88
+ ]
89
+ }
90
+ },
91
+ {
92
+ "question_id": "HSE15",
93
+ "instrument_sha256": "08158766cc36144d94cfba8333e0c7449ecebdfca2afba45e5d1b2f570fa9d7f",
94
+ "probabilities": {
95
+ "adapter": [
96
+ 0.5000021333495775,
97
+ 0.4999978666504224
98
+ ],
99
+ "uniform": [
100
+ 0.5,
101
+ 0.5
102
+ ],
103
+ "label_only_adapter": [
104
+ 0.5000329613685608,
105
+ 0.4999670535326004
106
+ ]
107
+ }
108
+ }
109
+ ]
110
+ }
external/htops-transfer-v1/protocol.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "ces24-to-htops-2506-external-transfer-v1",
3
+ "track": "retrospective_out_of_source",
4
+ "source": {
5
+ "id": "census-htops-hps-2506",
6
+ "publisher": "United States Census Bureau",
7
+ "field_dates": ["2025-06-16", "2025-06-25"],
8
+ "rights": "Published U.S. Census Bureau public-use statistical data and federal questionnaire. Release only aggregates, exact instrument excerpts and provenance.",
9
+ "universe": "U.S. adult survey respondents in the June 2025 HTOPS topical public-use release, using each selected question's documented all-respondent routing",
10
+ "estimand": "Person-weighted distribution among recorded substantive answers for each item, retaining offered uncertainty",
11
+ "weight": "PWEIGHT",
12
+ "missing_codes": ["", "-88", "-99"],
13
+ "puf_rows": 7485,
14
+ "puf_member": "HTOPS_HPS_2506_PUF.csv",
15
+ "dictionary_member": "HTOPS_HPS_2506_DATA_DICTIONARY_PUF_CSV.xlsx",
16
+ "dictionary_sha256": "0b1cc357d0c0c83438ae029bd132bd473a50fa689b6c925196b96691d5582c87",
17
+ "archive": {"url": "https://www2.census.gov/programs-surveys/demo/datasets/hhp/2025/topical/HTOPS_HPS_2506_CSV.zip", "sha256": "8d14cf52f5c3bc4fab5e74e3136cb753ab1195a06314725f00761035158172d4"},
18
+ "questionnaire": {"url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/HTOPS_2506_Questionnaire_ENGLISH.pdf", "sha256": "eabf314ba7d3f943e77658fbd787cecb5f90054c42deee3f25eb66d5764a0ad8"},
19
+ "user_notes": {"url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf", "sha256": "d85eca398268a94d4603c0f7fe62e4249e50babb9b0ce938c0c5d7ea9d143de1"},
20
+ "respondent_demographics": "Withheld. TAGE1 and REDUC1 describe baseline-roster Person 1. The reviewed documents do not establish that Person 1 answered these questions. No HTOPS demographic input or subgroup estimates."
21
+ },
22
+ "model": {
23
+ "repository": "Giuliocc/windtunnel-response-encoder",
24
+ "revision": "29973d528b804d3c6564243b96410325f9d62b0b",
25
+ "adapter_sha256": "6b26a64bc2d3c19cd051efaf4fda42ff332dd4e5a74d6a10637acb770240cd9c",
26
+ "base_config_sha256": "571b74b43adead7e559e53ab216b56d8ec7bdf45cd24f1e7be387e9488eba4ed",
27
+ "encoder_runner_sha256": "2052ababa9708b71ee35a74583a6384bb6caab52fd0efdb4ea1445719de0c553",
28
+ "source_helpers_sha256": "08f04b88bc5f994b8a49f3d672f0ab5dec99220d1bb325979a7b335888c48e76",
29
+ "scorer_sha256": "f103271a0c7fd79f5cdc79b11f424c2d90e5438430fb9bd2daa7e988d31e9918",
30
+ "original_prompt_prefix": "2024 CES pre-election survey, US citizen adults, English. ",
31
+ "external_prompt_prefix": "June 2025 U.S. Census Household Trends and Outlook Pulse Survey, U.S. adult respondents, English. ",
32
+ "population_standardization": "Arithmetic mean over the 12 named CES age-by-education cells, a fixed arbitrary reference mixture. These are not HTOPS demographic weights. This unconditioned estimate uses neither the model's unknown-cell embedding nor any HTOPS response or demographic values."
33
+ },
34
+ "baselines": {
35
+ "uniform": "Equal probability over the offered choices.",
36
+ "label_only_adapter": "Same fixed model, external prefix, response format, option order, option text, and 12-cell averaging, with the question stem and preceding context removed."
37
+ },
38
+ "metrics": ["total_variation", "half_multiclass_brier", "cross_entropy", "conditional_ordinal_brier"],
39
+ "aggregation": "Equal items within family, then equal families on the same set of scored items. Ordinal Brier applies only to registered ordered response scales.",
40
+ "minimum_public_category_count": 10,
41
+ "promotion": {"minimum_independent_test_families": 10, "status": "withheld", "reason": "One retrospective external cohort and three held-out expert-classified families. This test does not qualify as prospective evidence or a capability gate."},
42
+ "items": [
43
+ {
44
+ "question_id": "AI3",
45
+ "questionnaire_id": "AI3",
46
+ "questionnaire_page": 22,
47
+ "family": "ai_opt_out",
48
+ "question_text": "In the last 2 months, have you actively opted out of using an AI system? (e.g., disabling facial recognition, turning off a virtual assistant, stopping use of an AI-driven app)",
49
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}, {"id": "3", "label": "Not sure"}],
50
+ "ordinal_order": []
51
+ },
52
+ {
53
+ "question_id": "ACCESS_TRANSP",
54
+ "questionnaire_id": "TRANS2",
55
+ "questionnaire_page": 19,
56
+ "family": "transport_access",
57
+ "question_text": "Which one of the following statements best describes your access to transportation in the last 4 weeks:",
58
+ "options": [{"id": "1", "label": "Enough transportation to meet your needs"}, {"id": "2", "label": "Enough transportation, but not always the kinds you want to use"}, {"id": "3", "label": "Sometimes not enough transportation to meet your needs"}, {"id": "4", "label": "Often not enough transportation to meet your needs"}, {"id": "5", "label": "Always not enough transportation to meet your needs"}],
59
+ "ordinal_order": ["1", "2", "3", "4", "5"]
60
+ },
61
+ {
62
+ "question_id": "HSE14",
63
+ "questionnaire_id": "HSE14",
64
+ "questionnaire_page": 17,
65
+ "family": "household_energy_hardship",
66
+ "question_text": "In the last 2 months, did your household reduce or forego expenses for basic household necessities, such as medicine or food, in order to pay an energy bill?",
67
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}],
68
+ "ordinal_order": []
69
+ },
70
+ {
71
+ "question_id": "HSE15",
72
+ "questionnaire_id": "HSE15",
73
+ "questionnaire_page": 17,
74
+ "family": "household_energy_hardship",
75
+ "question_text": "In the last 2 months, did your household keep your home at a temperature that you felt was unsafe or unhealthy?",
76
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}],
77
+ "ordinal_order": []
78
+ }
79
+ ]
80
+ }
external/htops-transfer-v1/reproduction/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
external/htops-transfer-v1/reproduction/THIRD_PARTY_NOTICES.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Third-party material
2
+
3
+ CES Common Content 2024 V9 instruments and response aggregates derive from the CC0 1.0 Dataverse release. The records and source files have separate identifiers and hashes in the source receipt. [CES Dataverse record](https://doi.org/10.7910/DVN/X11EP6)
4
+
5
+ The 2024 one-year PUMS population cells derive from U.S. Census Bureau federal public-use microdata. Retain the agency attribution and documentation. [ACS PUMS documentation](https://www.census.gov/programs-surveys/acs/microdata/access.2024.html)
6
+
7
+ The encoder adapter requires the Apache-2.0 MiniLM base at revision `1110a243fdf4706b3f48f1d95db1a4f5529b4d41`. The head and replacement last block are experimental derivatives. [Base model](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/tree/1110a243fdf4706b3f48f1d95db1a4f5529b4d41)
external/htops-transfer-v1/reproduction/configs/encoder.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "base": "sentence-transformers/all-MiniLM-L6-v2",
3
+ "revision": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
4
+ "license": "apache-2.0",
5
+ "max_tokens": 256,
6
+ "probe_steps": 160,
7
+ "adapt_steps": 40,
8
+ "batch_items": 2,
9
+ "threads": 3,
10
+ "probe_lr": 0.003,
11
+ "adapt_lr": 2e-05,
12
+ "base_files_sha256": {
13
+ "config.json": "953f9c0d463486b10a6871cc2fd59f223b2c70184f49815e7efbcab5d8908b41",
14
+ "model.safetensors": "53aa51172d142c89d9012cce15ae4d6cc0ca6895895114379cacb4fab128d9db",
15
+ "special_tokens_map.json": "303df45a03609e4ead04bc3dc1536d0ab19b5358db685b6f3da123d05ec200e3",
16
+ "tokenizer.json": "be50c3628f2bf5bb5e3a7f17b1f74611b2561a3a27eeab05e5aa30f411572037",
17
+ "tokenizer_config.json": "acb92769e8195aabd29b7b2137a9e6d6e25c476a4f15aa4355c233426c61576b",
18
+ "vocab.txt": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
19
+ }
20
+ }
external/htops-transfer-v1/reproduction/configs/htops-transfer-v1.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "ces24-to-htops-2506-external-transfer-v1",
3
+ "track": "retrospective_out_of_source",
4
+ "source": {
5
+ "id": "census-htops-hps-2506",
6
+ "publisher": "United States Census Bureau",
7
+ "field_dates": ["2025-06-16", "2025-06-25"],
8
+ "rights": "Published U.S. Census Bureau public-use statistical data and federal questionnaire. Release only aggregates, exact instrument excerpts and provenance.",
9
+ "universe": "U.S. adult survey respondents in the June 2025 HTOPS topical public-use release, using each selected question's documented all-respondent routing",
10
+ "estimand": "Person-weighted distribution among recorded substantive answers for each item, retaining offered uncertainty",
11
+ "weight": "PWEIGHT",
12
+ "missing_codes": ["", "-88", "-99"],
13
+ "puf_rows": 7485,
14
+ "puf_member": "HTOPS_HPS_2506_PUF.csv",
15
+ "dictionary_member": "HTOPS_HPS_2506_DATA_DICTIONARY_PUF_CSV.xlsx",
16
+ "dictionary_sha256": "0b1cc357d0c0c83438ae029bd132bd473a50fa689b6c925196b96691d5582c87",
17
+ "archive": {"url": "https://www2.census.gov/programs-surveys/demo/datasets/hhp/2025/topical/HTOPS_HPS_2506_CSV.zip", "sha256": "8d14cf52f5c3bc4fab5e74e3136cb753ab1195a06314725f00761035158172d4"},
18
+ "questionnaire": {"url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/HTOPS_2506_Questionnaire_ENGLISH.pdf", "sha256": "eabf314ba7d3f943e77658fbd787cecb5f90054c42deee3f25eb66d5764a0ad8"},
19
+ "user_notes": {"url": "https://www2.census.gov/programs-surveys/demo/technical-documentation/hhp/2506_HTOPS_Household_Pulse_User_Notes_04232026.pdf", "sha256": "d85eca398268a94d4603c0f7fe62e4249e50babb9b0ce938c0c5d7ea9d143de1"},
20
+ "respondent_demographics": "Withheld. TAGE1 and REDUC1 describe baseline-roster Person 1. The reviewed documents do not establish that Person 1 answered these questions. No HTOPS demographic input or subgroup estimates."
21
+ },
22
+ "model": {
23
+ "repository": "Giuliocc/windtunnel-response-encoder",
24
+ "revision": "29973d528b804d3c6564243b96410325f9d62b0b",
25
+ "adapter_sha256": "6b26a64bc2d3c19cd051efaf4fda42ff332dd4e5a74d6a10637acb770240cd9c",
26
+ "base_config_sha256": "571b74b43adead7e559e53ab216b56d8ec7bdf45cd24f1e7be387e9488eba4ed",
27
+ "encoder_runner_sha256": "2052ababa9708b71ee35a74583a6384bb6caab52fd0efdb4ea1445719de0c553",
28
+ "source_helpers_sha256": "08f04b88bc5f994b8a49f3d672f0ab5dec99220d1bb325979a7b335888c48e76",
29
+ "scorer_sha256": "f103271a0c7fd79f5cdc79b11f424c2d90e5438430fb9bd2daa7e988d31e9918",
30
+ "original_prompt_prefix": "2024 CES pre-election survey, US citizen adults, English. ",
31
+ "external_prompt_prefix": "June 2025 U.S. Census Household Trends and Outlook Pulse Survey, U.S. adult respondents, English. ",
32
+ "population_standardization": "Arithmetic mean over the 12 named CES age-by-education cells, a fixed arbitrary reference mixture. These are not HTOPS demographic weights. This unconditioned estimate uses neither the model's unknown-cell embedding nor any HTOPS response or demographic values."
33
+ },
34
+ "baselines": {
35
+ "uniform": "Equal probability over the offered choices.",
36
+ "label_only_adapter": "Same fixed model, external prefix, response format, option order, option text, and 12-cell averaging, with the question stem and preceding context removed."
37
+ },
38
+ "metrics": ["total_variation", "half_multiclass_brier", "cross_entropy", "conditional_ordinal_brier"],
39
+ "aggregation": "Equal items within family, then equal families on the same set of scored items. Ordinal Brier applies only to registered ordered response scales.",
40
+ "minimum_public_category_count": 10,
41
+ "promotion": {"minimum_independent_test_families": 10, "status": "withheld", "reason": "One retrospective external cohort and three held-out expert-classified families. This test does not qualify as prospective evidence or a capability gate."},
42
+ "items": [
43
+ {
44
+ "question_id": "AI3",
45
+ "questionnaire_id": "AI3",
46
+ "questionnaire_page": 22,
47
+ "family": "ai_opt_out",
48
+ "question_text": "In the last 2 months, have you actively opted out of using an AI system? (e.g., disabling facial recognition, turning off a virtual assistant, stopping use of an AI-driven app)",
49
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}, {"id": "3", "label": "Not sure"}],
50
+ "ordinal_order": []
51
+ },
52
+ {
53
+ "question_id": "ACCESS_TRANSP",
54
+ "questionnaire_id": "TRANS2",
55
+ "questionnaire_page": 19,
56
+ "family": "transport_access",
57
+ "question_text": "Which one of the following statements best describes your access to transportation in the last 4 weeks:",
58
+ "options": [{"id": "1", "label": "Enough transportation to meet your needs"}, {"id": "2", "label": "Enough transportation, but not always the kinds you want to use"}, {"id": "3", "label": "Sometimes not enough transportation to meet your needs"}, {"id": "4", "label": "Often not enough transportation to meet your needs"}, {"id": "5", "label": "Always not enough transportation to meet your needs"}],
59
+ "ordinal_order": ["1", "2", "3", "4", "5"]
60
+ },
61
+ {
62
+ "question_id": "HSE14",
63
+ "questionnaire_id": "HSE14",
64
+ "questionnaire_page": 17,
65
+ "family": "household_energy_hardship",
66
+ "question_text": "In the last 2 months, did your household reduce or forego expenses for basic household necessities, such as medicine or food, in order to pay an energy bill?",
67
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}],
68
+ "ordinal_order": []
69
+ },
70
+ {
71
+ "question_id": "HSE15",
72
+ "questionnaire_id": "HSE15",
73
+ "questionnaire_page": 17,
74
+ "family": "household_energy_hardship",
75
+ "question_text": "In the last 2 months, did your household keep your home at a temperature that you felt was unsafe or unhealthy?",
76
+ "options": [{"id": "1", "label": "Yes"}, {"id": "2", "label": "No"}],
77
+ "ordinal_order": []
78
+ }
79
+ ]
80
+ }
external/htops-transfer-v1/reproduction/requirements-encoder-lock.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ -r requirements-lock.txt
3
+ torch==2.7.1+cpu
4
+ transformers==4.57.1
5
+ safetensors==0.8.0
6
+ tokenizers==0.22.2
7
+ regex==2026.11.25
8
+ sympy==1.14.0
9
+ mpmath==1.3.0
10
+ networkx==3.7
11
+ Jinja2==3.1.6
12
+ MarkupSafe==3.0.3
13
+ huggingface-hub==0.36.2
external/htops-transfer-v1/reproduction/requirements-lock.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ numpy==2.3.5
2
+ pandas==2.2.3
3
+ scipy==1.17.0
4
+ scikit-learn==1.8.0
5
+ threadpoolctl==3.6.0
6
+ joblib==1.5.3
7
+ pyarrow==26.0.1
8
+ huggingface-hub==0.36.2
9
+ certifi==2026.10.19
10
+ charset-normalizer==3.5.2
11
+ filelock==4.2.4
12
+ fsspec==2026.9.0
13
+ packaging==26.3
14
+ PyYAML==6.0.3
15
+ requests==2.34.2
16
+ tqdm==4.70.1
17
+ typing_extensions==4.16.0
18
+ urllib3==2.8.0
19
+ idna==3.18
20
+ hf-xet==1.8.0
21
+ python-dateutil==4.0.0
22
+ httpx==0.28.1
23
+ httpcore==1.0.9
24
+ h11==0.16.0
25
+ anyio==4.14.2
26
+ click==8.4.2
27
+ pytz==2026.6
28
+ tzdata==2026.2
external/htops-transfer-v1/reproduction/scripts/htops_transfer.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Freeze and score an offline retrospective transfer test on Census HTOPS."""
2
+
3
+ import argparse
4
+ from collections import defaultdict
5
+ import csv
6
+ from hashlib import sha256
7
+ from importlib.metadata import version
8
+ from io import TextIOWrapper
9
+ import math
10
+ from pathlib import Path
11
+ from statistics import mean
12
+ from zipfile import ZipFile
13
+
14
+ from windtunnel_response import baseline, sources
15
+
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ PROTOCOL = ROOT / "configs" / "htops-transfer-v1.json"
19
+ BASE_CONFIG = ROOT / "configs" / "encoder.json"
20
+ METHODS = ("adapter", "uniform", "label_only_adapter")
21
+
22
+
23
+ def require_digest(path, expected):
24
+ if sources.digest(path) != expected:
25
+ raise ValueError(f"SHA-256 mismatch for {Path(path).name}.")
26
+
27
+
28
+ def verify_source(source, archive, questionnaire, user_notes):
29
+ for path, pin in ((archive, "archive"), (questionnaire, "questionnaire"), (user_notes, "user_notes")):
30
+ require_digest(path, source[pin]["sha256"])
31
+ with ZipFile(archive) as zipped:
32
+ if sha256(zipped.read(source["dictionary_member"])).hexdigest() != source["dictionary_sha256"]:
33
+ raise ValueError("HTOPS dictionary does not match the protocol.")
34
+
35
+
36
+ def instrument(item):
37
+ return {**item, "response_type": "single_choice", "preceding_context": "", "stimulus_text": ""}
38
+
39
+
40
+ def freeze_predictions(protocol, base_dir, adapter):
41
+ import torch
42
+ from safetensors.torch import load_file
43
+ from transformers import AutoModel, AutoTokenizer
44
+ from windtunnel_response import encoder
45
+
46
+ pin = protocol["model"]
47
+ require_digest(BASE_CONFIG, pin["base_config_sha256"])
48
+ require_digest(encoder.__file__, pin["encoder_runner_sha256"])
49
+ require_digest(baseline.__file__, pin["scorer_sha256"])
50
+ require_digest(adapter, pin["adapter_sha256"])
51
+ base = sources.read(BASE_CONFIG)
52
+ for file, expected in base["base_files_sha256"].items():
53
+ require_digest(base_dir / file, expected)
54
+ torch.set_num_threads(base["threads"])
55
+ torch.use_deterministic_algorithms(True)
56
+ tokenizer = AutoTokenizer.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False)
57
+ model = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval()
58
+ scorer = encoder.OptionScorer(model.config.hidden_size).eval()
59
+ checkpoint = load_file(adapter, device="cpu")
60
+ model.encoder.layer[-1].load_state_dict({
61
+ key.removeprefix("last_block."): value for key, value in checkpoint.items() if key.startswith("last_block.")
62
+ })
63
+ scorer.load_state_dict({
64
+ key.removeprefix("head."): value for key, value in checkpoint.items() if key.startswith("head.")
65
+ })
66
+
67
+ @torch.no_grad()
68
+ def predict(question):
69
+ prompts, options = zip(*encoder.inputs(question), strict=True)
70
+ previous_prefix = pin["original_prompt_prefix"]
71
+ if not all(prompt.startswith(previous_prefix) for prompt in prompts):
72
+ raise ValueError("The frozen input template no longer matches this transfer protocol.")
73
+ prompts = [pin["external_prompt_prefix"] + prompt.removeprefix(previous_prefix) for prompt in prompts]
74
+ tokens = tokenizer(prompts, options, padding=True, truncation=False, return_tensors="pt")
75
+ if tokens.input_ids.shape[1] > base["max_tokens"]:
76
+ raise ValueError("An instrument exceeds the frozen token bound.")
77
+ probabilities = scorer(encoder.pooled(model, tokens)).softmax(dim=-1)
78
+ return probabilities[:len(sources.CELLS)].to(torch.float64).mean(dim=0).tolist()
79
+
80
+ rows = []
81
+ for item in protocol["items"]:
82
+ question = instrument(item)
83
+ rows.append({
84
+ "question_id": item["question_id"],
85
+ "instrument_sha256": sources.object_hash(question),
86
+ "probabilities": {
87
+ "adapter": predict(question),
88
+ "uniform": [1 / len(question["options"])] * len(question["options"]),
89
+ "label_only_adapter": predict({**question, "question_text": ""}),
90
+ },
91
+ })
92
+ return {
93
+ "schema_version": "windtunnel-htops-transfer-predictions-v1",
94
+ "protocol_sha256": sources.digest(PROTOCOL),
95
+ "transfer_runner_sha256": sources.digest(__file__),
96
+ "model_adapter_sha256": pin["adapter_sha256"],
97
+ "base": {"repository": base["base"], "revision": base["revision"], "files_sha256": base["base_files_sha256"]},
98
+ "software": {name: version(name) for name in ("torch", "transformers", "safetensors")},
99
+ "frozen_at_utc": sources.now(),
100
+ "rows": rows,
101
+ }
102
+
103
+
104
+ def approved_predictions(protocol, path, expected):
105
+ require_digest(path, expected)
106
+ frozen = sources.read(path)
107
+ if (frozen["schema_version"] != "windtunnel-htops-transfer-predictions-v1"
108
+ or frozen["model_adapter_sha256"] != protocol["model"]["adapter_sha256"]
109
+ or frozen["protocol_sha256"] != sources.digest(PROTOCOL)
110
+ or frozen["transfer_runner_sha256"] != sources.digest(__file__)):
111
+ raise ValueError("Predictions do not bind to this protocol, runner, and model.")
112
+ items = protocol["items"]
113
+ if len(frozen["rows"]) != len(items):
114
+ raise ValueError("Frozen predictions must cover every registered item.")
115
+ predictions = {}
116
+ for item, row in zip(items, frozen["rows"], strict=True):
117
+ question_id = item["question_id"]
118
+ if row["question_id"] != question_id or row["instrument_sha256"] != sources.object_hash(instrument(item)):
119
+ raise ValueError("Frozen predictions contain a different instrument.")
120
+ if set(row["probabilities"]) != set(METHODS):
121
+ raise ValueError("Frozen predictions do not contain every registered comparator.")
122
+ for values in row["probabilities"].values():
123
+ if (len(values) != len(item["options"]) or any(not math.isfinite(p) or not 0 <= p <= 1 for p in values)
124
+ or not math.isclose(math.fsum(values), 1, abs_tol=1e-6)):
125
+ raise ValueError("Invalid frozen option probabilities.")
126
+ predictions[question_id] = row
127
+ return frozen, predictions
128
+
129
+
130
+ def source_aggregates(protocol, archive):
131
+ source = protocol["source"]
132
+ counts = {
133
+ item["question_id"]: {option["id"]: [0, 0.0] for option in item["options"]}
134
+ for item in protocol["items"]
135
+ }
136
+ total = positive_weight = 0
137
+ with ZipFile(archive) as zipped, zipped.open(source["puf_member"]) as stream:
138
+ reader = csv.DictReader(TextIOWrapper(stream, encoding="utf-8-sig", newline=""))
139
+ if not set((*counts, source["weight"])) <= set(reader.fieldnames or []):
140
+ raise ValueError("Required weight or instrument fields are absent.")
141
+ for row in reader:
142
+ total += 1
143
+ weight = float(row[source["weight"]] or 0)
144
+ if not math.isfinite(weight) or weight < 0:
145
+ raise ValueError("An invalid person weight prevents aggregation.")
146
+ if not weight:
147
+ continue
148
+ positive_weight += 1
149
+ for question, options in counts.items():
150
+ response = row[question].strip()
151
+ if response in source["missing_codes"]:
152
+ continue
153
+ if response not in options:
154
+ raise ValueError(f"Unexpected response code for {question}.")
155
+ options[response][0] += 1
156
+ options[response][1] += weight
157
+ if total != source["puf_rows"]:
158
+ raise ValueError("HTOPS row count differs from the reviewed source.")
159
+ return total, positive_weight, counts
160
+
161
+
162
+ def evaluate(protocol, predictions_path, expected, archive):
163
+ require_digest(baseline.__file__, protocol["model"]["scorer_sha256"])
164
+ frozen, predictions = approved_predictions(protocol, predictions_path, expected)
165
+ # The public, pre-existing outcomes are first opened only after validating
166
+ # the exact committed prediction file. No tuning takes place in scoring.
167
+ total, positive_weight, counts = source_aggregates(protocol, archive)
168
+ rows, family_scores = [], defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
169
+ for item in protocol["items"]:
170
+ question = item["question_id"]
171
+ options = list(counts[question].values())
172
+ n = sum(value[0] for value in options)
173
+ row = {
174
+ "question_id": question, "family": item["family"],
175
+ "instrument_sha256": predictions[question]["instrument_sha256"],
176
+ "positive_weight_answered": n, "positive_weight_unanswered": positive_weight - n,
177
+ }
178
+ if min(value[0] for value in options) < protocol["minimum_public_category_count"]:
179
+ rows.append({**row, "status": "withheld_below_category_floor"})
180
+ continue
181
+ mass = math.fsum(value[1] for value in options)
182
+ reference = [value[1] / mass for value in options]
183
+ comparisons = {}
184
+ for method, prediction in predictions[question]["probabilities"].items():
185
+ metrics = baseline.scores(prediction, reference, item["ordinal_order"])
186
+ comparisons[method] = {"probabilities": prediction, "metrics": metrics}
187
+ for metric, value in metrics.items():
188
+ family_scores[item["family"]][method][metric].append(value)
189
+ rows.append({**row, "status": "scored", "observed_pweight_shares": reference, "comparisons": comparisons})
190
+ families = {
191
+ key: {method: {metric: mean(values) for metric, values in metrics.items()} for method, metrics in methods.items()}
192
+ for key, methods in family_scores.items()
193
+ }
194
+ cross_family = {}
195
+ for method in METHODS:
196
+ cross_family[method] = {}
197
+ for metric in protocol["metrics"]:
198
+ values = [family[method][metric] for family in families.values() if metric in family[method]]
199
+ if values:
200
+ cross_family[method][metric] = {"mean": mean(values), "families": len(values)}
201
+ return {
202
+ "schema_version": "windtunnel-htops-transfer-evaluation-v1",
203
+ "benchmark_id": protocol["id"],
204
+ "track": protocol["track"],
205
+ "protocol_sha256": frozen["protocol_sha256"],
206
+ "predictions_sha256": expected,
207
+ "predictions_frozen_at_utc": frozen["frozen_at_utc"],
208
+ "scored_at_utc": sources.now(),
209
+ "source": protocol["source"],
210
+ "model": protocol["model"],
211
+ "population_conditioning": "withheld",
212
+ "puf_rows": total,
213
+ "positive_person_weight_rows": positive_weight,
214
+ "coverage": {
215
+ "items_registered": len(rows), "items_scored": sum(row["status"] == "scored" for row in rows),
216
+ "families_registered": len({item["family"] for item in protocol["items"]}), "families_scored": len(families),
217
+ },
218
+ "promotion": protocol["promotion"],
219
+ "family_mean_metrics": families,
220
+ "equal_family_mean_metrics": cross_family,
221
+ "rows": rows,
222
+ }
223
+
224
+
225
+ def main():
226
+ parser = argparse.ArgumentParser(description=__doc__)
227
+ for name in ("archive", "questionnaire", "user-notes", "output"):
228
+ parser.add_argument(f"--{name}", required=True, type=Path)
229
+ commands = parser.add_subparsers(dest="phase", required=True)
230
+ freeze = commands.add_parser("freeze", help="Verify the source metadata and freeze predictions without opening responses.")
231
+ freeze.add_argument("--base-dir", required=True, type=Path)
232
+ freeze.add_argument("--adapter", required=True, type=Path)
233
+ score = commands.add_parser("score", help="Verify the committed prediction digest, then score observed aggregates.")
234
+ score.add_argument("--predictions", required=True, type=Path)
235
+ score.add_argument("--predictions-sha256", required=True)
236
+ args = parser.parse_args()
237
+ try:
238
+ protocol = sources.read(PROTOCOL)
239
+ require_digest(sources.__file__, protocol["model"]["source_helpers_sha256"])
240
+ verify_source(protocol["source"], args.archive, args.questionnaire, args.user_notes)
241
+ if args.phase == "freeze":
242
+ result = freeze_predictions(protocol, args.base_dir, args.adapter)
243
+ else:
244
+ result = evaluate(protocol, args.predictions, args.predictions_sha256, args.archive)
245
+ sources.write(args.output, result)
246
+ except (ValueError, OSError, KeyError) as error:
247
+ parser.error(str(error))
248
+
249
+
250
+ if __name__ == "__main__":
251
+ main()
external/htops-transfer-v1/reproduction/src/windtunnel_response/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Wind Tunnel Response Lab research software."""
external/htops-transfer-v1/reproduction/src/windtunnel_response/baseline.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fitted known-item model, development selection and respondent-holdout scoring."""
2
+ from time import perf_counter
3
+
4
+ import numpy as np
5
+ from scipy.special import softmax
6
+ from sklearn.linear_model import LogisticRegression
7
+ from threadpoolctl import threadpool_limits
8
+
9
+ from .sources import CELLS, object_hash
10
+
11
+ FEATURES = ["age_30_44", "age_45_64", "age_65_plus", "education_some_college", "education_bachelors_plus", "unknown"]
12
+ DESIGN = np.asarray([
13
+ [int(a == j) for j in (1,2,3)] + [int(e == j) for j in (1,2)] + [0]
14
+ for a in range(4) for e in range(3)
15
+ ] + [[0,0,0,0,0,1]], dtype=float)
16
+
17
+
18
+ def observed(df, question):
19
+ key = question["question_id"]
20
+ n_options = len(question["options"])
21
+ labels = df[key].to_numpy()
22
+ weights = df.commonweight.to_numpy()
23
+ valid = np.isin(labels, np.arange(1, n_options + 1))
24
+ y = labels[valid].astype(int) - 1
25
+ w = weights[valid]
26
+ counts = np.bincount(y, minlength=n_options)
27
+ masses = np.bincount(y, weights=w, minlength=n_options)
28
+ weight_sum = float(w.sum())
29
+ squared = float(w @ w)
30
+ return {
31
+ "human_n_eligible": len(df), "human_n_answered": len(y), "human_n_missing": len(df)-len(y),
32
+ "human_n_selected": counts.tolist(), "weight_sum": weight_sum, "weight_sum_squared": squared,
33
+ "eligible_weight_sum": float(weights.sum()),
34
+ "effective_n_weight_only": weight_sum ** 2 / squared if squared else 0,
35
+ "weighted_outcome_mass": masses.tolist(),
36
+ "probabilities": (masses / weight_sum).tolist() if weight_sum else None,
37
+ }
38
+
39
+
40
+ def probabilities(model, cell, candidate=None):
41
+ if cell not in [*CELLS, "unknown"]:
42
+ raise ValueError("Unknown population cell")
43
+ selected = candidate or model["champion"]
44
+ if selected == "uniform":
45
+ return np.full(len(model["marginal"]), 1.0 / len(model["marginal"]))
46
+ if selected == "marginal":
47
+ return np.asarray(model["marginal"])
48
+ if selected != "linear":
49
+ raise ValueError("Unsupported predictor")
50
+ return softmax(np.asarray(model["coefficients"]) @ DESIGN[[*CELLS, "unknown"].index(cell)] + model["intercepts"])
51
+
52
+
53
+ def scores(predicted, obs, ordered):
54
+ p, q = np.asarray(predicted), np.asarray(obs)
55
+ report = {
56
+ "total_variation": float(0.5 * np.abs(p-q).sum()),
57
+ "half_multiclass_brier": float(0.5 * (1 + p @ p - 2 * p @ q)),
58
+ "cross_entropy": float(-q @ np.log(np.clip(p, 1e-15, 1))),
59
+ }
60
+ if len(ordered) >= 3 and min(p[:len(ordered)].sum(), q[:len(ordered)].sum()) > 0:
61
+ count = len(ordered)
62
+ pc = np.cumsum(p[:count] / p[:count].sum())[:-1]
63
+ qc = np.cumsum(q[:count] / q[:count].sum())[:-1]
64
+ report["conditional_ordinal_brier"] = float(np.mean(qc * (1 - pc)**2 + (1 - qc) * pc**2))
65
+ return report
66
+
67
+
68
+ def fitted_model(part, question, protocol):
69
+ summary = observed(part, question)
70
+ key = question["question_id"]
71
+ count = len(question["options"])
72
+ valid = part[key].isin(range(1, count+1))
73
+ answerers = part.loc[valid]
74
+ weights = answerers.commonweight.to_numpy()
75
+ with threadpool_limits(limits=2):
76
+ trained = LogisticRegression(C=protocol["known_item"]["l2_c"], solver="lbfgs", max_iter=400, tol=1e-8)
77
+ trained.fit(DESIGN[answerers.cell.to_numpy()], answerers[key].astype(int).to_numpy(), sample_weight=weights / weights.mean())
78
+ if trained.classes_.tolist() != list(range(1, count+1)) or max(trained.n_iter_) >= trained.max_iter:
79
+ raise ValueError(f"Incomplete or nonconverged fit: {key}")
80
+ coef, intercept = trained.coef_, trained.intercept_
81
+ if count == 2:
82
+ coef = np.vstack((np.zeros_like(coef), coef))
83
+ intercept = np.hstack(([0.0], intercept))
84
+ cells = {}
85
+ for idx, cell in enumerate(CELLS):
86
+ cell_obs = observed(part[part.cell == idx], question)
87
+ cells[cell] = {
88
+ "answered": cell_obs["human_n_answered"],
89
+ "effective_n_weight_only": cell_obs["effective_n_weight_only"],
90
+ "supported": cell_obs["human_n_answered"] >= protocol["known_item"]["minimum_cell_answered"]
91
+ and cell_obs["effective_n_weight_only"] >= protocol["known_item"]["minimum_cell_kish"],
92
+ }
93
+ return {
94
+ "instrument_hash": question["instrument_hash"], "option_ids": [o["id"] for o in question["options"]],
95
+ "marginal": summary["probabilities"], "coefficients": coef.tolist(), "intercepts": intercept.tolist(),
96
+ "iterations": int(max(trained.n_iter_)), "trainable_parameters": int(trained.coef_.size + trained.intercept_.size),
97
+ "training_support": cells,
98
+ }
99
+
100
+
101
+ def by_cell(part, q):
102
+ return {cell: observed(part[part.cell == index], q) for index, cell in enumerate([*CELLS, "unknown"]) if cell != "unknown"} | {
103
+ "unknown": observed(part[part.cell == -1], q),
104
+ }
105
+
106
+
107
+ def evaluate_candidate(model, cells, q, candidate):
108
+ relevant = [(key, obs) for key, obs in cells.items() if obs["human_n_answered"]]
109
+ weight = np.asarray([obs["weight_sum"] for _, obs in relevant])
110
+ weight /= weight.sum()
111
+ prediction = np.asarray([probabilities(model, key, candidate) for key, _ in relevant])
112
+ reference = np.asarray([obs["probabilities"] for _, obs in relevant])
113
+ national = scores(weight @ prediction, weight @ reference, q["ordinal_order"])
114
+ subgroup = [scores(p, observed_p, q["ordinal_order"]) for p, observed_p in zip(prediction, reference)]
115
+ summary = {metric: float(sum(w * item[metric] for w, item in zip(weight, subgroup) if metric in item) /
116
+ sum(w for w, item in zip(weight, subgroup) if metric in item)) for metric in national if any(metric in item for item in subgroup)}
117
+ return {"prediction": (weight @ prediction).tolist(), "national": national, "within_cell": summary}
118
+
119
+
120
+ def train(df, items, frozen, config):
121
+ start = perf_counter()
122
+ protocol = frozen["protocol"]
123
+ models = {}
124
+ development = {}
125
+ training = df[df.split == "train"]
126
+ dev = df[df.split == "dev"]
127
+ for q in items:
128
+ key = q["question_id"]
129
+ model = fitted_model(training, q, protocol)
130
+ cells = by_cell(dev, q)
131
+ evaluated = {name: evaluate_candidate(model, cells, q, name) for name in ("marginal", "linear")}
132
+ model["champion"] = min(evaluated, key=lambda name: evaluated[name]["within_cell"]["half_multiclass_brier"])
133
+ models[key] = model
134
+ development[key] = evaluated
135
+ return {
136
+ **{k: config[k] for k in ("method_id","method_version")},
137
+ "validation_track": "known_item_reconstruction",
138
+ "evaluation_protocol_id": protocol["id"],
139
+ "frozen_split_sha256": object_hash(frozen),
140
+ "feature_names": FEATURES,
141
+ "cell_features": dict(zip([*CELLS, "unknown"], DESIGN.tolist())),
142
+ "items": models,
143
+ }, {"fit_elapsed_seconds": perf_counter()-start, "development": development}
144
+
145
+
146
+ def public_answered(obs):
147
+ return {k: v for k, v in obs.items() if k not in ("human_n_eligible", "human_n_missing", "eligible_weight_sum")}
148
+
149
+
150
+ def test(df, items, model, frozen):
151
+ if model["frozen_split_sha256"] != object_hash(frozen):
152
+ raise ValueError("Model is bound to a different split")
153
+ test_df = df[df.split == "test"]
154
+ rows = {}
155
+ for q in items:
156
+ fitted = model["items"][q["question_id"]]
157
+ reference = observed(test_df, q)
158
+ cells = by_cell(test_df, q)
159
+ candidates = {name: evaluate_candidate(fitted, cells, q, name) for name in ("uniform", "marginal", "linear")}
160
+ # Suppress the complete cell breakout for an item when it could reveal a rare answered category
161
+ # or an unpublished unknown cell by subtraction from its national total.
162
+ release_cells = cells["unknown"]["human_n_eligible"] == 0 and all(
163
+ min(obs["human_n_selected"]) >= 10
164
+ for key, obs in cells.items() if key != "unknown"
165
+ )
166
+ # These are exact, coarse aggregates of CC0 public microdata. Do not expose small counts from
167
+ # the national distribution; national item nonresponse counts under ten are suppressed.
168
+ if 0 < reference["human_n_missing"] < 10:
169
+ reference["human_n_missing"] = None
170
+ reference["human_n_eligible"] = None
171
+ reference["eligible_weight_sum"] = None
172
+ rows[q["question_id"]] = {
173
+ "observed": reference, "candidates": candidates, "champion": fitted["champion"],
174
+ "test_answerer_mix": [cells[key]["weight_sum"] / reference["weight_sum"] for key in [*CELLS, "unknown"]],
175
+ "subgroup_suppression": None if release_cells else "Joint breakout withheld to protect small category or missingness counts",
176
+ "subgroups": {
177
+ key: {"observed": public_answered(obs), "candidates": {
178
+ name: scores(probabilities(fitted, key, name), obs["probabilities"], q["ordinal_order"])
179
+ for name in ("uniform", "marginal", "linear")
180
+ }}
181
+ for key, obs in cells.items() if release_cells and key != "unknown"
182
+ },
183
+ }
184
+ means = {}
185
+ for name in ("uniform", "marginal", "linear", "champion"):
186
+ entries = [row["candidates"][row["champion"] if name == "champion" else name] for row in rows.values()]
187
+ means[name] = {scope: {key: float(np.mean([v[scope][key] for v in entries if key in v[scope]]))
188
+ for key in set().union(*(v[scope] for v in entries))}
189
+ for scope in ("national", "within_cell")}
190
+ return {"protocol_id": frozen["protocol"]["id"], "track": "known_item_reconstruction",
191
+ "item_equal_means": means, "rows": rows}
external/htops-transfer-v1/reproduction/src/windtunnel_response/encoder.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train an option scorer, then adapt the last pinned MiniLM transformer block."""
2
+ from collections import defaultdict
3
+ from hashlib import sha256
4
+ from pathlib import Path
5
+ import resource
6
+ from time import perf_counter
7
+
8
+ import numpy as np
9
+ import torch
10
+ from safetensors.torch import load_file, save_file
11
+ from torch import nn
12
+ from transformers import AutoModel, AutoTokenizer
13
+
14
+ from .baseline import by_cell, scores
15
+ from .sources import AGES, CELLS, EDUCATION, digest, object_hash, write
16
+
17
+ BASE_FILES = ("config.json", "model.safetensors", "special_tokens_map.json",
18
+ "tokenizer.json", "tokenizer_config.json", "vocab.txt")
19
+
20
+
21
+ class OptionScorer(nn.Module):
22
+ def __init__(self, hidden):
23
+ super().__init__()
24
+ self.population = nn.Embedding(len(CELLS) + 1, 12)
25
+ self.scorer = nn.Sequential(nn.Linear(hidden + 12, 64), nn.GELU(), nn.Linear(64, 1))
26
+
27
+ def forward(self, text):
28
+ # Population interactions are inside the nonlinear option scorer.
29
+ population = self.population.weight[:, None, :].expand(-1, text.shape[0], -1)
30
+ option_text = text[None, :, :].expand(population.shape[0], -1, -1)
31
+ return self.scorer(torch.cat([option_text, population], dim=-1)).squeeze(-1)
32
+
33
+
34
+ def inputs(question):
35
+ ordered = question["options"]
36
+ instrument = " | ".join(filter(None, [question["preceding_context"], question["question_text"], question["stimulus_text"]]))
37
+ prompt = ("2024 CES pre-election survey, US citizen adults, English. "
38
+ f"Format: {question['response_type']}. {instrument} "
39
+ f"Offered answers in order: {' | '.join(o['label'] for o in ordered)}.")
40
+ return [[prompt, option["label"]] for option in ordered]
41
+
42
+
43
+ def encode_tokens(tokenizer, question, maximum):
44
+ pairs = inputs(question)
45
+ result = tokenizer([p[0] for p in pairs], [p[1] for p in pairs], padding=True, truncation=False, return_tensors="pt")
46
+ if result.input_ids.shape[1] > maximum:
47
+ raise ValueError(f"Instrument exceeds {maximum} tokens: {question['question_id']}")
48
+ return result
49
+
50
+
51
+ def pooled(encoder, tokens):
52
+ hidden = encoder(**tokens).last_hidden_state
53
+ mask = tokens.attention_mask[..., None]
54
+ return torch.nn.functional.normalize((hidden * mask).sum(1) / mask.sum(1), dim=-1)
55
+
56
+
57
+ def examples(df, rows):
58
+ result = []
59
+ for q in rows:
60
+ cells = by_cell(df, q)
61
+ masses = [cells[key]["weight_sum"] for key in [*CELLS, "unknown"]]
62
+ proportions = [cells[key]["probabilities"] or [0.] * len(q["options"]) for key in [*CELLS, "unknown"]]
63
+ result.append((q, torch.tensor(proportions, dtype=torch.float32), torch.tensor(np.asarray(masses) / sum(masses), dtype=torch.float32)))
64
+ return result
65
+
66
+
67
+ def loss(logits, distribution, mass):
68
+ return -(mass * (distribution * logits.log_softmax(dim=-1)).sum(-1)).sum()
69
+
70
+
71
+ @torch.no_grad()
72
+ def evaluate(model, embeddings, examples, detailed=False):
73
+ sums = defaultdict(list)
74
+ report = {}
75
+ for q, reference, mass in examples:
76
+ predicted = model(embeddings(q)).softmax(dim=-1)
77
+ p = (mass @ predicted).numpy()
78
+ observed = (mass @ reference).numpy()
79
+ uniform = np.full(len(p), 1 / len(p))
80
+ reference_loss = scores(p, observed, q["ordinal_order"])
81
+ baseline = scores(uniform, observed, q["ordinal_order"])
82
+ row = {"prediction": p.tolist(), "observed": observed.tolist(), "scores": reference_loss, "uniform": baseline}
83
+ if detailed:
84
+ report[q["question_id"]] = row
85
+ sums["cell_cross_entropy"].append(float(-(mass * (reference * predicted.log()).sum(-1)).sum()))
86
+ for key in ("total_variation", "half_multiclass_brier"):
87
+ sums[key].append(reference_loss[key])
88
+ sums[f"uniform_{key}"].append(baseline[key])
89
+ return {"means": {key: float(np.mean(values)) for key, values in sums.items()}, "rows": report}
90
+
91
+
92
+ def optimize(model, embeddings, train, dev, params, count, batch, lr, generator, checkpoint):
93
+ optimizer = torch.optim.AdamW(params, lr=lr)
94
+ best, trace, best_step = float("inf"), [], 0
95
+ for step in range(1, count + 1):
96
+ indices = generator.choice(len(train), size=batch, replace=False)
97
+ optimizer.zero_grad()
98
+ losses = []
99
+ for index in indices:
100
+ question, distribution, mass = train[index]
101
+ losses.append(loss(model(embeddings(question)), distribution, mass))
102
+ objective = torch.stack(losses).mean()
103
+ if not torch.isfinite(objective):
104
+ raise ValueError("Nonfinite training objective")
105
+ objective.backward()
106
+ torch.nn.utils.clip_grad_norm_(params, 1.0)
107
+ optimizer.step()
108
+ if step in (1, count) or step % max(1, count // 8) == 0:
109
+ dev_objective = evaluate(model, embeddings, dev)["means"]["cell_cross_entropy"]
110
+ trace.append({"step": step, "train_minibatch_cross_entropy": float(objective.detach()), "dev_cell_cross_entropy": dev_objective})
111
+ if dev_objective < best:
112
+ best, best_step = dev_objective, step
113
+ checkpoint()
114
+ return {"steps": count, "selected_step": best_step, "trainable_parameters": sum(p.numel() for p in params), "trace": trace}
115
+
116
+
117
+ def block_hash(block):
118
+ h = sha256()
119
+ for name, value in block.state_dict().items():
120
+ h.update(name.encode())
121
+ h.update(value.detach().contiguous().numpy().tobytes())
122
+ return h.hexdigest()
123
+
124
+
125
+ def run(df, items, frozen, config, base_dir, output):
126
+ t0 = perf_counter()
127
+ seed = frozen["protocol"]["seed"]
128
+ torch.set_num_threads(config["threads"])
129
+ torch.manual_seed(seed)
130
+ torch.use_deterministic_algorithms(True)
131
+ generator = np.random.default_rng(seed)
132
+ tokenizer = AutoTokenizer.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False)
133
+ encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval()
134
+ encoder.requires_grad_(False)
135
+ model = OptionScorer(encoder.config.hidden_size)
136
+ block = encoder.encoder.layer[-1]
137
+ initial_block_hash = block_hash(block)
138
+ tokens = {q["question_id"]: encode_tokens(tokenizer, q, config["max_tokens"]) for q in items}
139
+ groups = {s: [q for q in items if q["question_family_id"] in fs] for s, fs in frozen["protocol"]["family_split"].items()}
140
+ train, dev = [examples(df[df.split == split], groups[split]) for split in ("train","dev")]
141
+
142
+ def embed(q):
143
+ return pooled(encoder, tokens[q["question_id"]])
144
+
145
+ with torch.no_grad():
146
+ cache = {q["question_id"]: embed(q) for q in groups["train"] + groups["dev"]}
147
+
148
+ def cached(q):
149
+ return cache[q["question_id"]]
150
+
151
+ output = Path(output)
152
+ output.mkdir(parents=True, exist_ok=True)
153
+ probe_file = output / "probe.safetensors"
154
+ adaptation_file = output / "adapter.safetensors"
155
+
156
+ def save_probe():
157
+ save_file(model.state_dict(), probe_file)
158
+
159
+ probe = optimize(model, cached, train, dev, list(model.parameters()), config["probe_steps"],
160
+ config["batch_items"], config["probe_lr"], generator, save_probe)
161
+ model.load_state_dict(load_file(probe_file))
162
+ block.requires_grad_(True)
163
+
164
+ def save_adapter():
165
+ save_file({**{f"head.{k}": v for k,v in model.state_dict().items()},
166
+ **{f"last_block.{k}": v for k,v in block.state_dict().items()}}, adaptation_file)
167
+
168
+ adapted = optimize(model, embed, train, dev, list(model.parameters()) + list(block.parameters()),
169
+ config["adapt_steps"], config["batch_items"], config["adapt_lr"], generator, save_adapter)
170
+ checkpoint = load_file(adaptation_file)
171
+ adapted_block = {k.removeprefix("last_block."): v for k,v in checkpoint.items() if k.startswith("last_block.")}
172
+ block.load_state_dict(adapted_block)
173
+ selected_block_hash = block_hash(block)
174
+ if initial_block_hash == selected_block_hash:
175
+ raise ValueError("Selected encoder checkpoint did not change the final block")
176
+ receipt = {
177
+ "config": config,
178
+ "base_files_sha256": {name: digest(Path(base_dir) / name) for name in BASE_FILES},
179
+ "protocol_sha256": object_hash(frozen),
180
+ "probe": {**probe, "sha256": digest(probe_file)},
181
+ "encoder_finetuned": {**adapted, "sha256": digest(adaptation_file), "initial_block_sha256": initial_block_hash,
182
+ "selected_block_sha256": selected_block_hash},
183
+ "final_test_opened_after_checkpoint_selection": True
184
+ }
185
+ write(output / "training.json", receipt)
186
+ unseen = examples(df[df.split == "test"], groups["test"])
187
+ model.load_state_dict({k.removeprefix("head."): v for k,v in checkpoint.items() if k.startswith("head.")})
188
+ adapted_score = evaluate(model, embed, unseen, detailed=True)
189
+ model.load_state_dict(load_file(probe_file))
190
+ encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval()
191
+ probe_score = evaluate(model, embed, unseen, detailed=True)
192
+ receipt.update({"elapsed_seconds": perf_counter() - t0, "linux_peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss})
193
+ write(output / "training.json", receipt)
194
+ policy = frozen["protocol"]["unseen_family"]
195
+ passed = len(groups["test"]) >= policy["minimum_test_families_for_promotion"]
196
+ passed = passed and adapted_score["means"]["total_variation"] <= policy["maximum_mean_tv_for_promotion"]
197
+ passed = passed and (adapted_score["means"]["uniform_half_multiclass_brier"] - adapted_score["means"]["half_multiclass_brier"]
198
+ >= policy["minimum_half_brier_improvement_for_promotion"])
199
+ write(output / "evaluation.json", {"track": "unseen_family_and_person", "family_counts": frozen["unseen_families_by_split"],
200
+ "promotion_passed": passed, "frozen_encoder_probe": probe_score,
201
+ "encoder_finetuned": adapted_score})
202
+ return receipt
203
+
204
+
205
+ def predict_checkpoint(base_dir, checkpoint_path, question, cells, max_tokens=256):
206
+ """Reproduce option-identified cell predictions from a published adapter."""
207
+ torch.set_num_threads(min(3, torch.get_num_threads()))
208
+ encoder = AutoModel.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False).eval()
209
+ tokenizer = AutoTokenizer.from_pretrained(base_dir, local_files_only=True, trust_remote_code=False)
210
+ scorer = OptionScorer(encoder.config.hidden_size).eval()
211
+ checkpoint = load_file(checkpoint_path)
212
+ scorer.load_state_dict({k.removeprefix("head."): v for k,v in checkpoint.items() if k.startswith("head.")})
213
+ encoder.encoder.layer[-1].load_state_dict({k.removeprefix("last_block."): v for k,v in checkpoint.items() if k.startswith("last_block.")})
214
+ with torch.no_grad():
215
+ predicted = scorer(pooled(encoder, encode_tokens(tokenizer, question, max_tokens))).softmax(dim=-1)
216
+ options = [o["id"] for o in question["options"]]
217
+ return {cell: dict(zip(options, predicted[[*CELLS, "unknown"].index(cell)].tolist())) for cell in cells}
external/htops-transfer-v1/reproduction/src/windtunnel_response/sources.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Version-pinned official sources and exact pre-election instruments."""
2
+ from datetime import datetime, timezone
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ import shutil
7
+ import urllib.request
8
+ from zipfile import ZipFile
9
+ import xml.etree.ElementTree as ET
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ STATES = frozenset([1,2,4,5,6,8,9,10,11,12,13,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,53,54,55,56])
15
+ AGES = ("18–29", "30–44", "45–64", "65+")
16
+ EDUCATION = ("High school or less", "Some college or associate degree", "Bachelor’s or higher")
17
+ CELLS = [f"a{a}-e{e}" for a in range(len(AGES)) for e in range(len(EDUCATION))]
18
+ ESTIMAND = "Distribution among recorded answers, including offered uncertainty. Blank, skipped and not-asked records are excluded from answer probabilities."
19
+
20
+
21
+ def now():
22
+ return datetime.now(timezone.utc).isoformat()
23
+
24
+
25
+ def digest(path):
26
+ with Path(path).open("rb") as stream:
27
+ return hashlib.file_digest(stream, "sha256").hexdigest()
28
+
29
+
30
+ def read(path):
31
+ return json.loads(Path(path).read_text(encoding="utf-8"))
32
+
33
+
34
+ def write(path, value):
35
+ path = Path(path)
36
+ path.parent.mkdir(parents=True, exist_ok=True)
37
+ temporary = path.with_suffix(path.suffix + ".tmp")
38
+ temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2) + "\n", encoding="utf-8")
39
+ temporary.replace(path)
40
+
41
+
42
+ def object_hash(value):
43
+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
44
+
45
+
46
+ def request(url, timeout=60):
47
+ headers = {"User-Agent": "Wind Tunnel Response Lab/0.1"}
48
+ return urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=timeout)
49
+
50
+
51
+ def download(url, path, sha256):
52
+ path = Path(path)
53
+ if path.exists() and digest(path) == sha256:
54
+ return
55
+ tmp = path.with_suffix(path.suffix + ".part")
56
+ path.parent.mkdir(parents=True, exist_ok=True)
57
+ with request(url) as stream, tmp.open("wb") as output:
58
+ shutil.copyfileobj(stream, output, length=1024 * 1024)
59
+ if digest(tmp) != sha256:
60
+ tmp.unlink()
61
+ raise ValueError(f"Source checksum mismatch: {path.name}")
62
+ tmp.replace(path)
63
+
64
+
65
+ def latest():
66
+ url = "https://dataverse.harvard.edu/api/datasets/:persistentId/?persistentId=doi:10.7910/DVN/X11EP6"
67
+ with request(url, timeout=30) as response:
68
+ return json.load(response)["data"]["latestVersion"]
69
+
70
+
71
+ def fetch(config, raw):
72
+ for name, (identifier, sha256) in config["files"].items():
73
+ download(f"https://dataverse.harvard.edu/api/access/datafile/{identifier}", raw / name, sha256)
74
+
75
+
76
+ def instrument_items(config, path):
77
+ ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
78
+ with ZipFile(path) as package:
79
+ xml = ET.fromstring(package.read("word/document.xml"))
80
+ lines = ["".join(t.text or "" for t in p.iter(ns + "t")) for p in xml.iter(ns + "p")]
81
+ items = []
82
+ for key, (family, guide_counts, ordinal_length) in config["items"].items():
83
+ idx = lines.index(key)
84
+ grid = lines[idx-1] not in (f"Page: implicit_page_{key}",)
85
+ stimulus = ""
86
+ context = ""
87
+ if grid:
88
+ grid_id = key[:-1] + "grid"
89
+ start = lines.index(f"Page: implicit_page_{grid_id}")
90
+ format_offset = next(i for i in range(start, idx) if lines[i] in ("GRID", "DYNAMIC GRID"))
91
+ stem = lines[format_offset+1]
92
+ stimulus = lines[idx+1]
93
+ if key.startswith("CC24_312"):
94
+ context = "We'd now like to ask you some questions about the people who represent you in government."
95
+ option_start = lines.index("COLUMNS", idx) + 1
96
+ location = grid_id
97
+ else:
98
+ stem = lines[idx+2]
99
+ option_start = lines.index("orderas-is", idx) + 1
100
+ location = key
101
+ upcoming = lines[option_start:option_start + 100]
102
+ options = []
103
+ for code in range(1, len(guide_counts)+1):
104
+ index = upcoming.index(str(code))
105
+ if upcoming[index+1] != "○" or not upcoming[index+2]:
106
+ raise ValueError(f"Could not parse offered option {key}/{code}")
107
+ options.append({"id": str(code), "label": upcoming[index+2]})
108
+ instrument = {"question_text": stem, "stimulus_text": stimulus, "preceding_context": context, "options": options, "language": "en"}
109
+ items.append({
110
+ **instrument, "question_id": key, "question_family_id": family, "survey_id": config["id"],
111
+ "wave": "pre-election", "source_variable": key, "source_location": f"CCES24_Common_pre.docx/{location}/{key}",
112
+ "field_dates": config["field_dates"], "eligibility": config["universe"], "routing": "Common pre-election instrument, no item-specific gate",
113
+ "response_type": "ordinal" if ordinal_length == len(options) else "single_choice",
114
+ "ordinal_order": [str(i) for i in range(1, ordinal_length+1)], "response_estimand": ESTIMAND,
115
+ "missing_codes": {"": "blank", "8": "skipped", "9": "not asked"},
116
+ "wording_hash": object_hash([stem, stimulus, context]), "instrument_hash": object_hash(instrument),
117
+ "supported_task_ids": ["known_item_reconstruction"],
118
+ })
119
+ return items
120
+
121
+
122
+ def prepare(config, raw):
123
+ for name, (_, sha) in config["files"].items():
124
+ if digest(raw / name) != sha:
125
+ raise ValueError(f"Unrecognized source bytes: {name}")
126
+ items = instrument_items(config, raw / "ces24-pre.docx")
127
+ keys = [q["question_id"] for q in items]
128
+ fields = ["caseid", "cit1", "commonweight", "inputstate", "birthyr", "educ", *keys]
129
+ df = pd.read_csv(raw / "ces24.csv", usecols=fields, dtype={"caseid": str}, low_memory=False)
130
+ if len(df) != 60_000 or df.caseid.isna().any() or not df.caseid.is_unique:
131
+ raise ValueError("Unexpected CES source respondent roster")
132
+ reconciliation = {}
133
+ for q in items:
134
+ key = q["question_id"]
135
+ checked = [int((df[key] == int(option["id"])).sum()) for option in q["options"]]
136
+ expected = config["items"][key][1]
137
+ unexpected = sorted(set(df[key].dropna()) - set(range(1, len(expected) + 1)) - {8, 9})
138
+ # Code 8 and 9 are reserved but no not-asked records may appear in this unrouted release.
139
+ if checked != expected or unexpected or (df[key] == 9).any():
140
+ raise ValueError(f"Guide/codebook reconciliation failed: {key}; {checked}, {unexpected}")
141
+ reconciliation[key] = {"guide_counts": expected, "csv_counts": checked}
142
+ age = 2024 - df.birthyr
143
+ target = (df.cit1 == 1) & df.inputstate.isin(STATES) & (age >= 18) & (df.commonweight > 0) & np.isfinite(df.commonweight)
144
+ df = df.loc[target].copy()
145
+ df["age_bin"] = np.searchsorted([30,45,65], age.loc[target], side="right")
146
+ ed = df.educ.map({1:0,2:0,3:1,4:1,5:2,6:2})
147
+ df["cell"] = np.where(ed.notna(), df.age_bin * len(EDUCATION) + ed.fillna(0), -1).astype(int)
148
+ return items, df, reconciliation
149
+
150
+
151
+ def freeze(df, items, protocol):
152
+ seed = protocol["seed"]
153
+ fractions = protocol["respondent_split"]
154
+ if len(fractions) != 3 or not np.isclose(sum(fractions), 1) or min(fractions) <= 0:
155
+ raise ValueError("Invalid respondent split")
156
+ assignments = {
157
+ key: ["train","dev","test"][np.searchsorted(np.cumsum(fractions)[:2],
158
+ int.from_bytes(hashlib.sha256(f"{seed}/{key}".encode()).digest()[:8], "big") / 2**64, side="right")]
159
+ for key in df.caseid
160
+ }
161
+ families = protocol["family_split"]
162
+ assigned = [f for fs in families.values() for f in fs]
163
+ if len(set(assigned)) != len(assigned) or set(assigned) != {q["question_family_id"] for q in items}:
164
+ raise ValueError("Families must form a disjoint partition")
165
+ df["split"] = df.caseid.map(assignments)
166
+ return {
167
+ "protocol": protocol,
168
+ "assignment_sha256": object_hash(assignments),
169
+ "registry_sha256": object_hash(items),
170
+ "respondents_by_split": {str(k): int(v) for k, v in df.split.value_counts().items()},
171
+ "known_item_questions": len(items),
172
+ "known_item_families": len(assigned),
173
+ "unseen_questions_by_split": {s: sum(q["question_family_id"] in fs for q in items) for s,fs in families.items()},
174
+ "unseen_families_by_split": {s: len(fs) for s,fs in families.items()},
175
+ }