ltr 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/ARCHITECTURE.md +92 -0
- data/CHANGELOG.md +5 -0
- data/LICENSE +21 -0
- data/README.md +186 -0
- data/docs/AGENTS.md +67 -0
- data/docs/aggregation-engines.md +80 -0
- data/docs/config.md +516 -0
- data/docs/data-contracts.md +94 -0
- data/docs/data-splits.md +34 -0
- data/docs/dataset-builder-steps.md +13 -0
- data/docs/dataset-csv.md +73 -0
- data/docs/dataset-enrichers.md +62 -0
- data/docs/errors.md +33 -0
- data/docs/feature-selection.md +108 -0
- data/docs/features.md +202 -0
- data/docs/glossary.md +56 -0
- data/docs/host-integration.md +128 -0
- data/docs/host-run-pipelines.md +48 -0
- data/docs/index.md +50 -0
- data/docs/inference.md +164 -0
- data/docs/label-transformers.md +242 -0
- data/docs/labels-from-behavior.md +94 -0
- data/docs/learning-to-rank.md +119 -0
- data/docs/metrics.md +166 -0
- data/docs/model-files.md +73 -0
- data/docs/optimization.md +72 -0
- data/docs/public-api.md +67 -0
- data/docs/rake-tasks.md +82 -0
- data/docs/relevance-grades.md +80 -0
- data/docs/run-locally.md +584 -0
- data/docs/run-on-aws.md +647 -0
- data/docs/training-objective.md +110 -0
- data/docs/ubi-documents.md +75 -0
- data/docs/ubi-logging.md +125 -0
- data/lib/ltr/README.md +28 -0
- data/lib/ltr/configuration/README.md +12 -0
- data/lib/ltr/configuration/config_loader.rb +326 -0
- data/lib/ltr/configuration/config_validator.rb +476 -0
- data/lib/ltr/configuration/configuration.rb +84 -0
- data/lib/ltr/configuration/example_config.yml +182 -0
- data/lib/ltr/data/README.md +20 -0
- data/lib/ltr/data/csv/README.md +9 -0
- data/lib/ltr/data/csv/typed_columns.rb +101 -0
- data/lib/ltr/data/csv.rb +126 -0
- data/lib/ltr/data/dataframe.rb +80 -0
- data/lib/ltr/data/dataset_loader.rb +29 -0
- data/lib/ltr/data/row_store.rb +188 -0
- data/lib/ltr/data/split_cache.rb +30 -0
- data/lib/ltr/data/splits.rb +86 -0
- data/lib/ltr/dataset_aggregation/README.md +32 -0
- data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
- data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
- data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
- data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
- data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
- data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
- data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
- data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
- data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
- data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
- data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
- data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
- data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
- data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
- data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
- data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
- data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
- data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
- data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
- data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
- data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
- data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
- data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
- data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
- data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
- data/lib/ltr/deploy/README.md +21 -0
- data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
- data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
- data/lib/ltr/deploy/feature_extractor.rb +94 -0
- data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
- data/lib/ltr/deploy/local_deployer.rb +61 -0
- data/lib/ltr/deploy/model_packager.rb +90 -0
- data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
- data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
- data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
- data/lib/ltr/errors/README.md +16 -0
- data/lib/ltr/errors/configuration_error.rb +5 -0
- data/lib/ltr/errors/deploy_error.rb +5 -0
- data/lib/ltr/errors/error.rb +5 -0
- data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
- data/lib/ltr/errors/missing_dependency_error.rb +5 -0
- data/lib/ltr/errors/sqlite_error.rb +14 -0
- data/lib/ltr/features/README.md +19 -0
- data/lib/ltr/features/encoders/README.md +10 -0
- data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
- data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
- data/lib/ltr/features/feature_engineering.rb +194 -0
- data/lib/ltr/features/feature_transformer.rb +92 -0
- data/lib/ltr/features/float32_range.rb +20 -0
- data/lib/ltr/features/transform_steps.rb +34 -0
- data/lib/ltr/features/transform_store.rb +123 -0
- data/lib/ltr/inference/README.md +11 -0
- data/lib/ltr/inference/base.rb +52 -0
- data/lib/ltr/inference/local_reranker.rb +147 -0
- data/lib/ltr/inference/sagemaker_client.rb +62 -0
- data/lib/ltr/metrics/README.md +12 -0
- data/lib/ltr/metrics/metric_scores.rb +67 -0
- data/lib/ltr/metrics/metrics.rb +139 -0
- data/lib/ltr/optimize/README.md +25 -0
- data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
- data/lib/ltr/optimize/candidate_selector.rb +97 -0
- data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
- data/lib/ltr/optimize/expected_improvement.rb +33 -0
- data/lib/ltr/optimize/feature_selection/README.md +15 -0
- data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
- data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
- data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
- data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
- data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
- data/lib/ltr/optimize/gaussian_process.rb +125 -0
- data/lib/ltr/optimize/optimization_dataset.rb +16 -0
- data/lib/ltr/optimize/optimize_features.rb +129 -0
- data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
- data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
- data/lib/ltr/optimize/search_space.rb +165 -0
- data/lib/ltr/optimize/update_config.rb +196 -0
- data/lib/ltr/ssm/README.md +11 -0
- data/lib/ltr/ssm/loader.rb +61 -0
- data/lib/ltr/ssm/parameter_paths.rb +19 -0
- data/lib/ltr/ssm/saver.rb +76 -0
- data/lib/ltr/support/README.md +13 -0
- data/lib/ltr/support/callable.rb +10 -0
- data/lib/ltr/support/optional_dependency.rb +31 -0
- data/lib/ltr/support/pipeline_result.rb +22 -0
- data/lib/ltr/support/pipeline_task.rb +81 -0
- data/lib/ltr/support/version.rb +7 -0
- data/lib/ltr/tasks/ltr.rake +24 -0
- data/lib/ltr/train/README.md +19 -0
- data/lib/ltr/train/deploy_gate.rb +77 -0
- data/lib/ltr/train/deploy_metric.rb +63 -0
- data/lib/ltr/train/eval_logger.rb +16 -0
- data/lib/ltr/train/evaluation_cache.rb +101 -0
- data/lib/ltr/train/modelling_pipeline.rb +82 -0
- data/lib/ltr/train/optimization_split_report.rb +54 -0
- data/lib/ltr/train/utils.rb +35 -0
- data/lib/ltr/train/xgb_evaluator.rb +96 -0
- data/lib/ltr/train/xgb_trainer.rb +154 -0
- data/lib/ltr/ubi.rb +86 -0
- data/lib/ltr.rb +61 -0
- data/scripts/seed_ubi.rb +75 -0
- metadata +346 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Training objective
|
|
2
|
+
|
|
3
|
+
The gem trains with XGBoost's `rank:ndcg` objective, which is LambdaMART. By the end of this page, you will know how LambdaMART weights its training pairs, which hyperparameters shape that weighting, and why the labels require `ndcg_exp_gain: false`. [Learning to rank](learning-to-rank.md#query-groups-qid) shows how the pairs come from `qid` groups.
|
|
4
|
+
|
|
5
|
+
## Glossary
|
|
6
|
+
|
|
7
|
+
| Term | Meaning |
|
|
8
|
+
|---|---|
|
|
9
|
+
| DCG, IDCG | Discounted Cumulative Gain adds up each document's gain times `1 / log2(rank + 1)`. IDCG is the DCG of the best possible (or Ideal) order for the query. |
|
|
10
|
+
| Gain | The amount a document adds to DCG before the rank discount. With `ndcg_exp_gain: false`, as in the shipped config, the gain is the label. Otherwise it is `2^label - 1`. |
|
|
11
|
+
| Hyperparameter | A training setting that the model does not learn from the data, such as `max_depth` or `learning_rate`. The config keeps them under `model.hyperparameters`. `ltr:optimize` searches for better values. |
|
|
12
|
+
| `label` | The target value for training the model. |
|
|
13
|
+
| LambdaMART | The pairwise ranking method behind the XGBoost `rank:ndcg` objective. |
|
|
14
|
+
| NDCG | Normalized DCG, which is DCG divided by IDCG. It runs from 0 to 1. |
|
|
15
|
+
| `qid` | The id of one query group. The gem numbers the kept groups from 1 with no gaps, after `min_documents_per_query` drops the small ones. |
|
|
16
|
+
| XGBoost | The gradient-boosted tree library that trains the model and scores the candidates. The gem uses its `rank:ndcg` objective. |
|
|
17
|
+
|
|
18
|
+
The full list is in the [glossary](glossary.md).
|
|
19
|
+
|
|
20
|
+
## DCG, discount and IDCG
|
|
21
|
+
|
|
22
|
+
DCG adds up each document's gain times the discount of its rank. The discount depends only on the rank.
|
|
23
|
+
|
|
24
|
+
```math
|
|
25
|
+
\mathrm{discount}(i) = \frac{1}{\log_2(i + 1)}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
- $`i`$ is the rank of a document in the query, starting at 1.
|
|
29
|
+
|
|
30
|
+
The discount is 1.0 at rank 1 and gets smaller at each rank below it, so a document counts less the lower it sits. NDCG divides DCG by IDCG, so it runs from 0 to 1. With the shipped `ndcg_exp_gain: false`, the gain of a document is its label. [Metrics](metrics.md#formulas) has the full formulas.
|
|
31
|
+
|
|
32
|
+
In the example below, the diagram scores one made-up query with three documents. The model puts Fish oil first, although Vitamin D3 has the highest label. Each line shows a document's label times the discount of its rank.
|
|
33
|
+
|
|
34
|
+
```mermaid
|
|
35
|
+
---
|
|
36
|
+
config:
|
|
37
|
+
flowchart:
|
|
38
|
+
wrappingWidth: 480
|
|
39
|
+
---
|
|
40
|
+
flowchart TB
|
|
41
|
+
M["<b>Model order</b><br>1. Fish oil (0.2) × 1.0000 = 0.2000<br>2. Vitamin D3 (0.8) × 0.6309 = 0.5047<br>3. Vitamin D3 with K2 (0.5) × 0.5000 = 0.2500"] --> DCG["DCG = 0.9547"]
|
|
42
|
+
I["<b>Best order</b><br>1. Vitamin D3 (0.8) × 1.0000 = 0.8000<br>2. Vitamin D3 with K2 (0.5) × 0.6309 = 0.3155<br>3. Fish oil (0.2) × 0.5000 = 0.1000"] --> IDCG["IDCG = 1.2155"]
|
|
43
|
+
DCG --> N["NDCG = 0.9547 / 1.2155 = 0.7855"]
|
|
44
|
+
IDCG --> N
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## How LambdaMART weights a pair
|
|
48
|
+
|
|
49
|
+
For each query, LambdaMART pairs up documents that share a `qid` and have different labels. Each boosting round adds a tree fitted to the gradients of these pairs. For each pair, the gradient step raises the `score` of the document with the higher label and lowers the `score` of the other one. LambdaMART weights each pair by how much NDCG would change if the two documents swapped places, so it compares documents two at a time but takes each weight from the whole ranked list. The [XGBoost learning-to-rank tutorial](https://xgboost.readthedocs.io/en/stable/tutorials/learning_to_rank.html) describes the objective and its parameters.
|
|
50
|
+
|
|
51
|
+
The change in NDCG for a pair comes from the labels of the two documents, the ranks the model gave them and the IDCG of their query.
|
|
52
|
+
|
|
53
|
+
```math
|
|
54
|
+
\Delta\mathrm{NDCG}_{ab} = \frac{\left| \mathrm{gain}(\ell_a) - \mathrm{gain}(\ell_b) \right| \cdot \left| \mathrm{discount}(i_a) - \mathrm{discount}(i_b) \right|}{\mathrm{IDCG}}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- $`a`$ and $`b`$ are the two documents of the pair.
|
|
58
|
+
- $`\ell_a`$ and $`\ell_b`$ are their labels, and $`\mathrm{gain}`$ is the label itself with the shipped `ndcg_exp_gain: false`.
|
|
59
|
+
- $`i_a`$ and $`i_b`$ are their ranks in the model's order.
|
|
60
|
+
- $`\mathrm{IDCG}`$ is the IDCG of their query.
|
|
61
|
+
|
|
62
|
+
A pair gets more weight when the gap between its labels is larger, and when the gap between the discounts of its two ranks is larger. The chart shows the discount for ranks 1 to 20. It falls fastest at the top of the list.
|
|
63
|
+
|
|
64
|
+
```mermaid
|
|
65
|
+
---
|
|
66
|
+
config:
|
|
67
|
+
xyChart:
|
|
68
|
+
height: 320
|
|
69
|
+
themeVariables:
|
|
70
|
+
xyChart:
|
|
71
|
+
plotColorPalette: "#2f6b4f"
|
|
72
|
+
---
|
|
73
|
+
xychart-beta
|
|
74
|
+
title "Discount by rank"
|
|
75
|
+
x-axis "Rank" [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
|
|
76
|
+
y-axis "Discount" 0 --> 1
|
|
77
|
+
bar [1.00, 0.63, 0.50, 0.43, 0.39, 0.36, 0.33, 0.32, 0.30, 0.29, 0.28, 0.27, 0.26, 0.26, 0.25, 0.24, 0.24, 0.24, 0.23, 0.23]
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The discount drops by 0.3691 from rank 1 to rank 2, but by only 0.0037 from rank 19 to rank 20. So the same mistake costs far more near the top. In the example below, a made-up query has 20 documents with these labels in model order:
|
|
81
|
+
|
|
82
|
+
`0.2, 0.8, 0.7, 0.7, 0.6, 0.6, 0.5, 0.5, 0.5, 0.4, 0.4, 0.4, 0.4, 0.3, 0.3, 0.3, 0.3, 0.3, 0.2, 0.8`
|
|
83
|
+
|
|
84
|
+
The model makes the same mistake twice. It puts a 0.2 document above a 0.8 document at ranks 1 and 2, and again at ranks 19 and 20. IDCG for this query is 3.7769. The table swaps each pair in turn.
|
|
85
|
+
|
|
86
|
+
| Order | DCG | NDCG | Change in NDCG |
|
|
87
|
+
|---|---|---|---|
|
|
88
|
+
| As the model ranked it | 3.3135 | 0.8773 | |
|
|
89
|
+
| Ranks 1 and 2 swapped | 3.5349 | 0.9359 | +0.0586 |
|
|
90
|
+
| Ranks 19 and 20 swapped | 3.3157 | 0.8779 | +0.0006 |
|
|
91
|
+
|
|
92
|
+
Both pairs have the same label gap of 0.6, so the gap between their discounts sets their weights, and the top pair gets about 100 times the weight of the bottom pair. In the shipped config, the bottom pair gets no gradient at all, because `lambdarank_num_pair_per_sample: 12` only builds pairs that involve the top 12 positions, as the table below explains.
|
|
93
|
+
|
|
94
|
+
## Hyperparameters
|
|
95
|
+
|
|
96
|
+
These keys shape how LambdaMART weights its pairs. The gem passes them to XGBoost as they are, so a key that is left out takes XGBoost's default, which the [XGBoost parameter list](https://xgboost.readthedocs.io/en/stable/parameter.html#parameters-for-learning-to-rank-rank-ndcg-rank-map-rank-pairwise) gives. [Config](config.md#model) describes the rest of the `model` section.
|
|
97
|
+
|
|
98
|
+
| Key | Shipped value | Effect |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| `model.hyperparameters.objective` | `rank:ndcg` | Picks LambdaMART, with NDCG as the target. |
|
|
101
|
+
| `model.hyperparameters.ndcg_exp_gain` | `false` | Sets the gain of a document. When `false`, the gain is its label. When `true`, the gain is $`2^{\mathrm{label}} - 1`$. |
|
|
102
|
+
| `model.hyperparameters.lambdarank_num_pair_per_sample` | `12` | The gem keeps XGBoost's default `lambdarank_pair_method: topk`. Under `topk` this is a cutoff, not a sample size. Only pairs that involve the top positions up to the cutoff get a gradient. |
|
|
103
|
+
| `model.hyperparameters.lambdarank_unbiased` | `true` | When `true`, turns on XGBoost's position-debiasing option. XGBoost uses each row's index inside its query group as the position, and only for the first `lambdarank_num_pair_per_sample` rows. The gem sorts each group by `original_position` before training, and rows with no position come last. The index equals the display position minus 1 only for a group from one session with no gaps. A merged group holds several sessions, so its indices run past the display positions. |
|
|
104
|
+
| `model.hyperparameters.eval_metric` | `ndcg@12` | The metric that early stopping watches. |
|
|
105
|
+
|
|
106
|
+
## Linear gain for decimal labels
|
|
107
|
+
|
|
108
|
+
Exponential gain is meant for whole-number grades such as 0 to 4, where $`2^{\mathrm{label}} - 1`$ makes a perfect result worth far more than a good one. XGBoost rejects fractional labels when `ndcg_exp_gain` is `true`, with the error "label must be either 0 or positive integer". The gem's labels are continuous decimals, because each one is built from smoothed view, add-to-cart and purchase rates, as [Labels from behavior](labels-from-behavior.md) explains. So `ndcg_exp_gain: false` is a requirement, not a preference.
|
|
109
|
+
|
|
110
|
+
With linear gain, the label gap in the $`\Delta\mathrm{NDCG}`$ formula above is the plain difference of the two labels, so the weight of a pair grows in proportion to its label gap. In the [`qid` example](learning-to-rank.md#query-groups-qid), the Magnesium glycinate and Zinc pair has labels 0.8 apart. It counts more than a pair with labels 0.3 apart, such as Vitamin D3 and Vitamin D3 with K2, when both pairs sit at the same two ranks of queries with the same IDCG.
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# UBI documents
|
|
2
|
+
|
|
3
|
+
This page gives the contract for the [User Behavior Insights](https://docs.opensearch.org/latest/search-plugins/ubi/index/) (UBI) query and event documents that the dataset pipeline reads from OpenSearch. It covers the two indices and their mappings, which documents the loader reads, and the rule the pipeline applies to each field. [Logging UBI documents](ubi-logging.md) shows how `Ltr::Ubi` writes them.
|
|
4
|
+
|
|
5
|
+
## Glossary
|
|
6
|
+
|
|
7
|
+
| Term | Meaning |
|
|
8
|
+
|---|---|
|
|
9
|
+
| Cascade action | A configured action other than `impression`. The loaders read only the events of cascade actions, and the cascade cutoff uses only them. |
|
|
10
|
+
| Configured action | An action that a `dataset_builder.conversion_rate_targets` entry names as a `numerator` or a `denominator`. The `_count` suffix is left off the name, so `view_count` gives the action `view`. `impression` is a configured action when a rate target names `impression_count`. |
|
|
11
|
+
| Hit ids | The list of doc ids that one search showed, in the order the page showed them. The loader reads it from the field that `dataset_builder.hit_ids_field` names, which defaults to `query_response_hit_ids`. A doc's position is its place in that list, counted from 1. |
|
|
12
|
+
|
|
13
|
+
## Required field types
|
|
14
|
+
|
|
15
|
+
The pipeline reads queries from the index that `ubi_data_loader.index.queries` names, and events from the index that `ubi_data_loader.index.events` names. The shipped names are `ubi_queries` and `ubi_events`. The table shows the four fields whose type matters in the mapping.
|
|
16
|
+
|
|
17
|
+
| Field | Type | What breaks without it |
|
|
18
|
+
|---|---|---|
|
|
19
|
+
| `<query_id_field>` | `keyword` | The key that `dataset_builder.query_id_field` names, `query_id` by default. The loader looks up queries with a `terms` query on it. A `text` field splits ids at hyphens. |
|
|
20
|
+
| `timestamp` | `date` | The loader filters and sorts on it. |
|
|
21
|
+
| `action_name` | `keyword` | The loader filters events with a `terms` query on it. A `text` field splits an action such as `add-to-cart` into tokens, so no event of that action matches. |
|
|
22
|
+
| `query_attributes` | `object` with `enabled: false` | Every doc id in `scores` becomes a new field. OpenSearch stops at 1000 fields and rejects the documents. |
|
|
23
|
+
|
|
24
|
+
[Create the UBI indices](run-locally.md#create-the-ubi-indices) has the commands that create both indices with these mappings.
|
|
25
|
+
|
|
26
|
+
## Which documents the pipeline reads
|
|
27
|
+
|
|
28
|
+
The loader reads events first, then the queries that those events name. The table shows the steps in order.
|
|
29
|
+
|
|
30
|
+
| Step | What the loader does |
|
|
31
|
+
|---|---|
|
|
32
|
+
| 1 | It searches the events index for events whose `timestamp` falls in a window of whole UTC days. The window starts at `00:00:00Z` on the day `ubi_data_loader.max_days_ago` days before the current UTC date. It ends at `23:59:59Z` on the current UTC date. |
|
|
33
|
+
| 2 | In the same search, it keeps only events whose `action_name` is a cascade action. It never loads `impression` events. The gem sets `impression_count` itself: 1 for a doc at or above the deepest cascade action in the search, 0 below it. |
|
|
34
|
+
| 3 | It keeps the newest `ubi_data_loader.n_events` of those events. The search sorts on `timestamp`, newest first. |
|
|
35
|
+
| 4 | It reads the query documents whose `query_id` matches one of those events. It does not filter queries by date. |
|
|
36
|
+
|
|
37
|
+
`ubi_data_loader.max_days_ago` and `ubi_data_loader.n_events` have no default, so the loader raises when one is missing. `ubi_data_loader.n_events` must be above 0. The shipped file sets `ubi_data_loader.max_days_ago` to `30` and `ubi_data_loader.n_events` to `10000`.
|
|
38
|
+
|
|
39
|
+
## Query documents
|
|
40
|
+
|
|
41
|
+
`Ltr::Ubi.query` builds a document, but it does not write to OpenSearch, so you index the returned Hash yourself.
|
|
42
|
+
|
|
43
|
+
| Field | Type | Required | Rule |
|
|
44
|
+
|---|---|---|---|
|
|
45
|
+
| `query_id` | string | yes | The key that events join on. `dataset_builder.query_id_field` sets the key name and defaults to `query_id`. The pipeline drops a record with a missing or blank value. |
|
|
46
|
+
| `user_query` | string | yes | The pipeline trims and lowercases it, and drops a record with a missing or blank value. |
|
|
47
|
+
| `timestamp` | ISO8601 string | yes | `Ltr::Ubi.query` writes it as a UTC ISO8601 string. The loader does not filter queries by date. |
|
|
48
|
+
| `query_attributes.scores` | object | yes | The keys are doc ids. Each value holds the scores for that doc, keyed by score name, with a number as each score. A text score is kept. A `true` score becomes 1 and a `false` score becomes 0. A score of `nil`, a hash or an array is left out. For example: `{"prodA": {"bm25_name": 0.9}}`. Both engines drop a record with no `query_attributes`, or with no `scores` hash in it. A `query_attributes` or `scores` that is present and not a hash raises `Ltr::InvalidDatasetError`. |
|
|
49
|
+
| `query_response_hit_ids` | array of strings | yes | The hit ids. `dataset_builder.hit_ids_field` sets the key name and defaults to `query_response_hit_ids`. Both engines skip a record with no hit ids or an empty array. |
|
|
50
|
+
| `application`, `client_id`, `query_response_id` | string | no | The dataset pipeline reads them only when `dataset_builder.additional_qid_fields` names them. |
|
|
51
|
+
|
|
52
|
+
[How the pipeline builds rows](dataset-csv.md#how-the-pipeline-builds-rows) explains how the hit ids and scores become rows.
|
|
53
|
+
|
|
54
|
+
### Additional rules for query documents
|
|
55
|
+
|
|
56
|
+
- Give each search its own `query_id`. When records repeat a `query_id`, both engines keep only the newest one, and the events of that `query_id` count once. If the newest record has no hit ids, the `query_id` gives no rows.
|
|
57
|
+
- Once per run, the pipeline logs one warning for the query records it skipped because they have no hit ids. The warning says how many records it skipped and lists the query ids of the first 10, for example `Skipped 3 ubi_queries record(s) with no query_response_hit_ids (first: q1, q2, q3)`. If no record is left, the run stops with an `ArgumentError`, because `dataset_builder.hit_ids_field` is probably wrong.
|
|
58
|
+
- A query group holds the searches that share one `qid`. By default, two searches are in the same group when their `user_query` is the same. `dataset_builder.additional_qid_fields` lists more fields that must also match. For example, with `[market]`, "magnesium" searched in `US` and "magnesium" searched in `CA` are two different groups. It defaults to `[]`. Each field is read from the top level of the document, or else from the first doc's score object. The values compare as text, so `1` and `"1"` are one value. See [Config](config.md#dataset_builder).
|
|
59
|
+
|
|
60
|
+
### Reserved score names
|
|
61
|
+
|
|
62
|
+
A reserved name is the name of a column that the gem writes into each row itself. The reserved names are `impression_count`, the `<action>_count` column of each cascade action, the `dataset_builder.doc_id_field` name, `qid`, `user_query`, `timestamp`, `original_position`, `query_length_tokens` and `bm25_fields_matched`.
|
|
63
|
+
|
|
64
|
+
Both engines leave out a score with a reserved name and keep the gem's value. Each run logs one warning that names the scores left out.
|
|
65
|
+
|
|
66
|
+
## Event documents
|
|
67
|
+
|
|
68
|
+
`Ltr::Ubi.event` builds a document, and you index the returned Hash yourself.
|
|
69
|
+
|
|
70
|
+
| Field | Type | Required | Rule |
|
|
71
|
+
|---|---|---|---|
|
|
72
|
+
| `query_id` | string | yes | Must match the `query_id` of a query document. `dataset_builder.query_id_field` sets the key name, as it does in query documents. The pipeline drops an event with a blank value. It also drops an event whose query id is not in the query set, and logs how many. |
|
|
73
|
+
| `action_name` | string | yes | The user action, such as `view`, `add_to_cart` or `purchase`. The loader reads only events of cascade actions. The pipeline drops an event with a blank value. |
|
|
74
|
+
| `event_attributes.<doc_id_field>` | string | yes | The doc that the action applies to. `dataset_builder.doc_id_field` sets the key name and defaults to `doc_id`. The pipeline drops an event with a blank value. If no cascade action event has a doc id under this key, the run raises `ArgumentError`. The message names that key. |
|
|
75
|
+
| `timestamp` | ISO8601 string | yes | The loader filters and sorts on it. [Which documents the pipeline reads](#which-documents-the-pipeline-reads) gives the window and the event count. The key name is always `timestamp`. |
|
data/docs/ubi-logging.md
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Logging UBI documents
|
|
2
|
+
|
|
3
|
+
This page shows how a host app logs each search with `Ltr::Ubi.query` and each user action with `Ltr::Ubi.event`, so the dataset pipeline can build training rows from them. [UBI documents](ubi-documents.md) gives the rules the pipeline applies when it reads them.
|
|
4
|
+
|
|
5
|
+
## Glossary
|
|
6
|
+
|
|
7
|
+
| Term | Meaning |
|
|
8
|
+
|---|---|
|
|
9
|
+
| Cascade | The rule that decides which documents a user examined in a session. Every document at or above the deepest position with a cascade action is examined. The documents below it are dropped unless `dataset_builder.cascade_cutoff` is `false`. |
|
|
10
|
+
| Cascade action | A configured action other than `impression`. The loaders read only the events of cascade actions, and the cascade cutoff uses only them. |
|
|
11
|
+
| Config loader | An `Ltr::ConfigLoader`, the object that holds the pipeline config. It reads the base YAML file, merges an optional override file on top, runs ERB and checks the values. |
|
|
12
|
+
| Configured action | An action that a `dataset_builder.conversion_rate_targets` entry names as a `numerator` or a `denominator`. The `_count` suffix is left off the name, so `view_count` gives the action `view`. `impression` is a configured action when a rate target names `impression_count`. |
|
|
13
|
+
| Hit ids | The list of doc ids that one search showed, in the order the page showed them. The loader reads it from the field that `dataset_builder.hit_ids_field` names, which defaults to `query_response_hit_ids`. A doc's position is its place in that list, counted from 1. |
|
|
14
|
+
| Host app | The app that runs the search in OpenSearch, logs it to UBI and calls the gem to rerank the results. |
|
|
15
|
+
| Impression | One session in which the cascade marks a document as examined. A document gets at most one impression per session. |
|
|
16
|
+
| OpenSearch | The search engine that runs the search and returns the candidates. It also holds the UBI indices that the dataset pipeline reads. |
|
|
17
|
+
| Pipeline | One of the three entry points: dataset, optimize and modelling. None of them calls another. |
|
|
18
|
+
| Shipped | The value in `lib/ltr/configuration/example_config.yml`. It can differ from the value the code uses when the key is missing. |
|
|
19
|
+
| UBI | User Behavior Insights, the query and event logs that the host app writes to OpenSearch. The shipped index names are `ubi_queries` and `ubi_events`. |
|
|
20
|
+
|
|
21
|
+
## Before you log
|
|
22
|
+
|
|
23
|
+
`Ltr::Ubi.query` and `Ltr::Ubi.event` take the model's `Ltr::ConfigLoader` as `config:` on each call. The loader's `dataset_builder` settings name keys in each document, and the model's pipeline reads those keys back by the same names. A host with more than one model must pass the loader of the model that will train on those searches, which [Host integration](host-integration.md#build-the-loader-for-ltrubi) shows how to build. Neither method writes to OpenSearch. Each returns a Hash that you index with your own client. [Required field types](ubi-documents.md#required-field-types) names the index for each document and shows how to create the indices. Both methods are part of the [public API](public-api.md#ubi-logging).
|
|
24
|
+
|
|
25
|
+
## Log a search and an action
|
|
26
|
+
|
|
27
|
+
Call `Ltr::Ubi.query` once for each search that shows results. Call `Ltr::Ubi.event` once for each action a user takes on one of those results, with the same `query_id`. The pipeline joins each event to its search by that id.
|
|
28
|
+
|
|
29
|
+
In the example below, a made-up search for `vitamin c` shows the documents `prodA` and `prodB`, and the user views `prodA`.
|
|
30
|
+
|
|
31
|
+
```ruby
|
|
32
|
+
config = Ltr::ConfigLoader.new(base_config_path: "config/ltr.yml")
|
|
33
|
+
|
|
34
|
+
Ltr::Ubi.query(
|
|
35
|
+
config: config,
|
|
36
|
+
query_id: "q1",
|
|
37
|
+
user_query: "vitamin c",
|
|
38
|
+
timestamp: Time.utc(2025, 4, 30, 0, 28),
|
|
39
|
+
scores: { "prodA" => { "bm25_name" => 0.90 }, "prodB" => { "bm25_name" => 0.70 } },
|
|
40
|
+
hit_ids: ["prodA", "prodB"]
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
Ltr::Ubi.event(
|
|
44
|
+
config: config,
|
|
45
|
+
query_id: "q1",
|
|
46
|
+
action_name: "view",
|
|
47
|
+
doc_id: "prodA",
|
|
48
|
+
timestamp: "2025-04-30T00:31:00-04:00"
|
|
49
|
+
)
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
When `config/ltr.yml` has the `dataset_builder` field names of the shipped `example_config.yml`, the two calls return these Hashes. They are shown here as the JSON you index.
|
|
53
|
+
|
|
54
|
+
Query document:
|
|
55
|
+
|
|
56
|
+
```json
|
|
57
|
+
{
|
|
58
|
+
"query_id": "q1",
|
|
59
|
+
"user_query": "vitamin c",
|
|
60
|
+
"timestamp": "2025-04-30T00:28:00Z",
|
|
61
|
+
"query_attributes": {
|
|
62
|
+
"scores": { "prodA": { "bm25_name": 0.9 }, "prodB": { "bm25_name": 0.7 } }
|
|
63
|
+
},
|
|
64
|
+
"query_response_hit_ids": ["prodA", "prodB"]
|
|
65
|
+
}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Event document:
|
|
69
|
+
|
|
70
|
+
```json
|
|
71
|
+
{
|
|
72
|
+
"query_id": "q1",
|
|
73
|
+
"action_name": "view",
|
|
74
|
+
"event_attributes": { "doc_id": "prodA" },
|
|
75
|
+
"timestamp": "2025-04-30T04:31:00Z"
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Mapping each argument to a key
|
|
80
|
+
|
|
81
|
+
The table lists each argument and the key it is saved under in the returned Hash. `config:` is left out, because it is not saved. Three of the key names come from `dataset_builder` settings, and [Renaming the keys](#renaming-the-keys) shows how to change them.
|
|
82
|
+
|
|
83
|
+
| Argument | Method | Key in the returned Hash |
|
|
84
|
+
|---|---|---|
|
|
85
|
+
| `query_id:` | Both | `dataset_builder.query_id_field`, which defaults to `query_id` |
|
|
86
|
+
| `timestamp:` | Both | `timestamp`, as a UTC ISO8601 string |
|
|
87
|
+
| `user_query:` | `Ltr::Ubi.query` | `user_query` |
|
|
88
|
+
| `scores:` | `Ltr::Ubi.query` | `query_attributes.scores`, a Hash of document id to a Hash of score name to score |
|
|
89
|
+
| `hit_ids:` | `Ltr::Ubi.query` | `dataset_builder.hit_ids_field`, which defaults to `query_response_hit_ids` |
|
|
90
|
+
| `application:`, `client_id:`, `query_response_id:` | `Ltr::Ubi.query` | The same names. A `nil` argument adds no key. The pipelines read these keys only when `dataset_builder.additional_qid_fields`, which defaults to `[]`, names them. |
|
|
91
|
+
| `action_name:` | `Ltr::Ubi.event` | `action_name` |
|
|
92
|
+
| `doc_id:` | `Ltr::Ubi.event` | `event_attributes.<doc_id_field>`, which defaults to `doc_id` |
|
|
93
|
+
|
|
94
|
+
## Renaming the keys
|
|
95
|
+
|
|
96
|
+
Three keys take their names from `dataset_builder` settings: `query_id_field`, `hit_ids_field` and `doc_id_field`. The table above gives their defaults. All the other keys have fixed names.
|
|
97
|
+
|
|
98
|
+
```yaml
|
|
99
|
+
dataset_builder:
|
|
100
|
+
query_id_field: "search_id"
|
|
101
|
+
hit_ids_field: "shown_product_ids"
|
|
102
|
+
doc_id_field: "product_id"
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Renaming a key changes only the key in the returned Hash. The keyword arguments keep their names: `query_id:`, `hit_ids:` and `doc_id:`.
|
|
106
|
+
|
|
107
|
+
## Timestamps
|
|
108
|
+
|
|
109
|
+
Both methods turn `timestamp` into a UTC ISO8601 string, such as `2025-04-30T04:31:00Z`. The string keeps whole seconds and drops any fraction. The table shows how each method reads each kind of value.
|
|
110
|
+
|
|
111
|
+
| Value you pass | What the method does |
|
|
112
|
+
|---|---|
|
|
113
|
+
| A `Time`, `DateTime` or `ActiveSupport::TimeWithZone` | Converts it to UTC. |
|
|
114
|
+
| A `Date` | Uses midnight UTC on that day. |
|
|
115
|
+
| An ISO8601 string with an offset | Converts it to UTC. |
|
|
116
|
+
| An ISO8601 string without an offset | Reads it in the time zone of the Ruby process (`TZ`), not the Rails `Time.zone`, then converts it to UTC. |
|
|
117
|
+
| `nil`, a date-only string such as `"2025-04-30"`, any other string, or any other type | Raises `ArgumentError`. |
|
|
118
|
+
|
|
119
|
+
The method converts a copy. The `Time` you pass keeps its own zone.
|
|
120
|
+
|
|
121
|
+
## Which action names to send
|
|
122
|
+
|
|
123
|
+
The pipeline names a count column after each `action_name` with `_count` added, so `view` becomes `view_count`. The loader reads only the events of cascade actions. A cascade action is a configured action other than `impression`. [`dataset_builder.conversion_rate_targets`](config.md#dataset_builderconversion_rate_targets) has no default, and the shipped targets use `view_count`, `add_to_cart_count` and `purchase_count`, so send `view`, `add_to_cart` and `purchase`.
|
|
124
|
+
|
|
125
|
+
Don't log `impression` events. The pipeline counts impressions itself from the hit ids and the deepest result with a cascade action, as [Cascade impressions](labels-from-behavior.md#cascade-impressions) explains. [Event documents](ubi-documents.md#event-documents) gives the rules for the events the loader reads.
|
data/lib/ltr/README.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# `lib/ltr`
|
|
2
|
+
|
|
3
|
+
Implementation of the `ltr` gem: learning-to-rank pipelines for search result reranking. The code is loaded by `lib/ltr.rb`, which requires dependencies, sets up the Zeitwerk autoloader, and exposes the `Ltr.config` / `Ltr.configure` host-integration hooks. Everything under this directory lives in the `Ltr::` namespace.
|
|
4
|
+
|
|
5
|
+
The gem is organised as three independent pipelines that share a single `Ltr::ConfigLoader` configuration — dataset aggregation, optimization, and training — plus the inference path used at query time. See `ARCHITECTURE.md` for the end-to-end architecture and `docs/index.md` for usage.
|
|
6
|
+
|
|
7
|
+
## Subfolders
|
|
8
|
+
|
|
9
|
+
| Folder | Purpose |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `configuration/` | Loading, validating, and merging the YAML pipeline config, plus the global host-integration `Configuration`. |
|
|
12
|
+
| `data/` | Low-level data primitives: CSV reading, the `Rover::DataFrame` helpers, dataset loading, and the in-memory row store. |
|
|
13
|
+
| `dataset_aggregation/` | The dataset aggregation pipeline: load UBI data, build a labelled dataset step by step, enrich it, transform labels, and persist it. |
|
|
14
|
+
| `deploy/` | Deployment of trained models — packaging inference artifacts, pushing to SageMaker, writing the feature store, and local persistence. |
|
|
15
|
+
| `errors/` | The gem's own exception classes, all descending from `Ltr::Error`. |
|
|
16
|
+
| `features/` | Feature engineering and encoding shared across training and inference (derived rank/relative-score features, feature transformation, encoders). |
|
|
17
|
+
| `inference/` | Runtime reranking: a dispatcher that routes to either the SageMaker endpoint or the local reranker. |
|
|
18
|
+
| `metrics/` | Ranking evaluation metrics (e.g. NDCG) and per-query score computation. |
|
|
19
|
+
| `optimize/` | The optimization pipeline: greedy feature selection and Bayesian hyperparameter tuning (Gaussian process, search space, config persistence). |
|
|
20
|
+
| `ssm/` | Reading and writing optimized features/hyperparameters to AWS SSM Parameter Store. |
|
|
21
|
+
| `support/` | Small cross-cutting helpers: the `Callable` mixin, `PipelineResult` value object, and the gem version. |
|
|
22
|
+
| `train/` | The training pipeline: XGBoost trainer and evaluator, evaluation caching, and shared training utilities. |
|
|
23
|
+
|
|
24
|
+
## Files
|
|
25
|
+
|
|
26
|
+
| File | Purpose |
|
|
27
|
+
|---|---|
|
|
28
|
+
| `ubi.rb` | Pure builder methods (`Ltr::Ubi.query` / `.event`) that shape host-supplied arguments, and the caller's `Ltr::ConfigLoader` passed as `config:`, into `ubi_queries` / `ubi_events` document Hashes for logging — no datastore writes. |
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# `lib/ltr/configuration`
|
|
2
|
+
|
|
3
|
+
Loads, validates, and merges the gem's YAML pipeline configuration, and defines the global host-integration `Ltr::Configuration`. `Ltr::ConfigLoader` is the single source of truth consumed by every pipeline (dataset aggregation, optimization, training, deploy, inference), exposing typed accessors for each config section; `Ltr::Configuration` provides the swappable logger, S3 client, and error reporter hooks accessed via `Ltr.config`.
|
|
4
|
+
|
|
5
|
+
## Files
|
|
6
|
+
|
|
7
|
+
| File | Purpose |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `config_loader.rb` | Loads the YAML config (with ERB evaluation), deep-merges an optional override file, validates it, and exposes typed accessors plus reload/save for the whole pipeline. |
|
|
10
|
+
| `config_validator.rb` | Validates a loaded config for type constraints and cross-field consistency (model, training, dataset_builder, evaluation, deploy, ssm), raising `Ltr::ConfigurationError`. It also warns for a key outside `KNOWN_KEYS`. `validate_aggregation!` holds the rules only aggregation needs (`conversion_rate_targets`, the `conversion_features` actions, and the column names from `additional_qid_fields` and the cascade actions). `validate!` does not call it. The UBI loaders call it when they start, so a config for logging events, training or deploying loads without rate targets. |
|
|
11
|
+
| `configuration.rb` | Global host-integration object (`Ltr.config`): supplies logger, S3 client, error reporter, project root, and OpenSearch connect options. Both builders are optional. The S3 builder runs each time the gem needs a client, so it should return a cached client. |
|
|
12
|
+
| `example_config.yml` | An example pipeline config that a host can copy as its base file. `ConfigLoader` does not load it unless a host passes its path. It defines model, training, features, evaluation, optimization, UBI loading, deploy, inference, and SSM settings. |
|