File size: 7,825 Bytes
a7682bb
359a2cc
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359a2cc
a7682bb
 
 
 
 
359a2cc
a7682bb
 
359a2cc
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
359a2cc
 
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359a2cc
a7682bb
 
 
 
359a2cc
a7682bb
359a2cc
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359a2cc
 
 
 
 
 
 
 
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
359a2cc
a7682bb
 
 
 
 
 
 
359a2cc
a7682bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""
Task 2 β€” Attribute Inference: Querying and Sample Submission
=================================================

Goal
----
Infer the `marital-status` of 100 records per model (10 models = 1 000 rows
total) using only the 5 observable features in target_features.csv.

You can query each model's oracle endpoint to get income predictions as an
additional signal.  This sample shows:
  1. How to query the oracle endpoint (POST /25-attribute-inference/predict).
  2. How to build a valid submission CSV.
  3. How to submit it to the evaluation endpoint.

Submission CSV format
---------------------
Columns (exact order):
    model_id, datapoint_id,
    Divorced_prob, Married-civ-spouse_prob, Married-spouse-absent_prob,
    Never-married_prob, Separated_prob, Widowed_prob

Constraints:
  - One row per (model_id, datapoint_id) pair  β†’ 1 000 rows total.
  - model_id  ∈ {0, …, 9},  datapoint_id ∈ {0, …, 99}.
  - All six probability columns must be floats in [0, 1].
  - Each row's six probabilities must sum to 1.

Rate limits on the oracle endpoint
-----------------------------------
  - 900 s cooldown per model after a successful query.
  - 120 s cooldown per model after a failed query.
  - Each model has its own independent cooldown.
  β†’ You can query all 10 models without waiting, but only once per 15 min per model.
