:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): add the nn inbox ranking family and signals_ml location (#116620)
posthog[bot]b72c7a54f70d
diff --git a/.dagster_home/workspace.yaml b/.dagster_home/workspace.yamlindex e7cad14797a9..960949619fec 100644--- a/.dagster_home/workspace.yaml+++ b/.dagster_home/workspace.yaml@@ -16,5 +16,8 @@ load_from:- python_module: posthog.dags.locations.growth- python_module: posthog.dags.locations.shared- python_module: posthog.dags.locations.signals+ # Needs torch (`uv sync --group inbox-ranking`), so it stays off by default.+ # See products/signals/dags/inbox_ranking/README.md before you uncomment it.+ # - python_module: posthog.dags.locations.signals_ml- python_module: posthog.dags.locations.ingestion- python_module: posthog.dags.locations.web_analyticsdiff --git a/.github/workflows/ci-inbox-ranking.yml b/.github/workflows/ci-inbox-ranking.ymlindex fd815380ff49..13b3883c89d6 100644--- a/.github/workflows/ci-inbox-ranking.yml+++ b/.github/workflows/ci-inbox-ranking.yml@@ -1,4 +1,4 @@-# Runs the inbox ranking multi-head network tests with the inbox-ranking dependency group.+# Runs the inbox ranking multi-head network and `nn` family tests with the inbox-ranking dependency group.# torch is not a main dependency, so the other test jobs skip these tests.name: Inbox ranking network CI@@ -6,6 +6,7 @@ on:pull_request:paths:- '.github/workflows/ci-inbox-ranking.yml'+ - 'posthog/dags/locations/signals_ml.py'- 'products/signals/dags/inbox_ranking/**'- 'pyproject.toml'- 'uv.lock'@@ -63,8 +64,9 @@ jobs:run: UV_PROJECT_ENVIRONMENT=$pythonLocation uv sync --frozen --dev --group inbox-ranking# The tests need no database, ClickHouse or Redis, so the job starts no services.- - name: Run the network tests+ - name: Run the network and nn family testsrun: |python -c "import torch, onnxruntime"pytest products/signals/dags/inbox_ranking/tests/test_multihead_network.py \- products/signals/dags/inbox_ranking/tests/test_multihead.py -v --tb=short+ products/signals/dags/inbox_ranking/tests/test_multihead.py \+ products/signals/dags/inbox_ranking/tests/test_nn.py -v --tb=shortdiff --git a/posthog/dags/locations/signals_ml.py b/posthog/dags/locations/signals_ml.pynew file mode 100644index 000000000000..9bdd1d1b87cf--- /dev/null+++ b/posthog/dags/locations/signals_ml.py@@ -0,0 +1,24 @@+import dagster++from products.signals.dags.inbox_ranking.common import is_inbox_ranking_registered+from products.signals.dags.inbox_ranking.nn import dag as inbox_ranking_nn++from . import loggers, resources++# Runs on an image with the `inbox-ranking` dependency group. torch is imported only inside the+# candidate asset's body, so this module imports on the main image too. Registered on US (and+# non-cloud) only, behind the same gate as `signals.py`.+if is_inbox_ranking_registered():+ defs = dagster.Definitions(+ assets=[+ inbox_ranking_nn.inbox_ranking_nn_examples,+ inbox_ranking_nn.inbox_ranking_nn_model_candidate,+ inbox_ranking_nn.inbox_ranking_nn_model_champion,+ ],+ jobs=[inbox_ranking_nn.inbox_ranking_nn_training_job],+ schedules=[inbox_ranking_nn.inbox_ranking_nn_training_schedule],+ loggers=loggers,+ resources=resources,+ )+else:+ defs = dagster.Definitions(loggers=loggers, resources=resources)diff --git a/products/signals/dags/inbox_ranking/AGENTS.md b/products/signals/dags/inbox_ranking/AGENTS.mdindex 5368ec8019e7..913a35cbf030 100644--- a/products/signals/dags/inbox_ranking/AGENTS.md+++ b/products/signals/dags/inbox_ranking/AGENTS.md@@ -8,7 +8,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- `inbox_report_title_embeddings` is a **leaf**: never add it to `inbox_report_model_data`'s `deps` or give that join a title column, or a failure in the title snapshot fails the training table. Its own `deps=[MODEL_DATA_TABLE]` exists for memory, not data — two full sets of 1536-float vectors must not be held at once in the run pod. Raising the pod memory limit is not the first resort.- `inbox_user_report_interactions` is a **leaf** with its own `USER_INTERACTIONS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`, and never stamp it with `FEATURE_SCHEMA_VERSION`, or a user-grain change sets off the labels refresh sensor. It writes a row only for a report in this region's Postgres whose team is in `training_consent_team_ids()`.- `inbox_project_vectors` is a **leaf** with its own `PROJECT_VECTORS_SCHEMA_VERSION`: keep it out of `inbox_report_model_data`'s `deps`. Its `deps=[EMBEDDINGS_TABLE, LABELS_TABLE]` keep it after the embeddings snapshot, so the two vector-heavy steps do not share the run pod's memory. `project_vectors` takes a report into a vector only when its vector landed and its UI engagement happened strictly before `as_of`; never widen that to the latest snapshot value. A report born on day D reads the dt=D−1 vectors (see the README).-- Register new jobs/schedules in `posthog/dags/locations/signals.py`, keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).+- Register new jobs/schedules in `posthog/dags/locations/signals.py` (or `signals_ml.py` for a torch-dependent dag), keep the EU gate (`is_inbox_ranking_registered()`), and remember the ci-dagster paths filter must cover every module a dag file imports (`uv run .github/scripts/check-dagster-paths.py`).## Training dag specifics@@ -25,7 +25,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- The model is read in three layers: **training** (train metrics), **test** (the random-by-report holdout, which drives promotion) and **online** (`inbox_ranking_served_scores`, the scoring sweep's live scores of each day's newborns, graded by `inbox_ranking_unseen_graded` at each head's horizon). Do not add an offline rescoring of the newborn pool beside the online layer: the sweep already scores it with every model key the manifest names.- `served_score_rows` keeps the earliest scored event per (report, model key) and takes `model_role` from the event's roles. Grades stay per `(model_name, model_version, model_role)` and are never pooled across versions. A re-run that reads no event is refused when the partition already holds rows, and so is one that reads fewer families than the object holds, because the newborn state snapshot behind those rows ages out and the dt=D+horizon grade reads them.- Every scored row carries `head_readable`, and an unreadable head is still graded: a rare head (`thumbs_up`, `reviewer_fix`) never clears `min_holdout_positives` on one day's holdout, so the pooled online grade is the only read that can give it a number. Keep the promotion gate reading `readable` from the candidate metadata: an unreadable head must not decide a promotion.-- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on; the candidate and champion assets walk that registry, and the grader and the events need no change to gain a family. Promotion stays inside a family, so a family never takes another family's `champion.json`. Do not fold the family into `model_version`, which the dashboard filters as a date.+- `model_name` is the model family, and every model object, scored row, grade and event carries it. A family is an entry in `MODEL_FAMILIES` (`training/unseen.py`) naming the feature set it is fit on, its `learner` and the `location` that trains it; each location's candidate and champion assets walk `families_trained_in(<location>)`, and the grader and the events need no change to gain a family. Promotion stays inside a family, so a family never takes another family's `champion.json`. Do not fold the family into `model_version`, which the dashboard filters as a date.- A family whose `metadata.json`, examples object or side input is missing for a partition is logged and skipped, so one family does not cost every family's series. The champion asset raises only when no family has a candidate at all.- Skipping is not the same as rebuilding from nothing, and the difference is destructive. An empty examples object produces an empty candidate, and the candidate's prefix cleanup then deletes the boosters that partition already holds, which a `champion.json` can be pointing at. So when a side input is unavailable, leave the partition's objects alone rather than writing empty ones over them.- The champion is compared to a candidate on the candidate's holdout, through the champion's `<head>.holdout.ubj` (the train-only fit). Keep writing that file: without it the gate falls back to the champion's stored AUC, which was measured on a different set of reports.@@ -35,6 +35,7 @@ Read `README.md` first for what the dataset is and how partitions behave. This f- The manifest schema and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, next to the feature contract, because the dag writes them and the sweep reads them. Its validators run at write time, so the dag refuses a manifest the sweep could not act on; the entry cap is the `ranking_score` artefact's, so a manifest can never produce a row the artefact refuses.- Publishing order is load-bearing. Every model copy finishes before `manifest.json` is written, so a failed copy leaves the previous manifest and the previous models serving. A model version is immutable, so a version whose `metadata.json` is already at the target is not copied again. A run with nothing to publish, and no champion for the served family is the case today, writes nothing rather than an empty manifest.- When a manifest entry has `reads_project_vectors`, the dt=D `inbox_project_vectors` day is copied to `serving/project_vectors/<D>/` before `manifest.json`, and the manifest names it in `project_vectors`. A missing day fails the publish, like a missing model file. Never copy project vectors to the mirror: they are per-team data of this deployment, so the mirror's manifest names none. Training and serving build the `project` and `has_history` inputs through the one `project_inputs` in `features.py`; keep `PROJECT_VECTOR_KINDS` and `MIN_PROJECT_HISTORY_REPORTS` there.+- `nn` is trained by the `signals_ml` location (`nn/dag.py`), never by the main one. torch is imported only inside the candidate asset's body (through `nn/train.py` and `multihead/network.py`). `signals_ml` must import without torch, and `test_multihead_network.py` pins that. Its champion goes through `decide_family_champion`, the same rule and gate as the boosters, graded through the incumbent's `model.holdout.onnx`. Keep `signals_ml` commented out in `.dagster_home/workspace.yaml`, and keep its schedule (04:30 UTC) stopped by default.## Invariants — do not breakdiff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.mdindex 77f978631af8..cc6a78e22e19 100644--- a/products/signals/dags/inbox_ranking/README.md+++ b/products/signals/dags/inbox_ranking/README.md@@ -15,11 +15,12 @@ inbox_ranking/│ ├── heads.py # the v0 outcome heads│ ├── train.py # per-head XGBoost fit + holdout/null metrics│ └── promotion.py # the champion promotion rule-├── multihead/ # dev-only: offline multi-head network prototype, no dag+├── multihead/ # the multi-head network, its ONNX export, and the offline prototype+├── nn/ # the `nn` family: examples → candidate → champion assets, on the `signals_ml` location└── tests/```-Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally through `.dagster_home/workspace.yaml`.+Registered via `posthog/dags/locations/signals.py` (US only) and loaded locally through `.dagster_home/workspace.yaml`. The `nn` family is registered via `posthog/dags/locations/signals_ml.py` instead, because it needs torch (see [The nn family](#the-nn-family)).## The dataset dag@@ -145,7 +146,7 @@ s3://<bucket>/<prefix>/└── inbox_ranking_served_scores/v1/dt=YYYY-MM-DD/ # the scoring sweep's scores of the reports born that day, per model key```-- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner: `report_embeddings` and `title_embeddings`, both per-head XGBoost, are the two trained here. `model_version` is the partition day it was fit on, and `model_role` is the role it was scored or trained under (`candidate` on the training events; `served`, `daily_candidate` or `cross_family` on the online grade). Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A second family is a second model graded on the same online rows, not a competitor for another family's pointer.+- **A model is a `(model_name, model_version, model_role)`.** `model_name` is the family: which features and which learner: `report_embeddings` and `title_embeddings`, both per-head XGBoost, are the two trained here. `nn`, one ONNX network, is trained by the `signals_ml` location, and each `MODEL_FAMILIES` entry names its `learner` and the `location` that trains it. `model_version` is the partition day it was fit on, and `model_role` is the role it was scored or trained under (`candidate` on the training events; `served`, `daily_candidate` or `cross_family` on the online grade). Each family owns a prefix under the models path and its own `champion.json`, so two families trained on the same day cannot collide, and promotion stays inside a family. A second family is a second model graded on the same online rows, not a competitor for another family's pointer.- **A feature set is one feature universe.** `products/signals/backend/ranking/features.py` holds a `FeatureSet` per universe: its name, its schema version, its ordered feature names, the report-state columns it reads, `build_matrix`, and how many rows it wants per report and per head. `report_embeddings` and `title_embeddings` are the two today. A candidate records the set it was fit on in its `metadata.json`, so the grader checks a model against its own set rather than one global contract, the examples asset writes one Parquet per set, and the unseen scorer builds one matrix per set and shares it across the families that read it. Adding a set means an entry in `FEATURE_SETS`; a model naming a set this build cannot produce is logged and left unscored.- **Examples are one row per report at its birth, by default.** For partition `dt=D` the examples asset reads the report-state and labels snapshots `dt=D-lookback..D` and emits one row per report, on the snapshot of the day it was created, labeled from the snapshot `horizon_days` later (3 for open, 7 for action / pr_created / discuss / thumbs_up, 14 for pr_merged / refund / reviewer_fix, 21 for dismiss_wrong / fixed / dismiss_lowvalue). Features are built by the feature set from that snapshot's state columns plus `age_hours`, the report's age at the snapshot. Labels are aligned to the state spine, so a report with no label event is a negative (all-zero labels), not absent. Label-only rows (no Postgres state) are skipped, as are state rows read long after their snapshot day (backfills carry current Postgres state; see `features_observed_at`) and, for the heads that read the status stream (`dismiss_wrong`, `action`, `fixed` and `dismiss_lowvalue`), rows whose status telemetry fails the dataset's `label_provenance_ok` check. Birth is the moment serving scores a report, and the label that comes out is a per-report probability, which is what the inbox ordering needs. A report born before the window, or one whose birth-day snapshot is missing from it, is no example; `reports_missing_birth_snapshot` on the asset counts the second case, which is a gap in the partitions.- **An outcome already visible on the birth day is a future positive.** A report born on day D has no scoring moment before D, so an outcome visible at D belongs to the moment being built rather than to an earlier one; the labels of D therefore read as their defaults for a report born on D. Most outcomes land on the birth day, so this is where the positives are: censoring on them costs the `pr_created` head most of its training signal. `<set>_<head>_birth_day_positives` on the examples asset, and `birth_day_positives` on the `inbox_ranking_examples_built` event, say how many positives the rule keeps. These rows carry a hindsight the other rows do not: the state snapshot reads `signal_count`, `total_weight`, `run_count` and the text sizes live from Postgres a few hours after day D ends, so a birth-day outcome happened before its own feature read. Both the holdout AUC and the newborn unseen grade therefore read optimistically on these rows, until the scoring sweep's timestamped score log replaces the daily snapshot as this table's source.@@ -174,7 +175,7 @@ s3://<object-storage bucket>/<prefix>/serving/Each entry names its `model_kind`, and the sweep loads it through that kind's handler in `products/signals/backend/ranking/model_store.py`:- `xgboost`, the default for a model without the field: one booster per head, `<head>.ubj`. The entry's `heads` list names the files.-- `onnx`: one `model.onnx` for every head. The entry names it in `model_file`, and `heads` still lists the heads it scores. The graph takes one float32 input, `report`, of shape (batch, feature-set width), and gives one output, `probabilities`, of shape (batch, heads). The column order of that output is `output_heads` in the model's `metadata.json`, and each head entry in `heads` there names `model.onnx` as its `file`. At load, the handler checks the input names and widths against what the model's feature set builds, and a mismatch skips the model like an unloadable booster. The session runs on CPU with a bounded thread count, and `onnxruntime` is imported only when a model loads. The project-vector inputs are not served yet.+- `onnx`: one `model.onnx` for every head. The entry names it in `model_file`, and `heads` still lists the heads it scores. The graph takes one float32 input, `report`, of shape (batch, feature-set width), and gives one output, `probabilities`, of shape (batch, heads). The column order of that output is `output_heads` in the model's `metadata.json`, and each head entry in `heads` there names `model.onnx` as its `file`. At load, the handler checks the input names and widths against what the model's feature set builds, and a mismatch skips the model like an unloadable booster. The session runs on CPU with a bounded thread count, and `onnxruntime` is imported only when a model loads. The project-vector inputs are not served yet, so the sweep skips an `nn` model, whose graph also takes `project` and `has_history`, until it feeds them.The manifest holds one entry per model with its `roles`: `served` for the champion of `INBOX_RANKING_SERVED_FAMILY`, `daily_candidate` for that family's candidate on this partition when it is a different, readable model, `pinned` for each model the `pin` override keeps (see [Overrides](#overrides)), and `cross_family` for every other family's champion that has a readable head. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first and `pinned` entries next. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. No family has a champion until the first promotion, so until then the asset writes nothing and says why.@@ -357,6 +358,33 @@ The run takes the newest day that has the state, labels and report embeddings caThe network leaves out every report that is in any head's holdout, so the comparison is conservative for it. A run holds one embeddings snapshot: the title embeddings are never read, and the project vectors are computed from the same table as the report vectors. Results vary with `--seed`, so compare a few seeds before you read a small AUC gap as a result.+### The nn family++`nn` is one multi-head network (`multihead/network.py`) over the report vector and the team's `typical`, `open`, `action` and `dismiss` project vectors, with the heads `open`, `action` and `fixed`. It is a model family like the per-head ones: it has its own prefix and its own `champion.json`, the main job's serving manifest names its champion as an `onnx` entry, and the online grader grades it. The main location's candidate and champion assets never fit it.++`inbox_ranking_nn_training_job` lives on its own code location, `posthog/dags/locations/signals_ml.py`, which runs on an image with the `inbox-ranking` group. torch is imported only inside the candidate asset's body, so the location module imports on the main image too, and `test_multihead_network.py` fails if torch reaches it. The job writes:++```text+s3://<bucket>/<prefix>/+├── inbox_ranking_nn_examples/v1/dt=YYYY-MM-DD/ # rows, a label and a holdout flag per head; no vectors+└── inbox_ranking_models/v1/nn/+ ├── dt=YYYY-MM-DD/model.onnx + model.holdout.onnx + metadata.json+ └── champion.json+```++- **Examples** are the prototype's: each head's `example_moments` over the `report_embeddings` set, capped by `cap_examples` and split by `holdout_mask`, so every head's rows and holdout are the ones its `report_embeddings` champion is graded on. The object holds no vector. The candidate and champion assets rebuild the report vectors and the project vectors from the dt=D embeddings and labels snapshots.+- **Candidate**: the network trains on the rows in no head's holdout and is graded on each head's own holdout through the same `head_metrics` the boosters use, so `metadata.json` carries the same per-head fields (pooled and within-team AUC, average precision, ECE, readability, row counts, example window). Readability uses the boosters' permutation null: three networks fit on permuted labels. `model.onnx` is a refit on every labeled row, and `model.holdout.onnx` is the train-only fit. `metadata.json` has `model_kind: onnx`, `feature_set: report_embeddings`, and `output_heads`, the graph's column order.+- **Champion**: the same rule, overrides and `INBOX_RANKING_AUTO_PROMOTE` gate as the other families (`decide_family_champion`). The incumbent is graded through its `model.holdout.onnx` on the candidate's holdout, with `onnxruntime`.+- **A missing partition is a skip.** If the dt=D state, labels or embeddings snapshot is missing, each asset logs and writes nothing, so the partition keeps the objects it holds.+- **Schedule**: 04:30 UTC, after the dataset job's 2h budget (02:30 UTC start) and before the 05:00 UTC training job when the run is short enough. A champion that lands after that day's manifest is published by the next day's manifest. The schedule is stopped by default in every environment.++To run it locally, install the group (`uv sync --group inbox-ranking`), sync the snapshots with `INBOX_RANKING_SYNC_EMBEDDINGS=1` as in [Running the training job locally](#running-the-training-job-locally), and uncomment `posthog.dags.locations.signals_ml` in `.dagster_home/workspace.yaml`. The entry is commented out because most developers do not have torch installed. Then launch the job:++```bash+dagster job launch -w .dagster_home/workspace.yaml --location posthog.dags.locations.signals_ml \+ -j inbox_ranking_nn_training_job --tags '{"dagster/partition": "2026-08-25"}'+```+## Configuration| Setting | Default | Meaning |diff --git a/products/signals/dags/inbox_ranking/multihead/inputs.py b/products/signals/dags/inbox_ranking/multihead/inputs.pyindex 3fa35cfb5531..ff6787c4934d 100644--- a/products/signals/dags/inbox_ranking/multihead/inputs.py+++ b/products/signals/dags/inbox_ranking/multihead/inputs.py@@ -5,6 +5,10 @@ import numpy as npfrom posthog.dataclasses import frozen+# The exported graph's names. A network without context takes only the first input.+ONNX_INPUTS = ("report", "project", "has_history")+ONNX_OUTPUT = "probabilities"+@frozenclass NetworkConfig:diff --git a/products/signals/dags/inbox_ranking/multihead/network.py b/products/signals/dags/inbox_ranking/multihead/network.pyindex cff3ee4831fb..8b74b0775188 100644--- a/products/signals/dags/inbox_ranking/multihead/network.py+++ b/products/signals/dags/inbox_ranking/multihead/network.py@@ -26,15 +26,13 @@ from torch import nnfrom torch.nn import functional as Ffrom products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS-from products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig, NetworkInputs+from products.signals.dags.inbox_ranking.multihead.inputs import ONNX_INPUTS, ONNX_OUTPUT, NetworkConfig, NetworkInputs# text-embedding-3 vectors are unit length, so each component is about 1/sqrt(D). Scaling by# sqrt(D) gives the projection unit-variance inputs, which is what its initialization assumes.INPUT_SCALE = math.sqrt(EMBEDDING_DIMENSIONS)ONNX_OPSET = 17-ONNX_INPUTS = ("report", "project", "has_history")-ONNX_OUTPUT = "probabilities"class _Model(nn.Module):diff --git a/products/signals/dags/inbox_ranking/multihead/prototype.py b/products/signals/dags/inbox_ranking/multihead/prototype.pyindex a4de32b2ad54..d224f2da825c 100644--- a/products/signals/dags/inbox_ranking/multihead/prototype.py+++ b/products/signals/dags/inbox_ranking/multihead/prototype.py@@ -81,11 +81,23 @@ class ExampleTable:return self.rows["report_team_id"].to_numpy(dtype=object)[rows]-def example_table(snapshots: Mapping[datetime.date, Snapshot], extras: Extras, *, holdout_days: int) -> ExampleTable:- """The moments of every prototype head, joined on the report moment."""+def example_table(+ snapshots: Mapping[datetime.date, Snapshot],+ extras: Extras,+ *,+ holdout_days: int,+ head_moments: Mapping[str, pd.DataFrame] | None = None,+) -> ExampleTable:+ """The moments of every prototype head, joined on the report moment. `head_moments` holds each+ head's capped moments by name, when the caller already built them."""frames = []for head in PROTOTYPE_HEADS:- moments = cap_examples(example_moments(snapshots, head, FEATURE_SET, extras), FEATURE_SET.max_examples_per_head)+ if head_moments is not None:+ moments = head_moments[head.name]+ else:+ moments = cap_examples(+ example_moments(snapshots, head, FEATURE_SET, extras), FEATURE_SET.max_examples_per_head+ )frames.append(moments.assign(holdout=holdout_mask(moments, holdout_days).to_numpy()).set_index(["report_id", "snapshot_date"])[["label", "holdout"]]diff --git a/products/signals/dags/inbox_ranking/nn/dag.py b/products/signals/dags/inbox_ranking/nn/dag.pynew file mode 100644index 000000000000..376c7460d057--- /dev/null+++ b/products/signals/dags/inbox_ranking/nn/dag.py@@ -0,0 +1,358 @@+"""Daily training for the `nn` model family: one multi-head network over the report vector and the+team's project vectors, exported to ONNX.++Three assets on the dataset dag's daily partition, registered by the `signals_ml` code location,+which runs on the image that carries torch:++ inbox_ranking_nn_examples/v1/dt=D/ rows, labels and holdout flags (`nn/examples.py`)+ inbox_ranking_models/v1/nn/dt=D/model.onnx the refit that serves, + model.holdout.onnx and metadata.json+ inbox_ranking_models/v1/nn/champion.json pointer to the version the scoring sweep loads++The main location's training job never fits `nn`, and this job never writes another family's+objects. The main job's serving manifest and online grader walk every family in `MODEL_FAMILIES`,+so they publish and grade an `nn` champion as an `onnx` entry with no change here. A champion that+lands after that day's manifest is published by the next day's manifest.++All three assets read the dt=D dataset partitions from the dataset bucket, as the main training job+does. A partition whose snapshots are missing is logged and skipped, and the objects already under+it stay as they are.+"""++import datetime+from collections.abc import Mapping+from typing import Any++import numpy as np+import dagster+import pyarrow as pa++from posthog import settings+from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import Extras+from products.signals.backend.ranking.overrides import read_ranking_overrides+from products.signals.backend.ranking.serving_manifest import ONNX_MODEL_FILE, ONNX_MODEL_KIND+from products.signals.dags.inbox_ranking.common import (+ S3_BUCKET_ENV,+ dataset_bucket,+ dataset_unconfigured,+ owner_tags,+ partition_object_key,+ read_parquet_if_exists,+ s3_client,+ skip_unconfigured,+ write_parquet,+)+from products.signals.dags.inbox_ranking.consent import training_consent_team_ids+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLE, STATE_TABLE+from products.signals.dags.inbox_ranking.dataset.project_vectors import EMBEDDING_COLUMNS, LABEL_COLUMNS+from products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig+from products.signals.dags.inbox_ranking.multihead.local import report_vectors+from products.signals.dags.inbox_ranking.nn.examples import (+ NN_HEADS,+ build_examples,+ examples_arrow,+ examples_from_arrow,+ network_inputs,+ subset,+)+from products.signals.dags.inbox_ranking.nn.model import HOLDOUT_MODEL_FILE, candidate_metadata, champion_grades+from products.signals.dags.inbox_ranking.training.calibration import bucket_rows+from products.signals.dags.inbox_ranking.training.dag import (+ _LOOKBACK_MAPPING,+ COMMON_ASSET_KWARGS,+ METADATA_FILE,+ _delete_other_objects,+ _put_json,+ _read_bytes_if_exists,+ decide_family_champion,+ load_snapshots,+ model_object_key,+ snapshot_dates,+)+from products.signals.dags.inbox_ranking.training.examples import drop_without_training_consent+from products.signals.dags.inbox_ranking.training.telemetry import (+ candidate_events,+ capture_training_events,+ holdout_calibration_events,+)+from products.signals.dags.inbox_ranking.training.train import HoldoutGrade+from products.signals.dags.inbox_ranking.training.unseen import NN_FAMILY++NN_EXAMPLES_TABLE = "inbox_ranking_nn_examples"+NN_CANDIDATE_ASSET = "inbox_ranking_nn_model_candidate"+NN_CHAMPION_ASSET = "inbox_ranking_nn_model_champion"++# The settings the prototype compared against the champion recipe with.+NETWORK_CONFIG = NetworkConfig()++NN_ASSET_KWARGS: dict[str, Any] = {**COMMON_ASSET_KWARGS, "group_name": "inbox_ranking_nn"}+++@frozen+class DayInputs:+ extras: Extras+ labels: pa.Table+ embeddings: pa.Table+++def _day_inputs(+ context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, partition_key: str+) -> DayInputs | None:+ """The report vectors, and the labels and embeddings snapshots the project vectors read, all from+ dt=D; None when either snapshot is missing. One embeddings snapshot serves every moment of the+ window, as in the main training job: each vector carries the moment it landed."""+ embeddings = read_parquet_if_exists(+ client, bucket, partition_object_key(prefix, EMBEDDINGS_TABLE, partition_key), columns=list(EMBEDDING_COLUMNS)+ )+ labels = read_parquet_if_exists(+ client, bucket, partition_object_key(prefix, LABELS_TABLE, partition_key), columns=list(LABEL_COLUMNS)+ )+ if embeddings is None or labels is None:+ missing = [name for name, table in ((EMBEDDINGS_TABLE, embeddings), (LABELS_TABLE, labels)) if table is None]+ context.log.warning(f"no {', '.join(missing)} snapshot for dt={partition_key}; nn skips this partition")+ return None+ return DayInputs(extras=report_vectors(embeddings), labels=labels, embeddings=embeddings)+++ name=NN_EXAMPLES_TABLE,+ deps=[+ dagster.AssetDep(STATE_TABLE, partition_mapping=_LOOKBACK_MAPPING),+ dagster.AssetDep(LABELS_TABLE, partition_mapping=_LOOKBACK_MAPPING),+ EMBEDDINGS_TABLE,+ ],+ **NN_ASSET_KWARGS,+)+def inbox_ranking_nn_examples(context: dagster.AssetExecutionContext) -> None:+ if skip_unconfigured(context):+ return+ partition_key = context.partition_key+ bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()++ dates = snapshot_dates(partition_key, settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS)+ snapshots = load_snapshots(client, bucket, prefix, dates)+ if dates[-1] not in snapshots:+ context.log.warning(f"no state and labels snapshots for dt={partition_key}; nn skips this partition")+ context.add_output_metadata({"skipped": dagster.MetadataValue.bool(True)})+ return+ day = _day_inputs(context, client, bucket, prefix, partition_key)+ if day is None:+ context.add_output_metadata({"skipped": dagster.MetadataValue.bool(True)})+ return+ snapshots, excluded = drop_without_training_consent(snapshots, training_consent_team_ids())+ examples = build_examples(snapshots, day.extras, holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS)+ if examples.rows_without_team:+ context.log.warning(f"{examples.rows_without_team} moments have no team and no project vectors; dropped")++ key = partition_object_key(prefix, NN_EXAMPLES_TABLE, partition_key)+ write_parquet(client, bucket, key, examples_arrow(examples), snapshot_date=partition_key)+ table = examples.table+ observed = ~np.isnan(table.labels)+ context.add_output_metadata(+ {+ "snapshots": dagster.MetadataValue.int(len(snapshots)),+ "rows": dagster.MetadataValue.int(len(table.rows)),+ "network_train_rows": dagster.MetadataValue.int(len(table.network_train_rows())),+ "rows_without_team": dagster.MetadataValue.int(examples.rows_without_team),+ "excluded_no_training_consent_reports": dagster.MetadataValue.int(excluded.reports),+ **{+ f"{head.name}_rows": dagster.MetadataValue.int(int(observed[:, index].sum()))+ for index, head in enumerate(NN_HEADS)+ },+ **{+ f"{head.name}_positives": dagster.MetadataValue.int(int(np.nansum(table.labels[:, index])))+ for index, head in enumerate(NN_HEADS)+ },+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{key}"),+ }+ )++[email protected](name=NN_CANDIDATE_ASSET, deps=[NN_EXAMPLES_TABLE], **NN_ASSET_KWARGS)+def inbox_ranking_nn_model_candidate(context: dagster.AssetExecutionContext) -> None:+ if skip_unconfigured(context):+ return+ context.add_output_metadata(train_candidate(context, s3_client(), dataset_bucket(), context.partition_key))+++def train_candidate(+ context: dagster.AssetExecutionContext, client, bucket: str, partition_key: str+) -> dict[str, dagster.MetadataValue]:+ """Fit the day's network, write its graphs and `metadata.json` under `nn/dt=D/`, and return the+ asset metadata. A partition without examples or snapshots keeps the objects it already holds,+ because a `champion.json` can name them."""+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX+ arrow = read_parquet_if_exists(client, bucket, partition_object_key(prefix, NN_EXAMPLES_TABLE, partition_key))+ if arrow is None:+ context.log.warning(f"no nn examples for dt={partition_key}; nn keeps this partition as it stands")+ return {"skipped": dagster.MetadataValue.bool(True)}+ day = _day_inputs(context, client, bucket, prefix, partition_key)+ if day is None:+ return {"skipped": dagster.MetadataValue.bool(True)}+ examples = examples_from_arrow(arrow)+ inputs = network_inputs(examples.table, day.extras, day.labels, day.embeddings)+ del day++ from products.signals.dags.inbox_ranking.nn.train import ( # noqa: PLC0415 — keeps torch off the location's import path+ train_network,+ )++ trained = train_network(examples.table, inputs, NN_HEADS, NETWORK_CONFIG)+ for head in trained.heads:+ context.log.info(f"nn {head.metrics.head}: {head.metrics.as_dict()}")+ for name in trained.skipped:+ context.log.warning(f"nn {name}: nothing to fit, skipped")++ files = {ONNX_MODEL_FILE: trained.model_onnx, HOLDOUT_MODEL_FILE: trained.holdout_model_onnx}+ written: set[str] = set()+ for filename, body in files.items():+ if body is None:+ continue+ key = model_object_key(prefix, NN_FAMILY.name, partition_key, filename)+ client.put_object(Bucket=bucket, Key=key, Body=body, ContentType="application/octet-stream")+ written.add(key)+ metadata = candidate_metadata(+ partition_key,+ trained,+ config=NETWORK_CONFIG,+ windows=examples.windows,+ trained_at=datetime.datetime.now(datetime.UTC),+ run_id=context.run_id,+ )+ metadata_key = model_object_key(prefix, NN_FAMILY.name, partition_key, METADATA_FILE)+ _put_json(client, bucket, metadata_key, metadata)+ written.add(metadata_key)+ stale = _delete_other_objects(client, bucket, model_object_key(prefix, NN_FAMILY.name, partition_key, ""), written)+ if stale:+ context.log.warning(f"removed {len(stale)} stale nn objects from a previous run of dt={partition_key}")+ capture_training_events(+ context,+ partition_key,+ [+ *candidate_events(metadata),+ *holdout_calibration_events(+ partition_key=partition_key,+ run_id=context.run_id,+ model_name=NN_FAMILY.name,+ rows=[+ row for head in trained.heads for row in bucket_rows(head.calibration, {"head": head.metrics.head})+ ],+ ),+ ],+ )+ return {+ "stale_objects_removed": dagster.MetadataValue.int(len(stale)),+ "network_train_rows": dagster.MetadataValue.int(trained.network_train_rows),+ "heads_trained": dagster.MetadataValue.int(len(trained.heads)),+ "heads_readable": dagster.MetadataValue.int(sum(1 for head in trained.heads if head.metrics.readable)),+ **{+ f"{head.metrics.head}_holdout_auc": dagster.MetadataValue.float(head.metrics.holdout_auc)+ for head in trained.heads+ if head.metrics.holdout_auc is not None+ },+ **{+ f"{head.metrics.head}_{name}": (+ dagster.MetadataValue.int(value) if isinstance(value, int) else dagster.MetadataValue.float(value)+ )+ for head in trained.heads+ for name, value in head.metrics.holdout_within_team.as_dict(prefix="holdout_").items()+ if value is not None+ },+ "s3_key": dagster.MetadataValue.text(f"s3://{bucket}/{metadata_key}"),+ }++[email protected](name=NN_CHAMPION_ASSET, deps=[NN_CANDIDATE_ASSET], **NN_ASSET_KWARGS)+def inbox_ranking_nn_model_champion(context: dagster.AssetExecutionContext) -> None:+ if skip_unconfigured(context):+ return+ metadata = decide_champion(context, s3_client(), dataset_bucket(), context.partition_key)+ context.add_output_metadata(metadata or {"skipped": dagster.MetadataValue.bool(True)})+++def decide_champion(+ context: dagster.AssetExecutionContext, client, bucket: str, partition_key: str+) -> dict[str, dagster.MetadataValue] | None:+ """The `nn` promotion decision, through the rule, the overrides and the+ `INBOX_RANKING_AUTO_PROMOTE` gate every family shares. Only `nn/champion.json` is ever written."""+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX++ def grade_champion(champion: Mapping[str, Any]) -> dict[str, HoldoutGrade]:+ version = champion.get("model_version")+ if champion.get("model_kind") != ONNX_MODEL_KIND:+ context.log.warning(f"nn champion {version} is not an {ONNX_MODEL_KIND} model; compared on its stored AUC")+ return {}+ holdout_model = _read_bytes_if_exists(+ client, bucket, model_object_key(prefix, NN_FAMILY.name, str(version), HOLDOUT_MODEL_FILE)+ )+ arrow = read_parquet_if_exists(client, bucket, partition_object_key(prefix, NN_EXAMPLES_TABLE, partition_key))+ if holdout_model is None or arrow is None:+ context.log.warning(+ f"no nn champion {HOLDOUT_MODEL_FILE} or no examples for dt={partition_key}; "+ "the nn champion is compared on its stored AUC"+ )+ return {}+ day = _day_inputs(context, client, bucket, prefix, partition_key)+ if day is None:+ return {}+ table = examples_from_arrow(arrow).table+ holdout = subset(table, np.flatnonzero(table.holdout.any(axis=1)))+ return champion_grades(+ champion, holdout_model, holdout, network_inputs(holdout, day.extras, day.labels, day.embeddings)+ )++ return decide_family_champion(+ context,+ client,+ bucket,+ prefix,+ partition_key,+ NN_FAMILY,+ read_ranking_overrides(datetime.datetime.now(datetime.UTC)),+ grade_champion=grade_champion,+ )+++inbox_ranking_nn_training_job = dagster.define_asset_job(+ name="inbox_ranking_nn_training_job",+ selection=[NN_EXAMPLES_TABLE, NN_CANDIDATE_ASSET, NN_CHAMPION_ASSET],+ tags={+ **owner_tags,+ # Five network fits per run (the train-only fit, NULL_PERMUTATIONS permuted-label fits and the+ # refit that ships), on CPU.+ "dagster/max_runtime": str(3 * 60 * 60),+ # The examples asset holds the lookback window's snapshots in pandas, as the main training job+ # does. The candidate holds one embeddings snapshot twice (as Arrow for the project vectors+ # and as the report side input), the report matrix, and one set of project vectors per+ # (team, day).+ "dagster-k8s/config": {+ "container_config": {+ "resources": {+ "requests": {"memory": "8Gi"},+ "limits": {"memory": "24Gi"},+ }+ }+ },+ },+)+++# After the dataset job's 2h budget (02:30 UTC start), so the dt=D-1 snapshots exist, and before the+# main training job (05:00 UTC) where the run is short enough. A champion that lands after that+# job's manifest is published by the next day's manifest. Stopped everywhere until the location is+# deployed on the image with torch.+ cron_schedule="30 4 * * *",+ job=inbox_ranking_nn_training_job,+ execution_timezone="UTC",+ default_status=dagster.DefaultScheduleStatus.STOPPED,+ tags=owner_tags,+)+def inbox_ranking_nn_training_schedule(+ context: dagster.ScheduleEvaluationContext,+) -> dagster.RunRequest | dagster.SkipReason:+ if dataset_unconfigured():+ return dagster.SkipReason(f"{S3_BUCKET_ENV} is not set; skipping until the dedicated bucket is provisioned")+ previous_day = context.scheduled_execution_time.date() - datetime.timedelta(days=1)+ return dagster.RunRequest(partition_key=previous_day.isoformat(), run_key=f"nn-training-{previous_day.isoformat()}")diff --git a/products/signals/dags/inbox_ranking/nn/examples.py b/products/signals/dags/inbox_ranking/nn/examples.pynew file mode 100644index 000000000000..6044802bd3e8--- /dev/null+++ b/products/signals/dags/inbox_ranking/nn/examples.py@@ -0,0 +1,117 @@+"""The `nn` family's examples and network inputs, without torch.++The examples are the prototype's (`multihead/prototype.py`): one row per report moment, with a label+and a holdout flag for each of `open`, `action` and `fixed`. Each head's moments come from+`example_moments` over the `report_embeddings` set and are capped by `cap_examples`, so every head's+cohort, horizon, row budget and holdout are the ones its `report_embeddings` champion is graded on.++The examples object holds the rows, labels and holdout flags only. The vectors are rebuilt from the+dt=D embeddings and labels snapshots by each asset that reads the object: the report vectors+carry 1536 floats per row and the project vectors four times that per (team, day), and both are a+pure function of those two snapshots.+"""++import json+import datetime+from collections.abc import Mapping++import numpy as np+import pandas as pd+import pyarrow as pa++from posthog.dataclasses import frozen++from products.signals.backend.ranking.features import Extras+from products.signals.dags.inbox_ranking.multihead.inputs import NetworkInputs+from products.signals.dags.inbox_ranking.multihead.prototype import (+ FEATURE_SET,+ PROTOTYPE_HEADS,+ ExampleTable,+ example_table,+ project_context,+ report_matrix,+)+from products.signals.dags.inbox_ranking.training.examples import Snapshot, cap_examples, example_moments++NN_HEADS = PROTOTYPE_HEADS+NN_HEAD_NAMES = tuple(head.name for head in NN_HEADS)++_ROW_COLUMNS = ("report_id", "snapshot_date", "report_team_id")+# Parquet schema metadata key that carries each head's example window.+EXAMPLE_WINDOWS_METADATA_KEY = b"inbox_ranking_example_windows"+++@frozen+class NNExamples:+ table: ExampleTable+ # Per head, the `example_window_start` and `example_cap_bound` the per-head families record.+ windows: Mapping[str, Mapping[str, object]]+ # Moments without a team. They have no project vectors, so the network cannot read them.+ rows_without_team: int = 0+++def _window(moments: pd.DataFrame, kept: pd.DataFrame) -> dict[str, object]:+ days = pd.to_datetime(kept["report_created_at"], utc=True).dt.floor("D").dropna()+ return {+ "example_window_start": days.min().date().isoformat() if len(days) else None,+ "example_cap_bound": len(kept) < len(moments),+ }+++def subset(table: ExampleTable, rows: np.ndarray) -> ExampleTable:+ """The rows `rows` of `table`, positioned from zero."""+ return ExampleTable(+ rows=table.rows.iloc[rows].reset_index(drop=True), labels=table.labels[rows], holdout=table.holdout[rows]+ )+++def build_examples(snapshots: Mapping[datetime.date, Snapshot], extras: Extras, *, holdout_days: int) -> NNExamples:+ moments = {head.name: example_moments(snapshots, head, FEATURE_SET, extras) for head in NN_HEADS}+ kept = {name: cap_examples(frame, FEATURE_SET.max_examples_per_head) for name, frame in moments.items()}+ table = example_table(snapshots, extras, holdout_days=holdout_days, head_moments=kept)+ with_team = table.rows["report_team_id"].notna().to_numpy()+ return NNExamples(+ table=subset(table, np.flatnonzero(with_team)),+ windows={name: _window(moments[name], kept[name]) for name in NN_HEAD_NAMES},+ rows_without_team=int((~with_team).sum()),+ )+++def examples_arrow(examples: NNExamples) -> pa.Table:+ """The examples as one Parquet-ready table: the row identity, then `<head>_label` (NaN where the+ head has no example) and `<head>_holdout` per head."""+ table = examples.table+ frame = table.rows[list(_ROW_COLUMNS)].copy()+ frame["report_id"] = frame["report_id"].astype(str)+ frame["report_team_id"] = frame["report_team_id"].astype("int64")+ for index, name in enumerate(NN_HEAD_NAMES):+ frame[f"{name}_label"] = table.labels[:, index].astype(np.float32)+ frame[f"{name}_holdout"] = table.holdout[:, index]+ arrow = pa.Table.from_pandas(frame, preserve_index=False)+ return arrow.replace_schema_metadata(+ {**(arrow.schema.metadata or {}), EXAMPLE_WINDOWS_METADATA_KEY: json.dumps(examples.windows).encode()}+ )+++def examples_from_arrow(arrow: pa.Table) -> NNExamples:+ frame = arrow.to_pandas()+ rows = frame[list(_ROW_COLUMNS)].reset_index(drop=True)+ labels = np.column_stack([frame[f"{name}_label"].to_numpy(dtype=np.float32) for name in NN_HEAD_NAMES])+ holdout = np.column_stack([frame[f"{name}_holdout"].to_numpy(dtype=bool) for name in NN_HEAD_NAMES])+ raw = (arrow.schema.metadata or {}).get(EXAMPLE_WINDOWS_METADATA_KEY)+ return NNExamples(+ table=ExampleTable(+ rows=rows,+ labels=labels.reshape(len(rows), len(NN_HEAD_NAMES)),+ holdout=holdout.reshape(len(rows), len(NN_HEAD_NAMES)),+ ),+ windows=json.loads(raw) if raw else {},+ )+++def network_inputs(table: ExampleTable, extras: Extras, labels: pa.Table, embeddings: pa.Table) -> NetworkInputs:+ """The report vector of each row as of its moment, and its team's project vectors as of the+ start of its snapshot day, the ones serving would read for a report born that day."""+ return NetworkInputs(+ reports=report_matrix(table.rows, extras), context=project_context(table.rows, labels, embeddings)+ )diff --git a/products/signals/dags/inbox_ranking/nn/model.py b/products/signals/dags/inbox_ranking/nn/model.pynew file mode 100644index 000000000000..b7e1d2729d15--- /dev/null+++ b/products/signals/dags/inbox_ranking/nn/model.py@@ -0,0 +1,142 @@+"""The `nn` family's model record and its ONNX scoring, without torch.++A candidate is two ONNX graphs under `inbox_ranking_models/v1/nn/dt=D/`: `model.onnx`, the refit on+every labeled row that a store serves, and `model.holdout.onnx`, the train-only fit that produced the+holdout metrics. A later candidate grades the champion through the second one on its own holdout,+as the per-head families grade a champion through `<head>.holdout.ubj`.+"""++import datetime+import dataclasses+from collections.abc import Mapping, Sequence+from typing import Any++import numpy as np++from posthog import settings+from posthog.dataclasses import frozen++from products.signals.backend.ranking.model_store import ONNX_OUTPUT_HEADS_KEY+from products.signals.backend.ranking.serving_manifest import ONNX_MODEL_FILE, ONNX_MODEL_KIND+from products.signals.dags.inbox_ranking.common import DATASET_VERSION+from products.signals.dags.inbox_ranking.multihead.inputs import ONNX_INPUTS, ONNX_OUTPUT, NetworkConfig, NetworkInputs+from products.signals.dags.inbox_ranking.multihead.prototype import FEATURE_SET, ExampleTable+from products.signals.dags.inbox_ranking.nn.examples import NN_HEAD_NAMES+from products.signals.dags.inbox_ranking.training.calibration import CalibrationBucket+from products.signals.dags.inbox_ranking.training.heads import HEADS_BY_NAME+from products.signals.dags.inbox_ranking.training.train import HeadMetrics, HoldoutGrade, holdout_grade+from products.signals.dags.inbox_ranking.training.unseen import NN_MODEL_NAME++HOLDOUT_MODEL_FILE = "model.holdout.onnx"+++@frozen+class NetworkHead:+ metrics: HeadMetrics+ calibration: tuple[CalibrationBucket, ...]+++@frozen+class TrainedNetwork:+ # The graphs' output columns, in order. Every head the network was fit on has a column, a+ # skipped head included.+ output_heads: tuple[str, ...]+ # None when no head had anything to fit.+ model_onnx: bytes | None+ holdout_model_onnx: bytes | None+ heads: tuple[NetworkHead, ...]+ skipped: tuple[str, ...]+ network_train_rows: int+ refit_rows: int+ # The project-vector kinds the graphs take, empty for a report-only network.+ vector_kinds: tuple[str, ...]+++def candidate_metadata(+ partition_key: str,+ trained: TrainedNetwork,+ *,+ config: NetworkConfig,+ windows: Mapping[str, Mapping[str, object]],+ trained_at: datetime.datetime,+ run_id: str,+) -> dict[str, Any]:+ """The `metadata.json` of an `nn` candidate, in the layout of the per-head families.++ The heads carry the same metric fields as a booster's (`train_head` and this trainer both fill+ `HeadMetrics`), so the promotion rule, the events and the manifest read every family alike.+ """+ return {+ "model_name": NN_MODEL_NAME,+ "model_version": partition_key,+ "dataset_version": DATASET_VERSION,+ "model_kind": ONNX_MODEL_KIND,+ # The set that builds the `report` input, so the grader and the store check the graph+ # against it like any other family.+ "feature_set": FEATURE_SET.name,+ "feature_schema_version": FEATURE_SET.schema_version,+ "feature_names": list(FEATURE_SET.feature_names),+ ONNX_OUTPUT_HEADS_KEY: list(trained.output_heads),+ "project_vector_kinds": list(trained.vector_kinds),+ "trained_at": trained_at.isoformat(),+ "run_id": run_id,+ "lookback_days": settings.INBOX_RANKING_TRAINING_LOOKBACK_DAYS,+ "holdout_days": settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ "network_config": dataclasses.asdict(config),+ "network_train_rows": trained.network_train_rows,+ "refit_rows": trained.refit_rows,+ "heads": [+ head.metrics.as_dict()+ | {+ "cohort": HEADS_BY_NAME[head.metrics.head].cohort.__name__,+ "horizon_days": HEADS_BY_NAME[head.metrics.head].horizon_days,+ "example_window_start": windows.get(head.metrics.head, {}).get("example_window_start"),+ "example_cap_bound": windows.get(head.metrics.head, {}).get("example_cap_bound"),+ "file": ONNX_MODEL_FILE,+ "holdout_file": HOLDOUT_MODEL_FILE,+ }+ for head in trained.heads+ ],+ "skipped_heads": list(trained.skipped),+ }+++def onnx_probabilities(model: bytes, inputs: NetworkInputs, output_heads: Sequence[str]) -> dict[str, np.ndarray]:+ """Each output head's probability for every row of `inputs`, from a graph `export_onnx` wrote.++ The graph is fed only the inputs it declares, so a report-only graph reads the report vectors+ of a table built with context.+ """+ import onnxruntime as ort # noqa: PLC0415 — keeps onnxruntime's native runtime off the location's import path++ session = ort.InferenceSession(model, providers=["CPUExecutionProvider"])+ declared = {node.name for node in session.get_inputs()}+ report_input, project_input, history_input = ONNX_INPUTS+ feeds: dict[str, np.ndarray] = {report_input: np.ascontiguousarray(inputs.reports, dtype=np.float32)}+ if project_input in declared:+ if inputs.context is None:+ raise ValueError("the graph takes project vectors and the inputs carry none")+ pairs = inputs.context.index+ feeds[project_input] = np.ascontiguousarray(inputs.context.vectors[pairs], dtype=np.float32)+ feeds[history_input] = np.ascontiguousarray(inputs.context.has_history[pairs], dtype=np.float32)+ (probabilities,) = session.run([ONNX_OUTPUT], {name: value for name, value in feeds.items() if name in declared})+ return {head: probabilities[:, column] for column, head in enumerate(output_heads)}+++def champion_grades(+ champion: Mapping[str, Any], holdout_model: bytes, table: ExampleTable, inputs: NetworkInputs+) -> dict[str, HoldoutGrade]:+ """The champion's readable heads graded on the candidate's holdout rows of `table`, through the+ champion's train-only graph. `inputs` holds a row for each row of `table`."""+ probabilities = onnx_probabilities(holdout_model, inputs, champion.get(ONNX_OUTPUT_HEADS_KEY) or ())+ grades: dict[str, HoldoutGrade] = {}+ for entry in champion.get("heads", []):+ name = entry.get("head")+ if not entry.get("readable") or name not in probabilities or name not in NN_HEAD_NAMES:+ continue+ index = NN_HEAD_NAMES.index(name)+ rows = table.head_rows(index, holdout=True)+ if len(rows) == 0:+ continue+ grades[name] = holdout_grade(table.labels[rows, index].astype(int), probabilities[name][rows])+ return gradesdiff --git a/products/signals/dags/inbox_ranking/nn/train.py b/products/signals/dags/inbox_ranking/nn/train.pynew file mode 100644index 000000000000..71fb38fbaa0d--- /dev/null+++ b/products/signals/dags/inbox_ranking/nn/train.py@@ -0,0 +1,135 @@+"""Fit the `nn` family: one multi-head network, graded per head the way the per-head boosters are.++The network trains on the rows in no head's holdout (`ExampleTable.network_train_rows`), and each+head is graded on its own holdout. Readability uses the boosters' rule: a head must clear the mean+holdout AUC of `NULL_PERMUTATIONS` networks fit on permuted labels by `NULL_MARGIN`. The graph that+ships is a refit on every labeled row, as a booster is, and the train-only graph is kept to grade+this model as a later champion.++This module imports torch through `multihead/network.py`. Import it only inside an asset body.+"""++import tempfile+import dataclasses+from collections.abc import Sequence+from pathlib import Path++import numpy as np+from sklearn.metrics import roc_auc_score++from posthog.dataclasses import frozen++from products.signals.dags.inbox_ranking.dataset.project_vectors import VECTOR_KINDS+from products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig, NetworkInputs+from products.signals.dags.inbox_ranking.multihead.network import MultiHeadNetwork, export_onnx+from products.signals.dags.inbox_ranking.multihead.prototype import ExampleTable+from products.signals.dags.inbox_ranking.nn.model import NetworkHead, TrainedNetwork+from products.signals.dags.inbox_ranking.training.heads import Head+from products.signals.dags.inbox_ranking.training.train import NULL_PERMUTATIONS, head_metrics+++def _fit(+ inputs: NetworkInputs, heads: Sequence[Head], config: NetworkConfig, labels: np.ndarray, rows: np.ndarray+) -> MultiHeadNetwork:+ network = MultiHeadNetwork(+ heads=[head.name for head in heads],+ with_context=inputs.context is not None,+ kinds=len(VECTOR_KINDS),+ config=config,+ )+ network.fit(inputs, labels, rows)+ return network+++def _onnx_bytes(network: MultiHeadNetwork) -> bytes:+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "model.onnx"+ export_onnx(network, path)+ return path.read_bytes()+++def _auc(y: np.ndarray, scores: np.ndarray) -> float | None:+ if len(y) == 0 or y.sum() in (0, len(y)):+ return None+ return float(roc_auc_score(y, scores))+++@frozen+class GradedHeads:+ holdout_network: MultiHeadNetwork+ trained: list[NetworkHead]+ skipped: list[str]+++def _graded_heads(+ table: ExampleTable,+ inputs: NetworkInputs,+ heads: Sequence[Head],+ config: NetworkConfig,+ train_rows: np.ndarray,+) -> GradedHeads:+ """The train-only network, each head it can grade, and each head with nothing to fit."""+ all_rows = np.arange(len(inputs))+ holdout_network = _fit(inputs, heads, config, table.labels, train_rows)+ scores = holdout_network.predict(inputs, all_rows)+ rng = np.random.default_rng(config.seed)+ null_scores = []+ for draw in range(NULL_PERMUTATIONS):+ permuted = table.labels.copy()+ permuted[train_rows] = table.labels[rng.permutation(train_rows)]+ null_config = dataclasses.replace(config, seed=config.seed + draw)+ null_scores.append(_fit(inputs, heads, null_config, permuted, train_rows).predict(inputs, all_rows))++ trained: list[NetworkHead] = []+ skipped: list[str] = []+ for index, head in enumerate(heads):+ observed = ~np.isnan(table.labels[:, index])+ head_train = train_rows[observed[train_rows]]+ test = table.head_rows(index, holdout=True)+ y_train = table.labels[head_train, index].astype(int)+ if len(y_train) == 0 or y_train.sum() in (0, len(y_train)):+ skipped.append(head.name)+ continue+ y_test = table.labels[test, index].astype(int)+ null_aucs: list[float] = []+ if _auc(y_test, scores[test, index]) is not None:+ null_aucs = [auc for draws in null_scores if (auc := _auc(y_test, draws[test, index])) is not None]+ metrics, calibration = head_metrics(+ head,+ y_train=y_train,+ train_scores=scores[head_train, index],+ y_test=y_test,+ holdout_scores=scores[test, index],+ null_aucs=null_aucs,+ refit_positive_rate=float(table.labels[observed, index].mean()),+ holdout_team_ids=table.team_ids(test),+ )+ trained.append(NetworkHead(metrics=metrics, calibration=calibration))+ return GradedHeads(holdout_network=holdout_network, trained=trained, skipped=skipped)+++def train_network(+ table: ExampleTable, inputs: NetworkInputs, heads: Sequence[Head], config: NetworkConfig+) -> TrainedNetwork:+ """`heads` is the column order of `table`'s labels and of the graphs' output."""+ output_heads = tuple(head.name for head in heads)+ train_rows = table.network_train_rows()+ refit_rows = np.flatnonzero((~np.isnan(table.labels)).any(axis=1))+ graded = _graded_heads(table, inputs, heads, config, train_rows) if len(train_rows) else None+ trained = graded.trained if graded is not None else []+ skipped = graded.skipped if graded is not None else list(output_heads)+ model_onnx = holdout_model_onnx = None+ if graded is not None and trained:+ # Refit on everything before shipping: the holdout only exists to grade the recipe.+ model_onnx = _onnx_bytes(_fit(inputs, heads, config, table.labels, refit_rows))+ holdout_model_onnx = _onnx_bytes(graded.holdout_network)+ return TrainedNetwork(+ output_heads=output_heads,+ model_onnx=model_onnx,+ holdout_model_onnx=holdout_model_onnx,+ heads=tuple(trained),+ skipped=tuple(skipped),+ network_train_rows=len(train_rows),+ refit_rows=len(refit_rows),+ vector_kinds=VECTOR_KINDS if inputs.context is not None else (),+ )diff --git a/products/signals/dags/inbox_ranking/tests/test_multihead_network.py b/products/signals/dags/inbox_ranking/tests/test_multihead_network.pyindex 528c3812c6d2..d7fd2d67d6a5 100644--- a/products/signals/dags/inbox_ranking/tests/test_multihead_network.py+++ b/products/signals/dags/inbox_ranking/tests/test_multihead_network.py@@ -33,6 +33,7 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")import djangodjango.setup()import posthog.dags.locations.signals+import posthog.dags.locations.signals_mlimport products.signals.backend.temporalimport products.signals.backend.ranking.scorerimport products.signals.dags.inbox_ranking.multihead.localdiff --git a/products/signals/dags/inbox_ranking/tests/test_nn.py b/products/signals/dags/inbox_ranking/tests/test_nn.pynew file mode 100644index 000000000000..8c8cfe6ad937--- /dev/null+++ b/products/signals/dags/inbox_ranking/tests/test_nn.py@@ -0,0 +1,256 @@+import io+import json+import datetime+from typing import Any++import pytest++import numpy as np+import dagster+import pyarrow as pa+import pyarrow.parquet as pq+from botocore.exceptions import ClientError+from sklearn.metrics import roc_auc_score++from posthog import settings++from products.signals.backend.ranking.model_contract import model_mismatch+from products.signals.backend.ranking.model_store import ONNX_OUTPUT_HEADS_KEY+from products.signals.backend.ranking.overrides import NO_OVERRIDES+from products.signals.backend.ranking.serving_manifest import CROSS_FAMILY_ROLE, ONNX_MODEL_FILE, ONNX_MODEL_KIND+from products.signals.dags.inbox_ranking.common import partition_object_key+from products.signals.dags.inbox_ranking.dataset.dag import EMBEDDINGS_TABLE, LABELS_TABLE+from products.signals.dags.inbox_ranking.multihead.inputs import NetworkConfig+from products.signals.dags.inbox_ranking.multihead.local import report_vectors+from products.signals.dags.inbox_ranking.nn import dag as nn_dag+from products.signals.dags.inbox_ranking.nn.examples import (+ NN_HEAD_NAMES,+ build_examples,+ examples_arrow,+ network_inputs,+ subset,+)+from products.signals.dags.inbox_ranking.nn.model import (+ HOLDOUT_MODEL_FILE,+ NetworkHead,+ TrainedNetwork,+ candidate_metadata,+ onnx_probabilities,+)+from products.signals.dags.inbox_ranking.tests.test_multihead import D0, DAYS, HOLDOUT_DAYS, _SyntheticInbox+from products.signals.dags.inbox_ranking.training.dag import (+ CHAMPION_FILE,+ METADATA_FILE,+ champion_object_key,+ inbox_ranking_model_candidate,+ inbox_ranking_model_champion,+ model_object_key,+)+from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifest+from products.signals.dags.inbox_ranking.training.train import HeadMetrics+from products.signals.dags.inbox_ranking.training.unseen import (+ NN_MODEL_NAME,+ REPORT_EMBEDDINGS_MODEL_NAME,+ TITLE_EMBEDDINGS_MODEL_NAME,+)++PREFIX = settings.INBOX_RANKING_DATASET_S3_PREFIX+PARTITION = "2026-08-19"+NOW = datetime.datetime(2026, 8, 20, 6, tzinfo=datetime.UTC)+++class _S3:+ def __init__(self, objects: dict[str, bytes] | None = None):+ self.objects = dict(objects or {})++ def get_object(self, *, Bucket, Key):+ if Key not in self.objects:+ raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")+ return {"Body": io.BytesIO(self.objects[Key])}++ def put_object(self, *, Bucket, Key, Body, **kwargs):+ self.objects[Key] = Body++ def upload_fileobj(self, fileobj, bucket, key, ExtraArgs=None):+ self.objects[key] = fileobj.read()++ def get_paginator(self, _name):+ return self++ def paginate(self, *, Bucket, Prefix):+ yield {"Contents": [{"Key": key} for key in sorted(self.objects) if key.startswith(Prefix)]}++ def delete_objects(self, *, Bucket, Delete):+ for obj in Delete["Objects"]:+ self.objects.pop(obj["Key"])+++def _parquet(table: pa.Table) -> bytes:+ sink = io.BytesIO()+ pq.write_table(table, sink)+ return sink.getvalue()+++def _trained_network() -> TrainedNetwork:+ metrics = HeadMetrics(+ head="open",+ train_rows=400,+ train_positives=120,+ holdout_rows=200,+ holdout_positives=60,+ holdout_auc=0.8,+ null_auc=0.5,+ null_auc_std=0.01,+ readable=True,+ )+ return TrainedNetwork(+ output_heads=NN_HEAD_NAMES,+ model_onnx=b"graph",+ holdout_model_onnx=b"holdout-graph",+ heads=(NetworkHead(metrics=metrics, calibration=()),),+ skipped=(),+ network_train_rows=400,+ refit_rows=600,+ vector_kinds=(),+ )+++def _nn_metadata(version: str) -> dict[str, Any]:+ return candidate_metadata(+ version, _trained_network(), config=NetworkConfig(), windows={}, trained_at=NOW, run_id="run-1"+ )+++def _xgboost_metadata(model_name: str, version: str) -> dict[str, Any]:+ return {+ "model_name": model_name,+ "model_version": version,+ "heads": [{"head": "open", "readable": True, "holdout_auc": 0.7, "file": "open.ubj"}],+ "promoted_at": "2026-08-01T06:00:00+00:00",+ }+++def no_side_effects(monkeypatch: pytest.MonkeyPatch) -> None:+ for module in ("products.signals.dags.inbox_ranking.training.dag", "products.signals.dags.inbox_ranking.nn.dag"):+ monkeypatch.setattr(f"{module}.capture_training_events", lambda *args, **kwargs: None)+ monkeypatch.setattr(f"{module}.read_ranking_overrides", lambda now: NO_OVERRIDES, raising=False)+ monkeypatch.setattr(settings, "INBOX_RANKING_AUTO_PROMOTE", True)+++def test_the_main_location_never_fits_or_promotes_nn(monkeypatch, no_side_effects):+ # Every family has a candidate and no champion, so the main champion asset promotes each family+ # it walks. An `nn` pointer written here would name XGBoost files the sweep loads as ONNX.+ client = _S3(+ {+ model_object_key(PREFIX, name, PARTITION, METADATA_FILE): json.dumps(+ _xgboost_metadata(name, PARTITION)+ ).encode()+ for name in (REPORT_EMBEDDINGS_MODEL_NAME, TITLE_EMBEDDINGS_MODEL_NAME, NN_MODEL_NAME)+ }+ )+ monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: client)++ with dagster.build_asset_context(partition_key=PARTITION) as context:+ inbox_ranking_model_candidate(context)+ inbox_ranking_model_champion(context)++ champions = {key.split("/")[-2] for key in client.objects if key.endswith(CHAMPION_FILE)}+ assert champions == {REPORT_EMBEDDINGS_MODEL_NAME, TITLE_EMBEDDINGS_MODEL_NAME}+ assert not [key for key in client.objects if f"/{NN_MODEL_NAME}/" in key and not key.endswith(METADATA_FILE)]+++def test_the_manifest_carries_an_nn_champion_as_an_onnx_entry():+ decision = compose_manifest(+ [+ FamilyModels(+ name=REPORT_EMBEDDINGS_MODEL_NAME,+ candidate=None,+ champion=_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15"),+ ),+ FamilyModels(name=NN_MODEL_NAME, candidate=None, champion=_nn_metadata("2026-08-16")),+ ],+ served_family=REPORT_EMBEDDINGS_MODEL_NAME,+ prefix=PREFIX,+ now=NOW,+ )++ assert decision.manifest is not None+ (entry,) = [entry for entry in decision.manifest.models if entry.model_name == NN_MODEL_NAME]+ assert entry.roles == [CROSS_FAMILY_ROLE]+ assert entry.model_kind == ONNX_MODEL_KIND+ assert entry.files == [ONNX_MODEL_FILE]+ assert entry.heads == ["open"]+++def test_nn_promotion_writes_only_its_own_pointer(no_side_effects):+ other_champion = json.dumps(_xgboost_metadata(REPORT_EMBEDDINGS_MODEL_NAME, "2026-08-15")).encode()+ client = _S3(+ {+ model_object_key(PREFIX, NN_MODEL_NAME, PARTITION, METADATA_FILE): json.dumps(+ _nn_metadata(PARTITION)+ ).encode(),+ champion_object_key(PREFIX, REPORT_EMBEDDINGS_MODEL_NAME): other_champion,+ }+ )+ before = set(client.objects)++ with dagster.build_asset_context(partition_key=PARTITION) as context:+ nn_dag.decide_champion(context, client, "bucket", PARTITION)++ assert set(client.objects) - before == {champion_object_key(PREFIX, NN_MODEL_NAME)}+ assert client.objects[champion_object_key(PREFIX, REPORT_EMBEDDINGS_MODEL_NAME)] == other_champion+ assert json.loads(client.objects[champion_object_key(PREFIX, NN_MODEL_NAME)])["model_version"] == PARTITION+++def test_the_nn_candidate_writes_a_graph_whose_columns_follow_its_recorded_head_order(monkeypatch, no_side_effects):+ pytest.importorskip("torch")+ onnxruntime = pytest.importorskip("onnxruntime")+ monkeypatch.setattr(+ nn_dag, "NETWORK_CONFIG", NetworkConfig(projection_dim=8, trunk_dim=8, dropout=0.1, epochs=40, batch_size=32)+ )+ inbox = _SyntheticInbox()+ embeddings, labels = inbox.embeddings(), inbox.labels()+ extras = report_vectors(embeddings)+ examples = build_examples(inbox.snapshots(), extras, holdout_days=HOLDOUT_DAYS)+ day = (D0 + datetime.timedelta(days=DAYS - 1)).isoformat()+ client = _S3(+ {+ partition_object_key(PREFIX, nn_dag.NN_EXAMPLES_TABLE, day): _parquet(examples_arrow(examples)),+ partition_object_key(PREFIX, EMBEDDINGS_TABLE, day): _parquet(embeddings),+ partition_object_key(PREFIX, LABELS_TABLE, day): _parquet(labels),+ }+ )++ with dagster.build_asset_context(partition_key=day) as context:+ nn_dag.train_candidate(context, client, "bucket", day)++ metadata = json.loads(client.objects[model_object_key(PREFIX, NN_MODEL_NAME, day, METADATA_FILE)])+ assert metadata["model_kind"] == ONNX_MODEL_KIND+ assert metadata[ONNX_OUTPUT_HEADS_KEY] == list(NN_HEAD_NAMES)+ assert model_mismatch(metadata) is None+ assert {head["head"] for head in metadata["heads"]} == set(NN_HEAD_NAMES)+ assert {(head["file"], head["holdout_file"]) for head in metadata["heads"]} == {+ (ONNX_MODEL_FILE, HOLDOUT_MODEL_FILE)+ }+ served = onnxruntime.InferenceSession(+ client.objects[model_object_key(PREFIX, NN_MODEL_NAME, day, ONNX_MODEL_FILE)],+ providers=["CPUExecutionProvider"],+ )+ assert served.get_outputs()[0].shape[1] == len(metadata[ONNX_OUTPUT_HEADS_KEY])++ # Each head's column of the train-only graph, read through `output_heads`, must reproduce the+ # holdout AUC recorded for that head. A column read for the wrong head ranks at chance here.+ table = examples.table+ holdout = subset(table, np.flatnonzero(table.holdout.any(axis=1)))+ probabilities = onnx_probabilities(+ client.objects[model_object_key(PREFIX, NN_MODEL_NAME, day, HOLDOUT_MODEL_FILE)],+ network_inputs(holdout, extras, labels, embeddings),+ metadata[ONNX_OUTPUT_HEADS_KEY],+ )+ for head in metadata["heads"]:+ index = NN_HEAD_NAMES.index(head["head"])+ rows = holdout.head_rows(index, holdout=True)+ auc = roc_auc_score(holdout.labels[rows, index], probabilities[head["head"]][rows])+ assert auc == pytest.approx(head["holdout_auc"], abs=1e-4)+ assert auc > 0.75diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.pyindex cc3d6cac8b87..96f986639f74 100644--- a/products/signals/dags/inbox_ranking/training/dag.py+++ b/products/signals/dags/inbox_ranking/training/dag.py@@ -25,11 +25,12 @@ promotion rule compares both models on one set of reports. Every model object sifamily's `model_name`, and promotion stays inside a family: a richer family is a second candidategraded on the same rows, not a competitor for another family's pointer.-Both the candidate and the champion asset walk `MODEL_FAMILIES`, so each family trains on the+Both the candidate and the champion asset walk `families_trained_in(MAIN_LOCATION)`, so each family trains on theexamples of the feature set it declares and decides against its own pointer. A family whoseexamples or metadata are missing that day is logged and skipped: its own series has a gap, andevery other family still trains, promotes and gets graded. The two embedding families read one textrendering each, from separate snapshots, so a missing snapshot costs one family and not the pair.+The `nn` family is trained by the `signals_ml` location (`nn/dag.py`) and never here.Two further assets grade the served models on data no example covers. `inbox_ranking_served_scores`(`training/served.py`) reads the scoring sweep's live scores of every report born on D, one row set@@ -43,7 +44,7 @@ same `Head` cohort, label and horizon.import jsonimport datetime-from collections.abc import Mapping, Sequence+from collections.abc import Callable, Mapping, Sequencefrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Any@@ -141,11 +142,13 @@ from products.signals.dags.inbox_ranking.training.train import (train_head,)from products.signals.dags.inbox_ranking.training.unseen import (+ MAIN_LOCATION,MODEL_FAMILIES,SERVED_SCORES_TABLE,HeadGrade,ModelFamily,calibration_rows,+ families_trained_in,graded_rows,head_grades,missing_label_columns,@@ -609,7 +612,7 @@ def inbox_ranking_model_candidate(context: dagster.AssetExecutionContext) -> Nonbucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()metadata: dict[str, dagster.MetadataValue] = {}- for family in MODEL_FAMILIES:+ for family in families_trained_in(MAIN_LOCATION):metadata |= _train_candidate(context, client, bucket, prefix, partition_key, family)context.add_output_metadata(metadata)@@ -729,7 +732,7 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> Noneoverrides = read_ranking_overrides(datetime.datetime.now(datetime.UTC))metadata: dict[str, dagster.MetadataValue] = {}decided = 0- for family in MODEL_FAMILIES:+ for family in families_trained_in(MAIN_LOCATION):family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family, overrides)if family_metadata is None:continue@@ -750,9 +753,62 @@ def _decide_champion(partition_key: str,family: ModelFamily,overrides: RankingOverrides,+) -> dict[str, dagster.MetadataValue] | None:+ """One per-head XGBoost family's promotion decision against its own pointer, or None when the+ family has no candidate for the partition."""++ def grade_champion(champion: Mapping[str, Any]) -> dict[str, HoldoutGrade]:+ champion_feature_set = model_feature_set(champion)+ if champion_feature_set is None:+ context.log.warning(+ f"{family.name} champion {champion['model_version']} reads a feature set this build cannot produce"+ )+ return {}+ # The champion is graded on the examples of its own feature set, the set the candidate+ # shares: promotion stays inside a family. Without that object there is no shared+ # holdout, so the rule falls back to the champion's stored AUC.+ examples = read_parquet_if_exists(+ client, bucket, examples_object_key(prefix, champion_feature_set.name, partition_key)+ )+ if examples is None:+ context.log.warning(+ f"no {champion_feature_set.name} examples for dt={partition_key}; "+ f"the {family.name} champion is compared on its stored AUC"+ )+ return {}+ return paired_champion_grades(+ client,+ bucket,+ prefix,+ dict(champion),+ examples.to_pandas(),+ feature_set=champion_feature_set,+ holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,+ )++ return decide_family_champion(+ context, client, bucket, prefix, partition_key, family, overrides, grade_champion=grade_champion+ )+++def decide_family_champion(+ context: dagster.AssetExecutionContext,+ client,+ bucket: str,+ prefix: str,+ partition_key: str,+ family: ModelFamily,+ overrides: RankingOverrides,+ *,+ grade_champion: Callable[[Mapping[str, Any]], dict[str, HoldoutGrade]],) -> dict[str, dagster.MetadataValue] | None:"""One family's promotion decision against its own pointer, or None when the family has no- candidate for the partition."""+ candidate for the partition.++ `grade_champion` grades the incumbent's train-only fit on the candidate's holdout, in the+ family's own learner. Every family shares the rest, so one rule, one override and one+ `INBOX_RANKING_AUTO_PROMOTE` gate decide every pointer.+ """candidate = _read_json_if_exists(client, bucket, model_object_key(prefix, family.name, partition_key, METADATA_FILE))@@ -765,43 +821,18 @@ def _decide_champion(champion_aucs: dict[str, float] = {}champion_eces: dict[str, float] = {}if champion is not None:- champion_feature_set = model_feature_set(champion)- if champion_feature_set is None:- context.log.warning(- f"{family.name} champion {champion['model_version']} reads a feature set this build cannot produce"- )- else:- # The champion is graded on the examples of its own feature set, the set the candidate- # shares: promotion stays inside a family. Without that object there is no shared- # holdout, so the rule falls back to the champion's stored AUC.- examples = read_parquet_if_exists(- client, bucket, examples_object_key(prefix, champion_feature_set.name, partition_key)+ champion_grades = grade_champion(champion)+ champion_aucs = {head: grade.auc for head, grade in champion_grades.items() if grade.auc is not None}+ champion_eces = {+ head: grade.expected_calibration_error+ for head, grade in champion_grades.items()+ if grade.expected_calibration_error is not None+ }+ if champion_grades:+ context.log.info(+ f"{family.name} champion {champion['model_version']} on this holdout: "+ f"AUC {champion_aucs}, ECE {champion_eces}")- if examples is None:- context.log.warning(- f"no {champion_feature_set.name} examples for dt={partition_key}; "- f"the {family.name} champion is compared on its stored AUC"- )- else:- champion_grades = paired_champion_grades(- client,- bucket,- prefix,- champion,- examples.to_pandas(),- feature_set=champion_feature_set,- holdout_days=settings.INBOX_RANKING_TRAINING_HOLDOUT_DAYS,- )- champion_aucs = {head: grade.auc for head, grade in champion_grades.items() if grade.auc is not None}- champion_eces = {- head: grade.expected_calibration_error- for head, grade in champion_grades.items()- if grade.expected_calibration_error is not None- }- context.log.info(- f"{family.name} champion {champion['model_version']} on this holdout: "- f"AUC {champion_aucs}, ECE {champion_eces}"- )promotion_override = overrides.promotion_for(family.name)decision = decide_promotion(candidate,@@ -844,7 +875,7 @@ def _decide_champion([promotion_event(partition_key=partition_key,- run_id=context.run.run_id,+ run_id=context.run_id,model_name=family.name,decision=decision,outcome=outcome,diff --git a/products/signals/dags/inbox_ranking/training/train.py b/products/signals/dags/inbox_ranking/training/train.pyindex 33bdbee9c03d..5e9ae18059c1 100644--- a/products/signals/dags/inbox_ranking/training/train.py+++ b/products/signals/dags/inbox_ranking/training/train.py@@ -159,6 +159,54 @@ def _head_readable(return holdout_positives >= min_positives and holdout_auc > 0.5 and holdout_auc - null_auc >= NULL_MARGIN+def head_metrics(+ head: Head,+ *,+ y_train: np.ndarray,+ train_scores: np.ndarray,+ y_test: np.ndarray,+ holdout_scores: np.ndarray,+ null_aucs: Sequence[float],+ refit_positive_rate: float,+ holdout_team_ids: np.ndarray,+) -> tuple[HeadMetrics, tuple[CalibrationBucket, ...]]:+ """One head's metrics and holdout calibration from the scores of its train-only fit.++ Every learner grades a head through this function, so the families' metadata carry the same+ fields with the same meaning, and one promotion rule reads them all. `null_aucs` are the holdout+ AUCs of the learner's fits on permuted labels.+ """+ holdout_auc = _auc(y_test, holdout_scores) if len(y_test) else None+ null_auc = float(np.mean(null_aucs)) if null_aucs else None+ null_auc_std = float(np.std(null_aucs)) if null_aucs else None+ readable = _head_readable(holdout_auc, null_auc, int(y_test.sum()), min_positives=head.min_holdout_positives)+ calibration = calibration_buckets(y_test.astype(bool), holdout_scores)+ metrics = HeadMetrics(+ head=head.name,+ train_rows=int(len(y_train)),+ train_positives=int(y_train.sum()),+ holdout_rows=int(len(y_test)),+ holdout_positives=int(y_test.sum()),+ holdout_auc=holdout_auc,+ null_auc=null_auc,+ null_auc_std=null_auc_std,+ readable=readable,+ train_auc=_auc(y_train, train_scores),+ holdout_average_precision=(+ float(average_precision_score(y_test, holdout_scores)) if holdout_auc is not None else None+ ),+ # Logloss is defined on a single-class holdout, unlike AUC and average precision.+ holdout_logloss=float(log_loss(y_test, holdout_scores, labels=[0, 1])) if len(y_test) else None,+ holdout_positive_rate=float(y_test.mean()) if len(y_test) else None,+ holdout_mean_score=float(holdout_scores.mean()) if len(y_test) else None,+ holdout_expected_calibration_error=expected_calibration_error(calibration),+ holdout_classification=classification_metrics(y_test, holdout_scores, float(y_train.mean())),+ refit_classification_threshold=refit_positive_rate,+ holdout_within_team=within_team_auc(y_test, holdout_scores, holdout_team_ids),+ )+ return metrics, calibration++def train_head(examples: pd.DataFrame, head: Head, *, feature_names: Sequence[str], holdout_days: int, seed: int = 0) -> TrainedHead | None:@@ -175,12 +223,10 @@ def train_head(return Nonemodel = _fit(x_train, y_train, seed)- train_auc = _auc(y_train, model.predict_proba(x_train)[:, 1])holdout_scores = model.predict_proba(x_test)[:, 1] if len(y_test) else np.array([])holdout_auc = _auc(y_test, holdout_scores) if len(y_test) else None- null_auc: float | None = None- null_auc_std: float | None = None+ null_aucs: list[float] = []if holdout_auc is not None:rng = np.random.default_rng(seed)null_aucs = [@@ -189,34 +235,16 @@ def train_head(if (auc := _auc(y_test, _fit(x_train, rng.permutation(y_train), seed + draw).predict_proba(x_test)[:, 1]))is not None]- if null_aucs:- null_auc = float(np.mean(null_aucs))- null_auc_std = float(np.std(null_aucs))- readable = _head_readable(holdout_auc, null_auc, int(y_test.sum()), min_positives=head.min_holdout_positives)- calibration = calibration_buckets(y_test.astype(bool), holdout_scores)- metrics = HeadMetrics(- head=head.name,- train_rows=int(len(y_train)),- train_positives=int(y_train.sum()),- holdout_rows=int(len(y_test)),- holdout_positives=int(y_test.sum()),- holdout_auc=holdout_auc,- null_auc=null_auc,- null_auc_std=null_auc_std,- readable=readable,- train_auc=train_auc,- holdout_average_precision=(- float(average_precision_score(y_test, holdout_scores)) if holdout_auc is not None else None- ),- # Logloss is defined on a single-class holdout, unlike AUC and average precision.- holdout_logloss=float(log_loss(y_test, holdout_scores, labels=[0, 1])) if len(y_test) else None,- holdout_positive_rate=float(y_test.mean()) if len(y_test) else None,- holdout_mean_score=float(holdout_scores.mean()) if len(y_test) else None,- holdout_expected_calibration_error=expected_calibration_error(calibration),- holdout_classification=classification_metrics(y_test, holdout_scores, float(y_train.mean())),- refit_classification_threshold=float(y.mean()),- holdout_within_team=within_team_auc(y_test, holdout_scores, _team_ids(rows)[test]),+ metrics, calibration = head_metrics(+ head,+ y_train=y_train,+ train_scores=model.predict_proba(x_train)[:, 1],+ y_test=y_test,+ holdout_scores=holdout_scores,+ null_aucs=null_aucs,+ refit_positive_rate=float(y.mean()),+ holdout_team_ids=_team_ids(rows)[test],)# Refit on everything before shipping: the holdout only exists to grade the recipe.final = _fit(x, y, seed)@@ -242,6 +270,15 @@ class HoldoutGrade:positives: int+def holdout_grade(y: np.ndarray, scores: np.ndarray) -> HoldoutGrade:+ """A saved model's AUC and calibration error on a candidate's holdout outcomes `y`."""+ return HoldoutGrade(+ auc=_auc(y, scores),+ expected_calibration_error=expected_calibration_error(calibration_buckets(y.astype(bool), scores)),+ positives=int(y.sum()),+ )++def booster_holdout_grade(booster_ubj: bytes, examples: pd.DataFrame, head: Head, *, feature_names: Sequence[str], holdout_days: int) -> HoldoutGrade | None:@@ -263,9 +300,4 @@ def booster_holdout_grade(return Nonex = rows.loc[test, names].astype(np.float32)y = rows.loc[test, "label"].to_numpy(dtype=int)- scores = booster.predict(xgb.DMatrix(x, feature_names=names))- return HoldoutGrade(- auc=_auc(y, scores),- expected_calibration_error=expected_calibration_error(calibration_buckets(y.astype(bool), scores)),- positives=int(y.sum()),- )+ return holdout_grade(y, booster.predict(xgb.DMatrix(x, feature_names=names)))diff --git a/products/signals/dags/inbox_ranking/training/unseen.py b/products/signals/dags/inbox_ranking/training/unseen.pyindex 79367de7dfb0..bbc06015ac0e 100644--- a/products/signals/dags/inbox_ranking/training/unseen.py+++ b/products/signals/dags/inbox_ranking/training/unseen.py@@ -27,6 +27,7 @@ from products.signals.backend.ranking.features import (TITLE_EMBEDDINGS_FEATURE_SET,FeatureSet,)+from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ONNX_MODEL_KINDfrom products.signals.dags.inbox_ranking.training.calibration import (CalibrationBucket,bucket_rows,@@ -60,6 +61,11 @@ CANDIDATE_ROLE = "candidate"# it was fit on. Both are in the identity, so two families trained on one day stay apart.REPORT_EMBEDDINGS_MODEL_NAME = "report_embeddings"TITLE_EMBEDDINGS_MODEL_NAME = "title_embeddings"+NN_MODEL_NAME = "nn"+# The Dagster code locations that train a family: `signals` on the main image, and `signals_ml` on+# the image that carries torch.+MAIN_LOCATION = "signals"+ML_LOCATION = "signals_ml"# Families this build no longer trains. Saved scores objects still hold their rows, so every reader# drops them through `with_model_names`: the grades stop with the family, and the rewrite guard does# not require rows that no re-run can produce.@@ -98,24 +104,39 @@ SCORE_COLUMNS = tuple(_SCORE_TYPES)@frozenclass ModelFamily:- """One family the training job fits: its name, and the feature set its trainer fits. Every- family is per-head XGBoost, so the learner is not a field yet."""+ """One family the training jobs fit: its name, the feature set it is fit on, the learner a+ model store loads it with, and the Dagster code location whose assets train it."""name: strfeature_set: FeatureSet+ learner: str = DEFAULT_MODEL_KIND+ location: str = MAIN_LOCATION-# The families the training job trains, in the order they are trained. A+# The families the training jobs train, in the order they are trained. A# family with no metadata for the day is skipped, so an entry can be added here before its trainer# writes its first candidate, and a family that fails costs its own series rather than every one.# The two embedding families read one `ReportEmbeddingsFeatureSet` instance each and fit with the# same module-level `XGB_PARAMS`, so their width, grain, row budget, sampling, split and booster# settings match by construction. Keep it that way: the pair is a measurement of the text choice,# and a recipe that differed between them would answer a question nobody asked.+# `nn` is one multi-head network over the report vector and the team's project vectors. It needs+# torch, so the `signals_ml` location trains it and the main location never fits it. It declares+# the report embeddings set, because that set builds its report input in training and at serving.MODEL_FAMILIES: tuple[ModelFamily, ...] = (ModelFamily(name=REPORT_EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),ModelFamily(name=TITLE_EMBEDDINGS_MODEL_NAME, feature_set=TITLE_EMBEDDINGS_FEATURE_SET),+ ModelFamily(+ name=NN_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET, learner=ONNX_MODEL_KIND, location=ML_LOCATION+ ),)+NN_FAMILY = next(family for family in MODEL_FAMILIES if family.name == NN_MODEL_NAME)+++def families_trained_in(location: str) -> tuple[ModelFamily, ...]:+ """The families whose candidate and champion assets live in `location`. The serving manifest+ and the online grader walk every family, so a family gains both wherever it trains."""+ return tuple(family for family in MODEL_FAMILIES if family.location == location)@frozen