Harness context codex item completed
{
"type": "codex_item_completed",
"item": {
"type": "CommandExecution",
"id": "exec-e68e73d0-c21a-4f8f-a773-e1c42fc9227b",
"process_id": "1805",
"command": [
"/bin/sh",
"-lc",
"ls -lh /task/data && sed -n '1,240p' /task/ranking_evaluation.py && sed -n '1,220p' /task/evaluate_public.py && cat /task/requirements.txt"
],
"cwd": "file:///app",
"parsed_cmd": [
{
"type": "list_files",
"cmd": "ls -lh /task/data",
"path": "data"
},
{
"type": "read",
"cmd": "sed -n '1,240p' /task/ranking_evaluation.py",
"name": "ranking_evaluation.py",
"path": "/task/ranking_evaluation.py"
},
{
"type": "read",
"cmd": "sed -n '1,220p' /task/evaluate_public.py",
"name": "evaluate_public.py",
"path": "/task/evaluate_public.py"
},
{
"type": "read",
"cmd": "cat /task/requirements.txt",
"name": "requirements.txt",
"path": "/task/requirements.txt"
}
],
"source": "unified_exec_startup",
"status": "completed",
"stdout": "total 340M\n-r--r--r-- 1 root root 342K Sep 25 00:45 candidate_catalog.parquet\n-r--r--r-- 1 root root 83K Sep 25 00:45 target_users.parquet\n-r--r--r-- 1 root root 7.4M Sep 25 00:46 test_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 test_preference_state.parquet\n-r--r--r-- 1 root root 838K Sep 25 00:45 train_dislikes.parquet\n-r--r--r-- 1 root root 5.2M Sep 25 00:45 train_likes.parquet\n-r--r--r-- 1 root root 305M Sep 25 00:45 train_listens.parquet\n-r--r--r-- 1 root root 153K Sep 25 00:45 train_undislikes.parquet\n-r--r--r-- 1 root root 1.8M Sep 25 00:45 train_unlikes.parquet\n-r--r--r-- 1 root root 36K Sep 25 00:45 val_dislikes.parquet\n-r--r--r-- 1 root root 292K Sep 25 00:45 val_likes.parquet\n-r--r--r-- 1 root root 9.5M Sep 25 00:45 val_listens.parquet\n-r--r--r-- 1 root root 7.7K Sep 25 00:45 val_undislikes.parquet\n-r--r--r-- 1 root root 71K Sep 25 00:45 val_unlikes.parquet\n-r--r--r-- 1 root root 7.3M Sep 25 00:45 validation_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 validation_preference_state.parquet\n\"\"\"Shared public primitives for Yambda discovery-ranking evaluation.\n\nBoth the solver-visible validation evaluator and the private submission judge\nimport this module from the generated task's ``public`` directory. It owns the\nstage-independent contract: reading a ranking, validating its shape, converting\nit to per-user rank order, looking up packed candidate eligibility, and\ncomputing graded NDCG@10.\n\nThe module deliberately contains no event-derived labels, private artifact\npaths, or pass thresholds. Each evaluator supplies its own relevance data and\nper-cutoff eligibility checks around these common operations.\n\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\n\n__all__ = [\n \"CandidateSet\",\n \"QUALITY_K\",\n \"RankingValidationError\",\n \"REQUIRED_COLUMNS\",\n \"TOP_N\",\n \"ndcg_at_k\",\n \"ranked_items\",\n \"read_ranking\",\n \"score_rankings\",\n \"validate_ranking\",\n]\n\nTOP_N = 100\nQUALITY_K = 10\nREQUIRED_COLUMNS = (\"uid\", \"item_id\", \"rank\")\n\n\nclass RankingValidationError(ValueError):\n \"\"\"Report a ranking-schema or structural-contract violation.\"\"\"\n\n\nclass CandidateSet:\n \"\"\"Provide membership lookups over one packed candidate-set archive.\n\n The archive contains aligned ``uids``, ``item_ids``, and\n ``packed_eligible`` arrays. Candidate column ``c`` is represented by bit\n ``c % 8`` of byte ``c // 8`` using little-endian bit order. Arrays are\n copied into memory so they remain valid after the archive is closed.\n \"\"\"\n\n def __init__(self, path: Path):\n \"\"\"Load an eligibility archive and build ID-to-position indexes.\n\n Args:\n path: Path to a ``.npz`` archive with the candidate-set schema.\n \"\"\"\n with np.load(path, allow_pickle=False) as artifact:\n self.uids = artifact[\"uids\"].astype(np.int64, copy=True)\n self.item_ids = artifact[\"item_ids\"].astype(np.int64, copy=True)\n self.packed = artifact[\"packed_eligible\"].astype(np.uint8, copy=True)\n self.uid_row = {int(uid): row for row, uid in enumerate(self.uids)}\n self.item_column = {\n int(item): column for column, item in enumerate(self.item_ids)\n }\n\n def is_eligible(self, uid: int, item_id: int) -> bool:\n \"\"\"Return whether ``item_id`` is eligible for ``uid``.\n\n IDs absent from the target-user or candidate-item arrays are treated as\n ineligible rather than raising an exception.\n\n Args:\n uid: Target user ID to query.\n item_id: Candidate item ID to query.\n\n Returns:\n ``True`` only when the corresponding packed eligibility bit is set.\n \"\"\"\n row = self.uid_row.get(int(uid))\n column = self.item_column.get(int(item_id))\n if row is None or column is None:\n return False\n byte, bit = divmod(column, 8)\n return bool((int(self.packed[row, byte]) >> bit) & 1)\n\n\ndef read_ranking(path: Path) -> pd.DataFrame:\n \"\"\"Read a parquet or CSV ranking into a pandas frame.\n\n Args:\n path: Input path. A ``.parquet`` suffix selects parquet; every other\n suffix is interpreted as CSV.\n\n Returns:\n The ranking frame as loaded by pandas.\n \"\"\"\n return pd.read_parquet(path) if path.suffix == \".parquet\" else pd.read_csv(path)\n\n\ndef validate_ranking(\n frame: pd.DataFrame,\n targets: set[int],\n) -> pd.DataFrame:\n \"\"\"Normalize and validate the stage-independent ranking contract.\n\n Required values must be finite integers. The user set must exactly match\n ``targets``; every user must have 100 rows, distinct items, and each rank\n from 1 through 100 exactly once. Cutoff-specific candidate eligibility is\n intentionally left to the calling evaluator.\n\n Args:\n frame: Raw ranking frame. Extra columns are discarded from an internal\n copy; the caller's frame is not modified.\n targets: Exact set of target user IDs the ranking must cover.\n\n Returns:\n A normalized frame containing only the required ``int64`` columns.\n\n Raises:\n RankingValidationError: If the ranking violates the shared contract.\n \"\"\"\n required = list(REQUIRED_COLUMNS)\n if not all(column in frame for column in required):\n raise RankingValidationError(f\"submission requires columns {required}\")\n\n normalized = frame[required].copy()\n for column in required:\n numeric = pd.to_numeric(normalized[column], errors=\"coerce\")\n values = numeric.to_numpy(dtype=float)\n if numeric.isna().any() or not np.isfinite(values).all():\n raise RankingValidationError(\n f\"submission {column} must be finite numeric values\"\n )\n if not np.equal(numeric, np.floor(numeric)).all():\n raise RankingValidationError(\n f\"submission {column} must contain integers\"\n )\n normalized[column] = numeric.astype(np.int64)\n\n submitted_users = set(map(int, normalized.uid.unique()))\n if submitted_users != targets:\n raise RankingValidationError(\n f\"submission user set mismatch: missing={len(targets - submitted_users)} \"\n f\"extra={len(submitted_users - targets)}\"\n )\n counts = normalized.groupby(\"uid\").size()\n if not (counts == TOP_N).all():\n raise RankingValidationError(\n f\"submission must contain exactly {TOP_N} rows for every target user\"\n )\n if normalized.duplicated([\"uid\", \"item_id\"]).any():\n raise RankingValidationError(\n \"submission contains duplicate (uid, item_id) pairs\"\n )\n valid_ranks = set(range(1, TOP_N + 1))\n ranks_are_valid = normalized.groupby(\"uid\")[\"rank\"].apply(\n lambda values: set(map(int, values)) == valid_ranks\n )\n if not ranks_are_valid.all():\n raise RankingValidationError(\n f\"each user must have every rank from 1 through {TOP_N} exactly once\"\n )\n return normalized\n\n\ndef ranked_items(frame: pd.DataFrame) -> dict[int, list[int]]:\n \"\"\"Convert a validated ranking frame to ordered items keyed by user.\n\n Args:\n frame: Frame that has passed :func:`validate_ranking`.\n\n Returns:\n A ``uid -> item IDs`` mapping ordered by ascending rank.\n \"\"\"\n ordered = frame.sort_values([\"uid\", \"rank\"])\n return {\n int(uid): list(map(int, values))\n for uid, values in ordered.groupby(\"uid\").item_id\n }\n\n\ndef ndcg_at_k(ranked: list[int], gold: dict[int, int], k: int) -> float:\n \"\"\"Compute graded normalized discounted cumulative gain at ``k``.\n\n Relevance gain is ``2**grade - 1`` and the discount at one-based rank\n ``r`` is ``1 / log2(r + 1)``. Items absent from ``gold`` have grade zero.\n\n Args:\n ranked: Item IDs in predicted rank order.\n gold: Mapping from relevant item IDs to integer relevance grades.\n k: Maximum number of predicted positions to score.\n\n Returns:\n For a valid duplicate-free ranking, NDCG in ``[0, 1]``; returns\n ``0.0`` when the ideal gain is zero.\n \"\"\"\n gains = np.asarray([gold.get(item, 0) for item in ranked[:k]], dtype=np.float64)\n discounts = 1.0 / np.log2(np.arange(2, len(gains) + 2))\n dcg = float(np.sum((np.power(2.0, gains) - 1.0) * discounts))\n ideal = np.asarray(sorted(gold.values(), reverse=True)[:k], dtype=np.float64)\n ideal_discounts = 1.0 / np.log2(np.arange(2, len(ideal) + 2))\n idcg = float(np.sum((np.power(2.0, ideal) - 1.0) * ideal_discounts))\n return dcg / idcg if idcg else 0.0\n\n\ndef score_rankings(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Relevant item grades keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n quality = float(\n np.mean(\n [\n ndcg_at_k(ranked[uid], gold, QUALITY_K)\n for uid, gold in graded.items()\n ]\n )\n )\n return {\n \"quality_ndcg@10\": round(quality, 6),\n \"quality_users\": len(graded),\n }\n#!/usr/bin/env python3\n\"\"\"Score a validation-stage ranking against public discovery labels.\n\n``build_task.py`` publishes this module with the solver-visible task files. It\nloads target users, validation eligibility, and validation-window events from\nthe adjacent ``data`` directory, then evaluates one ranking supplied on the\ncommand line. Stage-independent mechanics come from the adjacent public\n``ranking_evaluation.py`` module. The builder installs the same checked-in\nmodule in the private judge, so public and private scoring mechanics cannot\ndrift. A relevant candidate receives grade 3 for an organic like or grade 1 for\nan organic listen with at least 80 percent completion; a like takes precedence\nwhen both events exist.\n\nBefore scoring, the ranking must contain exactly 100 distinct eligible items\nfor every target user, with integer-valued ``uid``, ``item_id``, and ``rank``\ncolumns and ranks 1 through 100 exactly once per user. Extra columns are\nignored. Quality is graded NDCG@10, averaged only over users who have at least\none eligible relevant item in the validation window.\n\nThe evaluator prints a JSON object containing the model path and scores. It\ndoes not apply the task's pass threshold; its purpose is model development and\nselection. The private judge applies the threshold to the final submission.\n\nUsage::\n\n python evaluate_public.py <validation-ranking.parquet|csv>\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nimport sys\nfrom pathlib import Path\n\nimport pandas as pd\n\nfrom ranking_evaluation import (\n CandidateSet,\n RankingValidationError,\n ranked_items,\n read_ranking,\n score_rankings,\n validate_ranking,\n)\n\n\nHERE = Path(__file__).resolve().parent\nDATA = HERE / \"data\"\nLISTEN_STRONG = 80\n\n\ndef validation_truth(\n eligibility: CandidateSet, targets: set[int]\n) -> dict[int, dict[int, int]]:\n \"\"\"Build cutoff-correct graded relevance from public validation events.\n\n Only target-user events for eligible candidates are retained. Organic\n listens completed to at least 80 percent receive grade 1, and organic likes\n receive grade 3. Repeated user-item events are collapsed, and processing\n likes second ensures that grade 3 wins over grade 1.\n\n Args:\n eligibility: Validation-cutoff candidate membership service.\n targets: Complete set of target user IDs.\n\n Returns:\n A nested ``uid -> item_id -> grade`` mapping. Users without an eligible\n relevant event are omitted.\n \"\"\"\n listens = pd.read_parquet(DATA / \"val_listens.parquet\")\n likes = pd.read_parquet(DATA / \"val_likes.parquet\")\n strong = listens[\n listens.uid.isin(targets)\n & (listens.is_organic == 1)\n & (listens.played_ratio_pct >= LISTEN_STRONG)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n organic_likes = likes[\n likes.uid.isin(targets) & (likes.is_organic == 1)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n\n graded: dict[int, dict[int, int]] = {}\n for raw_uid, raw_item in strong.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 1\n for raw_uid, raw_item in organic_likes.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 3\n return graded\n\n\ndef load_submission(\n path: Path, eligibility: CandidateSet, targets: set[int]\n) -> dict[int, list[int]]:\n \"\"\"Load and validate a public validation ranking.\n\n Files ending in ``.parquet`` are read as parquet; every other suffix is\n read as CSV. The required columns must be integer-valued, cover exactly the\n target-user set, contain 100 rows and ranks 1 through 100 per user, avoid\n duplicate user-item pairs, and contain only cutoff-eligible items.\n\n Args:\n path: Ranking file to read.\n eligibility: Validation-cutoff candidate membership service.\n targets: Exact set of users the ranking must cover.\n\n Returns:\n A ``uid -> ranked item IDs`` mapping ordered by ascending rank.\n\n Raises:\n ValueError: If the ranking violates the required schema or invariants.\n \"\"\"\n frame = validate_ranking(read_ranking(path), targets)\n if not all(\n eligibility.is_eligible(uid, item)\n for uid, item in frame[[\"uid\", \"item_id\"]].itertuples(index=False, name=None)\n ):\n raise RankingValidationError(\n \"submission contains an item rejected by eligibility service\"\n )\n return ranked_items(frame)\n\n\ndef score(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with public relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Eligible validation relevance keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n return score_rankings(ranked, graded)\n\n\ndef main() -> None:\n \"\"\"Run the public evaluator CLI and print its JSON score report.\"\"\"\n targets_frame = pd.read_parquet(DATA / \"target_users.parquet\")\n targets = set(targets_frame.uid.astype(int))\n eligibility = CandidateSet(DATA / \"validation_eligible_candidates.npz\")\n graded = validation_truth(eligibility, targets)\n\n if len(sys.argv) != 2:\n raise SystemExit(\n \"usage: evaluate_public.py <validation-ranking.parquet|csv>\"\n )\n path = Path(sys.argv[1])\n ranked = load_submission(path, eligibility, targets)\n print(json.dumps({\"model\": str(path), \"scores\": score(ranked, graded)}, indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n# Exact distribution inventory for the Yambda two-tower task family.\n#\n# This is an input to `uv pip sync`, not a list of minimum requirements. A\n# conforming task environment contains exactly these third-party Python\n# distributions and no others. Python itself is pinned by task.toml and both\n# Harbor image Dockerfiles.\nattrs==26.1.0\nbleach==6.4.0\ncertifi==2026.7.22\nchardet==7.6.0\ncharset-normalizer==3.5.1\nfastjsonschema==2.22.2\nfilelock==3.32.3\nfsspec==2026.7.0\nidna==3.18\nJinja2==3.1.6\njoblib==1.5.3\njsonschema==4.26.0\njsonschema-specifications==2025.9.1\njupyter-core==5.9.1\njupytext==1.19.5\nkaggle==2.2.4\nkagglesdk==0.1.37\nmarkdown-it-py==4.2.0\nMarkupSafe==3.0.3\nmdit-py-plugins==0.6.1\nmdurl==0.1.2\nmpmath==1.3.0\nnbformat==5.11.1\nnetworkx==3.6.1\nnumpy==2.2.6\npackaging==26.3\npandas==2.3.3\npillow==12.3.0\npip==26.0.1\nplatformdirs==4.11.3\nprotobuf==7.35.1\npyarrow==18.1.0\npython-dateutil==2.9.0.post0\npython-dotenv==1.2.3\npython-slugify==8.0.4\npytz==2026.3.post1\nPyYAML==6.0.3\nreferencing==0.37.0\nreportlab==4.2.5\nrequests==2.34.2\nrpds-py==2026.6.3\nscikit-learn==1.7.2\nscipy==1.15.3\nsetuptools==84.0.0\nsix==1.17.0\nsympy==1.14.0\ntext-unidecode==1.3\nthreadpoolctl==3.6.0\ntorch==2.8.0\ntqdm==4.70.0\ntraitlets==5.16.1\ntyping-extensions==4.16.0\ntzdata==2026.3\nurllib3==2.7.0\nwebencodings==0.6.1\n",
"stderr": "",
"aggregated_output": "total 340M\n-r--r--r-- 1 root root 342K Sep 25 00:45 candidate_catalog.parquet\n-r--r--r-- 1 root root 83K Sep 25 00:45 target_users.parquet\n-r--r--r-- 1 root root 7.4M Sep 25 00:46 test_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 test_preference_state.parquet\n-r--r--r-- 1 root root 838K Sep 25 00:45 train_dislikes.parquet\n-r--r--r-- 1 root root 5.2M Sep 25 00:45 train_likes.parquet\n-r--r--r-- 1 root root 305M Sep 25 00:45 train_listens.parquet\n-r--r--r-- 1 root root 153K Sep 25 00:45 train_undislikes.parquet\n-r--r--r-- 1 root root 1.8M Sep 25 00:45 train_unlikes.parquet\n-r--r--r-- 1 root root 36K Sep 25 00:45 val_dislikes.parquet\n-r--r--r-- 1 root root 292K Sep 25 00:45 val_likes.parquet\n-r--r--r-- 1 root root 9.5M Sep 25 00:45 val_listens.parquet\n-r--r--r-- 1 root root 7.7K Sep 25 00:45 val_undislikes.parquet\n-r--r--r-- 1 root root 71K Sep 25 00:45 val_unlikes.parquet\n-r--r--r-- 1 root root 7.3M Sep 25 00:45 validation_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 validation_preference_state.parquet\n\"\"\"Shared public primitives for Yambda discovery-ranking evaluation.\n\nBoth the solver-visible validation evaluator and the private submission judge\nimport this module from the generated task's ``public`` directory. It owns the\nstage-independent contract: reading a ranking, validating its shape, converting\nit to per-user rank order, looking up packed candidate eligibility, and\ncomputing graded NDCG@10.\n\nThe module deliberately contains no event-derived labels, private artifact\npaths, or pass thresholds. Each evaluator supplies its own relevance data and\nper-cutoff eligibility checks around these common operations.\n\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\n\n__all__ = [\n \"CandidateSet\",\n \"QUALITY_K\",\n \"RankingValidationError\",\n \"REQUIRED_COLUMNS\",\n \"TOP_N\",\n \"ndcg_at_k\",\n \"ranked_items\",\n \"read_ranking\",\n \"score_rankings\",\n \"validate_ranking\",\n]\n\nTOP_N = 100\nQUALITY_K = 10\nREQUIRED_COLUMNS = (\"uid\", \"item_id\", \"rank\")\n\n\nclass RankingValidationError(ValueError):\n \"\"\"Report a ranking-schema or structural-contract violation.\"\"\"\n\n\nclass CandidateSet:\n \"\"\"Provide membership lookups over one packed candidate-set archive.\n\n The archive contains aligned ``uids``, ``item_ids``, and\n ``packed_eligible`` arrays. Candidate column ``c`` is represented by bit\n ``c % 8`` of byte ``c // 8`` using little-endian bit order. Arrays are\n copied into memory so they remain valid after the archive is closed.\n \"\"\"\n\n def __init__(self, path: Path):\n \"\"\"Load an eligibility archive and build ID-to-position indexes.\n\n Args:\n path: Path to a ``.npz`` archive with the candidate-set schema.\n \"\"\"\n with np.load(path, allow_pickle=False) as artifact:\n self.uids = artifact[\"uids\"].astype(np.int64, copy=True)\n self.item_ids = artifact[\"item_ids\"].astype(np.int64, copy=True)\n self.packed = artifact[\"packed_eligible\"].astype(np.uint8, copy=True)\n self.uid_row = {int(uid): row for row, uid in enumerate(self.uids)}\n self.item_column = {\n int(item): column for column, item in enumerate(self.item_ids)\n }\n\n def is_eligible(self, uid: int, item_id: int) -> bool:\n \"\"\"Return whether ``item_id`` is eligible for ``uid``.\n\n IDs absent from the target-user or candidate-item arrays are treated as\n ineligible rather than raising an exception.\n\n Args:\n uid: Target user ID to query.\n item_id: Candidate item ID to query.\n\n Returns:\n ``True`` only when the corresponding packed eligibility bit is set.\n \"\"\"\n row = self.uid_row.get(int(uid))\n column = self.item_column.get(int(item_id))\n if row is None or column is None:\n return False\n byte, bit = divmod(column, 8)\n return bool((int(self.packed[row, byte]) >> bit) & 1)\n\n\ndef read_ranking(path: Path) -> pd.DataFrame:\n \"\"\"Read a parquet or CSV ranking into a pandas frame.\n\n Args:\n path: Input path. A ``.parquet`` suffix selects parquet; every other\n suffix is interpreted as CSV.\n\n Returns:\n The ranking frame as loaded by pandas.\n \"\"\"\n return pd.read_parquet(path) if path.suffix == \".parquet\" else pd.read_csv(path)\n\n\ndef validate_ranking(\n frame: pd.DataFrame,\n targets: set[int],\n) -> pd.DataFrame:\n \"\"\"Normalize and validate the stage-independent ranking contract.\n\n Required values must be finite integers. The user set must exactly match\n ``targets``; every user must have 100 rows, distinct items, and each rank\n from 1 through 100 exactly once. Cutoff-specific candidate eligibility is\n intentionally left to the calling evaluator.\n\n Args:\n frame: Raw ranking frame. Extra columns are discarded from an internal\n copy; the caller's frame is not modified.\n targets: Exact set of target user IDs the ranking must cover.\n\n Returns:\n A normalized frame containing only the required ``int64`` columns.\n\n Raises:\n RankingValidationError: If the ranking violates the shared contract.\n \"\"\"\n required = list(REQUIRED_COLUMNS)\n if not all(column in frame for column in required):\n raise RankingValidationError(f\"submission requires columns {required}\")\n\n normalized = frame[required].copy()\n for column in required:\n numeric = pd.to_numeric(normalized[column], errors=\"coerce\")\n values = numeric.to_numpy(dtype=float)\n if numeric.isna().any() or not np.isfinite(values).all():\n raise RankingValidationError(\n f\"submission {column} must be finite numeric values\"\n )\n if not np.equal(numeric, np.floor(numeric)).all():\n raise RankingValidationError(\n f\"submission {column} must contain integers\"\n )\n normalized[column] = numeric.astype(np.int64)\n\n submitted_users = set(map(int, normalized.uid.unique()))\n if submitted_users != targets:\n raise RankingValidationError(\n f\"submission user set mismatch: missing={len(targets - submitted_users)} \"\n f\"extra={len(submitted_users - targets)}\"\n )\n counts = normalized.groupby(\"uid\").size()\n if not (counts == TOP_N).all():\n raise RankingValidationError(\n f\"submission must contain exactly {TOP_N} rows for every target user\"\n )\n if normalized.duplicated([\"uid\", \"item_id\"]).any():\n raise RankingValidationError(\n \"submission contains duplicate (uid, item_id) pairs\"\n )\n valid_ranks = set(range(1, TOP_N + 1))\n ranks_are_valid = normalized.groupby(\"uid\")[\"rank\"].apply(\n lambda values: set(map(int, values)) == valid_ranks\n )\n if not ranks_are_valid.all():\n raise RankingValidationError(\n f\"each user must have every rank from 1 through {TOP_N} exactly once\"\n )\n return normalized\n\n\ndef ranked_items(frame: pd.DataFrame) -> dict[int, list[int]]:\n \"\"\"Convert a validated ranking frame to ordered items keyed by user.\n\n Args:\n frame: Frame that has passed :func:`validate_ranking`.\n\n Returns:\n A ``uid -> item IDs`` mapping ordered by ascending rank.\n \"\"\"\n ordered = frame.sort_values([\"uid\", \"rank\"])\n return {\n int(uid): list(map(int, values))\n for uid, values in ordered.groupby(\"uid\").item_id\n }\n\n\ndef ndcg_at_k(ranked: list[int], gold: dict[int, int], k: int) -> float:\n \"\"\"Compute graded normalized discounted cumulative gain at ``k``.\n\n Relevance gain is ``2**grade - 1`` and the discount at one-based rank\n ``r`` is ``1 / log2(r + 1)``. Items absent from ``gold`` have grade zero.\n\n Args:\n ranked: Item IDs in predicted rank order.\n gold: Mapping from relevant item IDs to integer relevance grades.\n k: Maximum number of predicted positions to score.\n\n Returns:\n For a valid duplicate-free ranking, NDCG in ``[0, 1]``; returns\n ``0.0`` when the ideal gain is zero.\n \"\"\"\n gains = np.asarray([gold.get(item, 0) for item in ranked[:k]], dtype=np.float64)\n discounts = 1.0 / np.log2(np.arange(2, len(gains) + 2))\n dcg = float(np.sum((np.power(2.0, gains) - 1.0) * discounts))\n ideal = np.asarray(sorted(gold.values(), reverse=True)[:k], dtype=np.float64)\n ideal_discounts = 1.0 / np.log2(np.arange(2, len(ideal) + 2))\n idcg = float(np.sum((np.power(2.0, ideal) - 1.0) * ideal_discounts))\n return dcg / idcg if idcg else 0.0\n\n\ndef score_rankings(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Relevant item grades keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n quality = float(\n np.mean(\n [\n ndcg_at_k(ranked[uid], gold, QUALITY_K)\n for uid, gold in graded.items()\n ]\n )\n )\n return {\n \"quality_ndcg@10\": round(quality, 6),\n \"quality_users\": len(graded),\n }\n#!/usr/bin/env python3\n\"\"\"Score a validation-stage ranking against public discovery labels.\n\n``build_task.py`` publishes this module with the solver-visible task files. It\nloads target users, validation eligibility, and validation-window events from\nthe adjacent ``data`` directory, then evaluates one ranking supplied on the\ncommand line. Stage-independent mechanics come from the adjacent public\n``ranking_evaluation.py`` module. The builder installs the same checked-in\nmodule in the private judge, so public and private scoring mechanics cannot\ndrift. A relevant candidate receives grade 3 for an organic like or grade 1 for\nan organic listen with at least 80 percent completion; a like takes precedence\nwhen both events exist.\n\nBefore scoring, the ranking must contain exactly 100 distinct eligible items\nfor every target user, with integer-valued ``uid``, ``item_id``, and ``rank``\ncolumns and ranks 1 through 100 exactly once per user. Extra columns are\nignored. Quality is graded NDCG@10, averaged only over users who have at least\none eligible relevant item in the validation window.\n\nThe evaluator prints a JSON object containing the model path and scores. It\ndoes not apply the task's pass threshold; its purpose is model development and\nselection. The private judge applies the threshold to the final submission.\n\nUsage::\n\n python evaluate_public.py <validation-ranking.parquet|csv>\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nimport sys\nfrom pathlib import Path\n\nimport pandas as pd\n\nfrom ranking_evaluation import (\n CandidateSet,\n RankingValidationError,\n ranked_items,\n read_ranking,\n score_rankings,\n validate_ranking,\n)\n\n\nHERE = Path(__file__).resolve().parent\nDATA = HERE / \"data\"\nLISTEN_STRONG = 80\n\n\ndef validation_truth(\n eligibility: CandidateSet, targets: set[int]\n) -> dict[int, dict[int, int]]:\n \"\"\"Build cutoff-correct graded relevance from public validation events.\n\n Only target-user events for eligible candidates are retained. Organic\n listens completed to at least 80 percent receive grade 1, and organic likes\n receive grade 3. Repeated user-item events are collapsed, and processing\n likes second ensures that grade 3 wins over grade 1.\n\n Args:\n eligibility: Validation-cutoff candidate membership service.\n targets: Complete set of target user IDs.\n\n Returns:\n A nested ``uid -> item_id -> grade`` mapping. Users without an eligible\n relevant event are omitted.\n \"\"\"\n listens = pd.read_parquet(DATA / \"val_listens.parquet\")\n likes = pd.read_parquet(DATA / \"val_likes.parquet\")\n strong = listens[\n listens.uid.isin(targets)\n & (listens.is_organic == 1)\n & (listens.played_ratio_pct >= LISTEN_STRONG)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n organic_likes = likes[\n likes.uid.isin(targets) & (likes.is_organic == 1)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n\n graded: dict[int, dict[int, int]] = {}\n for raw_uid, raw_item in strong.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 1\n for raw_uid, raw_item in organic_likes.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 3\n return graded\n\n\ndef load_submission(\n path: Path, eligibility: CandidateSet, targets: set[int]\n) -> dict[int, list[int]]:\n \"\"\"Load and validate a public validation ranking.\n\n Files ending in ``.parquet`` are read as parquet; every other suffix is\n read as CSV. The required columns must be integer-valued, cover exactly the\n target-user set, contain 100 rows and ranks 1 through 100 per user, avoid\n duplicate user-item pairs, and contain only cutoff-eligible items.\n\n Args:\n path: Ranking file to read.\n eligibility: Validation-cutoff candidate membership service.\n targets: Exact set of users the ranking must cover.\n\n Returns:\n A ``uid -> ranked item IDs`` mapping ordered by ascending rank.\n\n Raises:\n ValueError: If the ranking violates the required schema or invariants.\n \"\"\"\n frame = validate_ranking(read_ranking(path), targets)\n if not all(\n eligibility.is_eligible(uid, item)\n for uid, item in frame[[\"uid\", \"item_id\"]].itertuples(index=False, name=None)\n ):\n raise RankingValidationError(\n \"submission contains an item rejected by eligibility service\"\n )\n return ranked_items(frame)\n\n\ndef score(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with public relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Eligible validation relevance keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n return score_rankings(ranked, graded)\n\n\ndef main() -> None:\n \"\"\"Run the public evaluator CLI and print its JSON score report.\"\"\"\n targets_frame = pd.read_parquet(DATA / \"target_users.parquet\")\n targets = set(targets_frame.uid.astype(int))\n eligibility = CandidateSet(DATA / \"validation_eligible_candidates.npz\")\n graded = validation_truth(eligibility, targets)\n\n if len(sys.argv) != 2:\n raise SystemExit(\n \"usage: evaluate_public.py <validation-ranking.parquet|csv>\"\n )\n path = Path(sys.argv[1])\n ranked = load_submission(path, eligibility, targets)\n print(json.dumps({\"model\": str(path), \"scores\": score(ranked, graded)}, indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n# Exact distribution inventory for the Yambda two-tower task family.\n#\n# This is an input to `uv pip sync`, not a list of minimum requirements. A\n# conforming task environment contains exactly these third-party Python\n# distributions and no others. Python itself is pinned by task.toml and both\n# Harbor image Dockerfiles.\nattrs==26.1.0\nbleach==6.4.0\ncertifi==2026.7.22\nchardet==7.6.0\ncharset-normalizer==3.5.1\nfastjsonschema==2.22.2\nfilelock==3.32.3\nfsspec==2026.7.0\nidna==3.18\nJinja2==3.1.6\njoblib==1.5.3\njsonschema==4.26.0\njsonschema-specifications==2025.9.1\njupyter-core==5.9.1\njupytext==1.19.5\nkaggle==2.2.4\nkagglesdk==0.1.37\nmarkdown-it-py==4.2.0\nMarkupSafe==3.0.3\nmdit-py-plugins==0.6.1\nmdurl==0.1.2\nmpmath==1.3.0\nnbformat==5.11.1\nnetworkx==3.6.1\nnumpy==2.2.6\npackaging==26.3\npandas==2.3.3\npillow==12.3.0\npip==26.0.1\nplatformdirs==4.11.3\nprotobuf==7.35.1\npyarrow==18.1.0\npython-dateutil==2.9.0.post0\npython-dotenv==1.2.3\npython-slugify==8.0.4\npytz==2026.3.post1\nPyYAML==6.0.3\nreferencing==0.37.0\nreportlab==4.2.5\nrequests==2.34.2\nrpds-py==2026.6.3\nscikit-learn==1.7.2\nscipy==1.15.3\nsetuptools==84.0.0\nsix==1.17.0\nsympy==1.14.0\ntext-unidecode==1.3\nthreadpoolctl==3.6.0\ntorch==2.8.0\ntqdm==4.70.0\ntraitlets==5.16.1\ntyping-extensions==4.16.0\ntzdata==2026.3\nurllib3==2.7.0\nwebencodings==0.6.1\n",
"exit_code": 0,
"duration": {
"secs": 0,
"nanos": 6320
},
"formatted_output": "total 340M\n-r--r--r-- 1 root root 342K Sep 25 00:45 candidate_catalog.parquet\n-r--r--r-- 1 root root 83K Sep 25 00:45 target_users.parquet\n-r--r--r-- 1 root root 7.4M Sep 25 00:46 test_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 test_preference_state.parquet\n-r--r--r-- 1 root root 838K Sep 25 00:45 train_dislikes.parquet\n-r--r--r-- 1 root root 5.2M Sep 25 00:45 train_likes.parquet\n-r--r--r-- 1 root root 305M Sep 25 00:45 train_listens.parquet\n-r--r--r-- 1 root root 153K Sep 25 00:45 train_undislikes.parquet\n-r--r--r-- 1 root root 1.8M Sep 25 00:45 train_unlikes.parquet\n-r--r--r-- 1 root root 36K Sep 25 00:45 val_dislikes.parquet\n-r--r--r-- 1 root root 292K Sep 25 00:45 val_likes.parquet\n-r--r--r-- 1 root root 9.5M Sep 25 00:45 val_listens.parquet\n-r--r--r-- 1 root root 7.7K Sep 25 00:45 val_undislikes.parquet\n-r--r--r-- 1 root root 71K Sep 25 00:45 val_unlikes.parquet\n-r--r--r-- 1 root root 7.3M Sep 25 00:45 validation_eligible_candidates.npz\n-r--r--r-- 1 root root 1.1M Sep 25 00:46 validation_preference_state.parquet\n\"\"\"Shared public primitives for Yambda discovery-ranking evaluation.\n\nBoth the solver-visible validation evaluator and the private submission judge\nimport this module from the generated task's ``public`` directory. It owns the\nstage-independent contract: reading a ranking, validating its shape, converting\nit to per-user rank order, looking up packed candidate eligibility, and\ncomputing graded NDCG@10.\n\nThe module deliberately contains no event-derived labels, private artifact\npaths, or pass thresholds. Each evaluator supplies its own relevance data and\nper-cutoff eligibility checks around these common operations.\n\"\"\"\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\n\n__all__ = [\n \"CandidateSet\",\n \"QUALITY_K\",\n \"RankingValidationError\",\n \"REQUIRED_COLUMNS\",\n \"TOP_N\",\n \"ndcg_at_k\",\n \"ranked_items\",\n \"read_ranking\",\n \"score_rankings\",\n \"validate_ranking\",\n]\n\nTOP_N = 100\nQUALITY_K = 10\nREQUIRED_COLUMNS = (\"uid\", \"item_id\", \"rank\")\n\n\nclass RankingValidationError(ValueError):\n \"\"\"Report a ranking-schema or structural-contract violation.\"\"\"\n\n\nclass CandidateSet:\n \"\"\"Provide membership lookups over one packed candidate-set archive.\n\n The archive contains aligned ``uids``, ``item_ids``, and\n ``packed_eligible`` arrays. Candidate column ``c`` is represented by bit\n ``c % 8`` of byte ``c // 8`` using little-endian bit order. Arrays are\n copied into memory so they remain valid after the archive is closed.\n \"\"\"\n\n def __init__(self, path: Path):\n \"\"\"Load an eligibility archive and build ID-to-position indexes.\n\n Args:\n path: Path to a ``.npz`` archive with the candidate-set schema.\n \"\"\"\n with np.load(path, allow_pickle=False) as artifact:\n self.uids = artifact[\"uids\"].astype(np.int64, copy=True)\n self.item_ids = artifact[\"item_ids\"].astype(np.int64, copy=True)\n self.packed = artifact[\"packed_eligible\"].astype(np.uint8, copy=True)\n self.uid_row = {int(uid): row for row, uid in enumerate(self.uids)}\n self.item_column = {\n int(item): column for column, item in enumerate(self.item_ids)\n }\n\n def is_eligible(self, uid: int, item_id: int) -> bool:\n \"\"\"Return whether ``item_id`` is eligible for ``uid``.\n\n IDs absent from the target-user or candidate-item arrays are treated as\n ineligible rather than raising an exception.\n\n Args:\n uid: Target user ID to query.\n item_id: Candidate item ID to query.\n\n Returns:\n ``True`` only when the corresponding packed eligibility bit is set.\n \"\"\"\n row = self.uid_row.get(int(uid))\n column = self.item_column.get(int(item_id))\n if row is None or column is None:\n return False\n byte, bit = divmod(column, 8)\n return bool((int(self.packed[row, byte]) >> bit) & 1)\n\n\ndef read_ranking(path: Path) -> pd.DataFrame:\n \"\"\"Read a parquet or CSV ranking into a pandas frame.\n\n Args:\n path: Input path. A ``.parquet`` suffix selects parquet; every other\n suffix is interpreted as CSV.\n\n Returns:\n The ranking frame as loaded by pandas.\n \"\"\"\n return pd.read_parquet(path) if path.suffix == \".parquet\" else pd.read_csv(path)\n\n\ndef validate_ranking(\n frame: pd.DataFrame,\n targets: set[int],\n) -> pd.DataFrame:\n \"\"\"Normalize and validate the stage-independent ranking contract.\n\n Required values must be finite integers. The user set must exactly match\n ``targets``; every user must have 100 rows, distinct items, and each rank\n from 1 through 100 exactly once. Cutoff-specific candidate eligibility is\n intentionally left to the calling evaluator.\n\n Args:\n frame: Raw ranking frame. Extra columns are discarded from an internal\n copy; the caller's frame is not modified.\n targets: Exact set of target user IDs the ranking must cover.\n\n Returns:\n A normalized frame containing only the required ``int64`` columns.\n\n Raises:\n RankingValidationError: If the ranking violates the shared contract.\n \"\"\"\n required = list(REQUIRED_COLUMNS)\n if not all(column in frame for column in required):\n raise RankingValidationError(f\"submission requires columns {required}\")\n\n normalized = frame[required].copy()\n for column in required:\n numeric = pd.to_numeric(normalized[column], errors=\"coerce\")\n values = numeric.to_numpy(dtype=float)\n if numeric.isna().any() or not np.isfinite(values).all():\n raise RankingValidationError(\n f\"submission {column} must be finite numeric values\"\n )\n if not np.equal(numeric, np.floor(numeric)).all():\n raise RankingValidationError(\n f\"submission {column} must contain integers\"\n )\n normalized[column] = numeric.astype(np.int64)\n\n submitted_users = set(map(int, normalized.uid.unique()))\n if submitted_users != targets:\n raise RankingValidationError(\n f\"submission user set mismatch: missing={len(targets - submitted_users)} \"\n f\"extra={len(submitted_users - targets)}\"\n )\n counts = normalized.groupby(\"uid\").size()\n if not (counts == TOP_N).all():\n raise RankingValidationError(\n f\"submission must contain exactly {TOP_N} rows for every target user\"\n )\n if normalized.duplicated([\"uid\", \"item_id\"]).any():\n raise RankingValidationError(\n \"submission contains duplicate (uid, item_id) pairs\"\n )\n valid_ranks = set(range(1, TOP_N + 1))\n ranks_are_valid = normalized.groupby(\"uid\")[\"rank\"].apply(\n lambda values: set(map(int, values)) == valid_ranks\n )\n if not ranks_are_valid.all():\n raise RankingValidationError(\n f\"each user must have every rank from 1 through {TOP_N} exactly once\"\n )\n return normalized\n\n\ndef ranked_items(frame: pd.DataFrame) -> dict[int, list[int]]:\n \"\"\"Convert a validated ranking frame to ordered items keyed by user.\n\n Args:\n frame: Frame that has passed :func:`validate_ranking`.\n\n Returns:\n A ``uid -> item IDs`` mapping ordered by ascending rank.\n \"\"\"\n ordered = frame.sort_values([\"uid\", \"rank\"])\n return {\n int(uid): list(map(int, values))\n for uid, values in ordered.groupby(\"uid\").item_id\n }\n\n\ndef ndcg_at_k(ranked: list[int], gold: dict[int, int], k: int) -> float:\n \"\"\"Compute graded normalized discounted cumulative gain at ``k``.\n\n Relevance gain is ``2**grade - 1`` and the discount at one-based rank\n ``r`` is ``1 / log2(r + 1)``. Items absent from ``gold`` have grade zero.\n\n Args:\n ranked: Item IDs in predicted rank order.\n gold: Mapping from relevant item IDs to integer relevance grades.\n k: Maximum number of predicted positions to score.\n\n Returns:\n For a valid duplicate-free ranking, NDCG in ``[0, 1]``; returns\n ``0.0`` when the ideal gain is zero.\n \"\"\"\n gains = np.asarray([gold.get(item, 0) for item in ranked[:k]], dtype=np.float64)\n discounts = 1.0 / np.log2(np.arange(2, len(gains) + 2))\n dcg = float(np.sum((np.power(2.0, gains) - 1.0) * discounts))\n ideal = np.asarray(sorted(gold.values(), reverse=True)[:k], dtype=np.float64)\n ideal_discounts = 1.0 / np.log2(np.arange(2, len(ideal) + 2))\n idcg = float(np.sum((np.power(2.0, ideal) - 1.0) * ideal_discounts))\n return dcg / idcg if idcg else 0.0\n\n\ndef score_rankings(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Relevant item grades keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n quality = float(\n np.mean(\n [\n ndcg_at_k(ranked[uid], gold, QUALITY_K)\n for uid, gold in graded.items()\n ]\n )\n )\n return {\n \"quality_ndcg@10\": round(quality, 6),\n \"quality_users\": len(graded),\n }\n#!/usr/bin/env python3\n\"\"\"Score a validation-stage ranking against public discovery labels.\n\n``build_task.py`` publishes this module with the solver-visible task files. It\nloads target users, validation eligibility, and validation-window events from\nthe adjacent ``data`` directory, then evaluates one ranking supplied on the\ncommand line. Stage-independent mechanics come from the adjacent public\n``ranking_evaluation.py`` module. The builder installs the same checked-in\nmodule in the private judge, so public and private scoring mechanics cannot\ndrift. A relevant candidate receives grade 3 for an organic like or grade 1 for\nan organic listen with at least 80 percent completion; a like takes precedence\nwhen both events exist.\n\nBefore scoring, the ranking must contain exactly 100 distinct eligible items\nfor every target user, with integer-valued ``uid``, ``item_id``, and ``rank``\ncolumns and ranks 1 through 100 exactly once per user. Extra columns are\nignored. Quality is graded NDCG@10, averaged only over users who have at least\none eligible relevant item in the validation window.\n\nThe evaluator prints a JSON object containing the model path and scores. It\ndoes not apply the task's pass threshold; its purpose is model development and\nselection. The private judge applies the threshold to the final submission.\n\nUsage::\n\n python evaluate_public.py <validation-ranking.parquet|csv>\n\"\"\"\nfrom __future__ import annotations\n\nimport json\nimport sys\nfrom pathlib import Path\n\nimport pandas as pd\n\nfrom ranking_evaluation import (\n CandidateSet,\n RankingValidationError,\n ranked_items,\n read_ranking,\n score_rankings,\n validate_ranking,\n)\n\n\nHERE = Path(__file__).resolve().parent\nDATA = HERE / \"data\"\nLISTEN_STRONG = 80\n\n\ndef validation_truth(\n eligibility: CandidateSet, targets: set[int]\n) -> dict[int, dict[int, int]]:\n \"\"\"Build cutoff-correct graded relevance from public validation events.\n\n Only target-user events for eligible candidates are retained. Organic\n listens completed to at least 80 percent receive grade 1, and organic likes\n receive grade 3. Repeated user-item events are collapsed, and processing\n likes second ensures that grade 3 wins over grade 1.\n\n Args:\n eligibility: Validation-cutoff candidate membership service.\n targets: Complete set of target user IDs.\n\n Returns:\n A nested ``uid -> item_id -> grade`` mapping. Users without an eligible\n relevant event are omitted.\n \"\"\"\n listens = pd.read_parquet(DATA / \"val_listens.parquet\")\n likes = pd.read_parquet(DATA / \"val_likes.parquet\")\n strong = listens[\n listens.uid.isin(targets)\n & (listens.is_organic == 1)\n & (listens.played_ratio_pct >= LISTEN_STRONG)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n organic_likes = likes[\n likes.uid.isin(targets) & (likes.is_organic == 1)\n ][[\"uid\", \"item_id\"]].drop_duplicates()\n\n graded: dict[int, dict[int, int]] = {}\n for raw_uid, raw_item in strong.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 1\n for raw_uid, raw_item in organic_likes.itertuples(index=False, name=None):\n uid, item = int(raw_uid), int(raw_item)\n if eligibility.is_eligible(uid, item):\n graded.setdefault(uid, {})[item] = 3\n return graded\n\n\ndef load_submission(\n path: Path, eligibility: CandidateSet, targets: set[int]\n) -> dict[int, list[int]]:\n \"\"\"Load and validate a public validation ranking.\n\n Files ending in ``.parquet`` are read as parquet; every other suffix is\n read as CSV. The required columns must be integer-valued, cover exactly the\n target-user set, contain 100 rows and ranks 1 through 100 per user, avoid\n duplicate user-item pairs, and contain only cutoff-eligible items.\n\n Args:\n path: Ranking file to read.\n eligibility: Validation-cutoff candidate membership service.\n targets: Exact set of users the ranking must cover.\n\n Returns:\n A ``uid -> ranked item IDs`` mapping ordered by ascending rank.\n\n Raises:\n ValueError: If the ranking violates the required schema or invariants.\n \"\"\"\n frame = validate_ranking(read_ranking(path), targets)\n if not all(\n eligibility.is_eligible(uid, item)\n for uid, item in frame[[\"uid\", \"item_id\"]].itertuples(index=False, name=None)\n ):\n raise RankingValidationError(\n \"submission contains an item rejected by eligibility service\"\n )\n return ranked_items(frame)\n\n\ndef score(\n ranked: dict[int, list[int]],\n graded: dict[int, dict[int, int]],\n) -> dict[str, float | int]:\n \"\"\"Aggregate per-user NDCG@10 over users with public relevance labels.\n\n Args:\n ranked: Ranked item IDs for every target user.\n graded: Eligible validation relevance keyed by user and item.\n\n Returns:\n The six-decimal ``quality_ndcg@10`` value and number of scored users.\n \"\"\"\n return score_rankings(ranked, graded)\n\n\ndef main() -> None:\n \"\"\"Run the public evaluator CLI and print its JSON score report.\"\"\"\n targets_frame = pd.read_parquet(DATA / \"target_users.parquet\")\n targets = set(targets_frame.uid.astype(int))\n eligibility = CandidateSet(DATA / \"validation_eligible_candidates.npz\")\n graded = validation_truth(eligibility, targets)\n\n if len(sys.argv) != 2:\n raise SystemExit(\n \"usage: evaluate_public.py <validation-ranking.parquet|csv>\"\n )\n path = Path(sys.argv[1])\n ranked = load_submission(path, eligibility, targets)\n print(json.dumps({\"model\": str(path), \"scores\": score(ranked, graded)}, indent=2))\n\n\nif __name__ == \"__main__\":\n main()\n# Exact distribution inventory for the Yambda two-tower task family.\n#\n# This is an input to `uv pip sync`, not a list of minimum requirements. A\n# conforming task environment contains exactly these third-party Python\n# distributions and no others. Python itself is pinned by task.toml and both\n# Harbor image Dockerfiles.\nattrs==26.1.0\nbleach==6.4.0\ncertifi==2026.7.22\nchardet==7.6.0\ncharset-normalizer==3.5.1\nfastjsonschema==2.22.2\nfilelock==3.32.3\nfsspec==2026.7.0\nidna==3.18\nJinja2==3.1.6\njoblib==1.5.3\njsonschema==4.26.0\njsonschema-specifications==2025.9.1\njupyter-core==5.9.1\njupytext==1.19.5\nkaggle==2.2.4\nkagglesdk==0.1.37\nmarkdown-it-py==4.2.0\nMarkupSafe==3.0.3\nmdit-py-plugins==0.6.1\nmdurl==0.1.2\nmpmath==1.3.0\nnbformat==5.11.1\nnetworkx==3.6.1\nnumpy==2.2.6\npackaging==26.3\npandas==2.3.3\npillow==12.3.0\npip==26.0.1\nplatformdirs==4.11.3\nprotobuf==7.35.1\npyarrow==18.1.0\npython-dateutil==2.9.0.post0\npython-dotenv==1.2.3\npython-slugify==8.0.4\npytz==2026.3.post1\nPyYAML==6.0.3\nreferencing==0.37.0\nreportlab==4.2.5\nrequests==2.34.2\nrpds-py==2026.6.3\nscikit-learn==1.7.2\nscipy==1.15.3\nsetuptools==84.0.0\nsix==1.17.0\nsympy==1.14.0\ntext-unidecode==1.3\nthreadpoolctl==3.6.0\ntorch==2.8.0\ntqdm==4.70.0\ntraitlets==5.16.1\ntyping-extensions==4.16.0\ntzdata==2026.3\nurllib3==2.7.0\nwebencodings==0.6.1\n"
}
}