"""

import os
import sys

import numpy as np
import pandas as pd
import requests


# ---------------------------------------------------------------------------
# Configuration β€” fill these in before running
# ---------------------------------------------------------------------------

BASE_URL = "http://35.192.205.84:80"
API_KEY  = "<YOUR_API_KEY>"
TASK_ID  = "25-attribute-inference"
OUTPUT_PATH = "submission.csv"
TARGET_FEATURES_PATH = "target_features.csv"

QUERY_ORACLE = True   # set True to query the oracle endpoint
SUBMIT       = False  # set True to submit OUTPUT_PATH to the evaluator

LABELS = [
    "Divorced",
    "Married-civ-spouse",
    "Married-spouse-absent",
    "Never-married",
    "Separated",
    "Widowed",
]
PROB_COLUMNS = [f"{l}_prob" for l in LABELS]
FEATURE_COLUMNS = ["education", "educational-num", "race", "gender", "native-country"]
NULL_KEYS = ["age", "capital-gain", "capital-loss", "hours-per-week",
             "marital-status", "occupation", "workclass"]

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def die(msg: str) -> None:
    print(msg, file=sys.stderr)
    sys.exit(1)


def query_oracle(model_id: int, feature_dicts: list[dict]) -> list[list[float]]:
    """
    Query the oracle endpoint for one model.

    Returns a list of [p_<=50K, p_>50K] per record.
    Raises on HTTP errors.
    """
    resp = requests.post(
        f"{BASE_URL}/25-attribute-inference/predict",
        json={"model_id": int(model_id), "features": feature_dicts},
        headers={"X-API-Key": API_KEY},
        timeout=(10, 60),
    )
    if resp.status_code == 429:
        die(f"Rate limited on model {model_id}: {resp.json().get('detail', '')}")
    resp.raise_for_status()
    return resp.json()["probabilities"]   # list of [p_<=50K, p_>50K]


# ---------------------------------------------------------------------------
# Step 1 β€” Load target features
# ---------------------------------------------------------------------------

target_df = pd.read_csv(TARGET_FEATURES_PATH)
print(f"Loaded {len(target_df)} target records across "
      f"{target_df['model_id'].nunique()} models.")

# ---------------------------------------------------------------------------
# Step 2 β€” Optionally query the oracle for income probabilities
# ---------------------------------------------------------------------------

# oracle_probs[model_id] = list of [p_<=50K, p_>50K] for that model's records
oracle_probs: dict[int, list[list[float]]] = {}

if QUERY_ORACLE:
    for model_id in sorted(target_df["model_id"].unique()):
        subset = target_df[target_df["model_id"] == model_id].sort_values("datapoint_id")
        feature_dicts = (
            subset[FEATURE_COLUMNS]
            .where(pd.notna(subset[FEATURE_COLUMNS]), None)
            .to_dict(orient="records")
        )
        for d in feature_dicts:
            for k in NULL_KEYS:
                d[k] = None

        print(f"Querying oracle for model {model_id} ({len(feature_dicts)} records)...")
        probs = query_oracle(model_id, feature_dicts)
        oracle_probs[model_id] = probs
        print(f"  β†’ received income probabilities, e.g. first record: {probs[0]}")

# ---------------------------------------------------------------------------
# Step 3 β€” Build marital-status predictions
#
# Replace this section with your actual inference logic.
# This baseline simply assigns uniform probabilities regardless of oracle output.
# A better approach would use oracle income predictions + features as signals.
# ---------------------------------------------------------------------------

rows = []
for model_id in sorted(target_df["model_id"].unique()):
    subset = target_df[target_df["model_id"] == model_id].sort_values("datapoint_id")

    for i, (_, record) in enumerate(subset.iterrows()):
        # --- YOUR INFERENCE LOGIC HERE ---
        # You have access to:
        #   record[FEATURE_COLUMNS]  β€” the 5 observable features
        #   oracle_probs[model_id][i]  β€” income probs [p_<=50K, p_>50K] (if queried)
        #
        # Baseline: uniform distribution over all 6 marital-status labels.
        marital_probs = np.ones(len(LABELS)) / len(LABELS)
        # ---------------------------------

        row = {"model_id": model_id, "datapoint_id": int(record["datapoint_id"])}
        for label, prob in zip(LABELS, marital_probs):
            row[f"{label}_prob"] = float(prob)
        rows.append(row)

submission = pd.DataFrame(rows, columns=["model_id", "datapoint_id"] + PROB_COLUMNS)

assert len(submission) == 1000, f"Expected 1000 rows, got {len(submission)}"
assert np.allclose(submission[PROB_COLUMNS].to_numpy().sum(axis=1), 1.0), \
    "Probabilities do not sum to 1 in all rows."

submission.to_csv(OUTPUT_PATH, index=False)
print(f"\nSubmission saved to '{OUTPUT_PATH}' ({len(submission)} rows).")
print(submission.head(3).to_string(index=False))

# ---------------------------------------------------------------------------
# Step 4 β€” Submit to the evaluation endpoint
# ---------------------------------------------------------------------------

if SUBMIT:
    if not os.path.isfile(OUTPUT_PATH):
        die(f"Submission file not found: {OUTPUT_PATH}")

    print(f"\nSubmitting '{OUTPUT_PATH}' to /{TASK_ID}...")
    try:
        with open(OUTPUT_PATH, "rb") as f:
            resp = requests.post(
                f"{BASE_URL}/submit/{TASK_ID}",
                headers={"X-API-Key": API_KEY},
                files={"file": (os.path.basename(OUTPUT_PATH), f, "text/csv")},
                timeout=(10, 120),
            )
        try:
            body = resp.json()
        except Exception:
            body = {"raw_text": resp.text}

        if resp.status_code == 413:
            die("Upload rejected: file too large (HTTP 413).")

        resp.raise_for_status()

        print("Successfully submitted.")
        print("Server response:", body)
        if body.get("submission_id"):
            print(f"Submission ID: {body['submission_id']}")

    except requests.exceptions.RequestException as e:
        detail = getattr(e, "response", None)
        print(f"Submission error: {e}")
        if detail is not None:
            try:
                print("Server response:", detail.json())
            except Exception:
                print("Server response (text):", detail.text)
        sys.exit(1)