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.
Files changed (169) hide show
  1. checksums.yaml +7 -0
  2. data/ARCHITECTURE.md +92 -0
  3. data/CHANGELOG.md +5 -0
  4. data/LICENSE +21 -0
  5. data/README.md +186 -0
  6. data/docs/AGENTS.md +67 -0
  7. data/docs/aggregation-engines.md +80 -0
  8. data/docs/config.md +516 -0
  9. data/docs/data-contracts.md +94 -0
  10. data/docs/data-splits.md +34 -0
  11. data/docs/dataset-builder-steps.md +13 -0
  12. data/docs/dataset-csv.md +73 -0
  13. data/docs/dataset-enrichers.md +62 -0
  14. data/docs/errors.md +33 -0
  15. data/docs/feature-selection.md +108 -0
  16. data/docs/features.md +202 -0
  17. data/docs/glossary.md +56 -0
  18. data/docs/host-integration.md +128 -0
  19. data/docs/host-run-pipelines.md +48 -0
  20. data/docs/index.md +50 -0
  21. data/docs/inference.md +164 -0
  22. data/docs/label-transformers.md +242 -0
  23. data/docs/labels-from-behavior.md +94 -0
  24. data/docs/learning-to-rank.md +119 -0
  25. data/docs/metrics.md +166 -0
  26. data/docs/model-files.md +73 -0
  27. data/docs/optimization.md +72 -0
  28. data/docs/public-api.md +67 -0
  29. data/docs/rake-tasks.md +82 -0
  30. data/docs/relevance-grades.md +80 -0
  31. data/docs/run-locally.md +584 -0
  32. data/docs/run-on-aws.md +647 -0
  33. data/docs/training-objective.md +110 -0
  34. data/docs/ubi-documents.md +75 -0
  35. data/docs/ubi-logging.md +125 -0
  36. data/lib/ltr/README.md +28 -0
  37. data/lib/ltr/configuration/README.md +12 -0
  38. data/lib/ltr/configuration/config_loader.rb +326 -0
  39. data/lib/ltr/configuration/config_validator.rb +476 -0
  40. data/lib/ltr/configuration/configuration.rb +84 -0
  41. data/lib/ltr/configuration/example_config.yml +182 -0
  42. data/lib/ltr/data/README.md +20 -0
  43. data/lib/ltr/data/csv/README.md +9 -0
  44. data/lib/ltr/data/csv/typed_columns.rb +101 -0
  45. data/lib/ltr/data/csv.rb +126 -0
  46. data/lib/ltr/data/dataframe.rb +80 -0
  47. data/lib/ltr/data/dataset_loader.rb +29 -0
  48. data/lib/ltr/data/row_store.rb +188 -0
  49. data/lib/ltr/data/split_cache.rb +30 -0
  50. data/lib/ltr/data/splits.rb +86 -0
  51. data/lib/ltr/dataset_aggregation/README.md +32 -0
  52. data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
  53. data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
  54. data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
  55. data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
  56. data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
  57. data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
  58. data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
  59. data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
  60. data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
  61. data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
  62. data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
  63. data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
  64. data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
  65. data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
  66. data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
  67. data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
  68. data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
  69. data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
  70. data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
  71. data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
  72. data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
  73. data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
  74. data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
  75. data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
  76. data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
  77. data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
  78. data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
  79. data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
  80. data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
  81. data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
  82. data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
  83. data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
  84. data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
  85. data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
  86. data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
  87. data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
  88. data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
  89. data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
  90. data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
  91. data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
  92. data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
  93. data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
  94. data/lib/ltr/deploy/README.md +21 -0
  95. data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
  96. data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
  97. data/lib/ltr/deploy/feature_extractor.rb +94 -0
  98. data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
  99. data/lib/ltr/deploy/local_deployer.rb +61 -0
  100. data/lib/ltr/deploy/model_packager.rb +90 -0
  101. data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
  102. data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
  103. data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
  104. data/lib/ltr/errors/README.md +16 -0
  105. data/lib/ltr/errors/configuration_error.rb +5 -0
  106. data/lib/ltr/errors/deploy_error.rb +5 -0
  107. data/lib/ltr/errors/error.rb +5 -0
  108. data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
  109. data/lib/ltr/errors/missing_dependency_error.rb +5 -0
  110. data/lib/ltr/errors/sqlite_error.rb +14 -0
  111. data/lib/ltr/features/README.md +19 -0
  112. data/lib/ltr/features/encoders/README.md +10 -0
  113. data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
  114. data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
  115. data/lib/ltr/features/feature_engineering.rb +194 -0
  116. data/lib/ltr/features/feature_transformer.rb +92 -0
  117. data/lib/ltr/features/float32_range.rb +20 -0
  118. data/lib/ltr/features/transform_steps.rb +34 -0
  119. data/lib/ltr/features/transform_store.rb +123 -0
  120. data/lib/ltr/inference/README.md +11 -0
  121. data/lib/ltr/inference/base.rb +52 -0
  122. data/lib/ltr/inference/local_reranker.rb +147 -0
  123. data/lib/ltr/inference/sagemaker_client.rb +62 -0
  124. data/lib/ltr/metrics/README.md +12 -0
  125. data/lib/ltr/metrics/metric_scores.rb +67 -0
  126. data/lib/ltr/metrics/metrics.rb +139 -0
  127. data/lib/ltr/optimize/README.md +25 -0
  128. data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
  129. data/lib/ltr/optimize/candidate_selector.rb +97 -0
  130. data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
  131. data/lib/ltr/optimize/expected_improvement.rb +33 -0
  132. data/lib/ltr/optimize/feature_selection/README.md +15 -0
  133. data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
  134. data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
  135. data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
  136. data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
  137. data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
  138. data/lib/ltr/optimize/gaussian_process.rb +125 -0
  139. data/lib/ltr/optimize/optimization_dataset.rb +16 -0
  140. data/lib/ltr/optimize/optimize_features.rb +129 -0
  141. data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
  142. data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
  143. data/lib/ltr/optimize/search_space.rb +165 -0
  144. data/lib/ltr/optimize/update_config.rb +196 -0
  145. data/lib/ltr/ssm/README.md +11 -0
  146. data/lib/ltr/ssm/loader.rb +61 -0
  147. data/lib/ltr/ssm/parameter_paths.rb +19 -0
  148. data/lib/ltr/ssm/saver.rb +76 -0
  149. data/lib/ltr/support/README.md +13 -0
  150. data/lib/ltr/support/callable.rb +10 -0
  151. data/lib/ltr/support/optional_dependency.rb +31 -0
  152. data/lib/ltr/support/pipeline_result.rb +22 -0
  153. data/lib/ltr/support/pipeline_task.rb +81 -0
  154. data/lib/ltr/support/version.rb +7 -0
  155. data/lib/ltr/tasks/ltr.rake +24 -0
  156. data/lib/ltr/train/README.md +19 -0
  157. data/lib/ltr/train/deploy_gate.rb +77 -0
  158. data/lib/ltr/train/deploy_metric.rb +63 -0
  159. data/lib/ltr/train/eval_logger.rb +16 -0
  160. data/lib/ltr/train/evaluation_cache.rb +101 -0
  161. data/lib/ltr/train/modelling_pipeline.rb +82 -0
  162. data/lib/ltr/train/optimization_split_report.rb +54 -0
  163. data/lib/ltr/train/utils.rb +35 -0
  164. data/lib/ltr/train/xgb_evaluator.rb +96 -0
  165. data/lib/ltr/train/xgb_trainer.rb +154 -0
  166. data/lib/ltr/ubi.rb +86 -0
  167. data/lib/ltr.rb +61 -0
  168. data/scripts/seed_ubi.rb +75 -0
  169. metadata +346 -0
@@ -0,0 +1,94 @@
1
+ # Labels from behavior
2
+
3
+ This page explains how the gem builds the label of each query and document from user events. It covers which documents count as examined, how the rates in `dataset_builder.conversion_rate_targets` add up to `raw_label`, how smoothing treats a document with few impressions, how unexamined documents become negatives, and how to check a label with `debug_mode`. [Label transformers](label-transformers.md) explains how `raw_label` becomes the `label` the model trains on.
4
+
5
+ ## The input
6
+
7
+ The gem learns only from implicit feedback. It reads [User Behavior Insights](https://github.com/o19s/ubi) (UBI) data from two [OpenSearch UBI](https://docs.opensearch.org/latest/search-plugins/ubi/index/) indexes. The queries index holds each search and the documents it returned. The events index holds actions such as a view, an add to cart or a purchase.
8
+
9
+ [UBI documents](ubi-documents.md#which-documents-the-pipeline-reads) gives the index names, the date window and the event count. A search with no events in that window is not in the dataset.
10
+
11
+ ## From events to a label
12
+
13
+ A session is one search, which is one record in the queries index. The dataset builder runs these steps:
14
+
15
+ 1. `UbiJoiner` joins each event to its session. It drops a search with a blank `user_query` and trims and lowercases the rest.
16
+ 2. `QueryAggregator` makes one row for each document in a session and counts its actions, using the cascade rule below.
17
+ 3. `UserQueryAggregator` sums the `_count` columns over the sessions of each `qid` and document. [Query groups](learning-to-rank.md#query-groups-qid) explains which sessions share a `qid`.
18
+ 4. `NegativeDownsampler` drops some [negatives](#negatives) when `negative_downsample_ratio` is set.
19
+ 5. `LabelCreator` computes `raw_label` from the counts.
20
+ 6. A [label transformer](label-transformers.md) turns `raw_label` into `label`.
21
+ 7. `DatasetFilters` removes queries with fewer than `min_documents_per_query` documents (shipped `3`).
22
+
23
+ The `sqlite` engine runs steps 1 to 4 in SQL. It gives the same results as the `ruby` engine. See [What both engines give](aggregation-engines.md#what-both-engines-give).
24
+
25
+ ### Cascade impressions
26
+
27
+ A user who viewed the 3rd result probably looked at results 1 and 2. Counting every returned document as an impression would give low labels to documents that were never on screen.
28
+
29
+ So in each session, the gem finds the deepest position that had a cascade action. A cascade action is a numerator or a denominator in `conversion_rate_targets`, other than `impression`. Every document at or above that position gets one impression. The documents below it were not examined, and the gem drops them unless `cascade_cutoff` is `false`. A session with no cascade action adds no rows.
30
+
31
+ A document's position is its place in `dataset_builder.hit_ids_field` (shipped `query_response_hit_ids`). A document with no entry in the session's [`scores`](ubi-documents.md#query-documents) gets no row.
32
+
33
+ Each action count is capped at 1 per document per session. So `view_count` counts sessions with a view, and a numerator never exceeds `impression_count`.
34
+
35
+ Example (made-up session). The search "magnesium" shows five products. The user views Magnesium citrate and buys Magnesium threonate, so the cutoff is position 4.
36
+
37
+ | Position | Product | `impression_count` | `view_count` | `purchase_count` |
38
+ |---|---|---|---|---|
39
+ | 1 | Magnesium glycinate | 1 | 0 | 0 |
40
+ | 2 | Magnesium citrate | 1 | 1 | 0 |
41
+ | 3 | Magnesium oxide | 1 | 0 | 0 |
42
+ | 4 | Magnesium threonate | 1 | 0 | 1 |
43
+ | 5 | Magnesium malate | dropped | | |
44
+
45
+ ### Conversion-rate targets
46
+
47
+ Each entry in `conversion_rate_targets` defines one rate, `numerator / denominator`, over the summed counts. The shipped entries are:
48
+
49
+ | `name` | `numerator` | `denominator` | `weight` | `nu` |
50
+ |---|---|---|---|---|
51
+ | `ctr` | `view_count` | `impression_count` | 1 | 50 |
52
+ | `atcr` | `add_to_cart_count` | `impression_count` | 2 | 100 |
53
+ | `cvr` | `purchase_count` | `impression_count` | 3 | 150 |
54
+
55
+ `denominator` defaults to `impression_count`. `raw_label` is the sum of `weight × smoothed rate` over the entries.
56
+
57
+ `LabelCreator` raises `ArgumentError` when a numerator is greater than its denominator. The message names the first such `qid` and document. The per-session cap rules this out for the default denominator. For a custom denominator such as `view_count`, `allow_invariant_violation: true` on the entry logs a warning instead.
58
+
59
+ ### Smoothing the rates
60
+
61
+ One impression and one view give a view rate of 1.0. So `LabelCreator` adds `nu` made-up impressions at the dataset's average rate `mu` to every row:
62
+
63
+ ```
64
+ mu = sum of the numerators / sum of the denominators (all rows)
65
+ smoothed_rate = (numerator + mu × nu) / (denominator + nu)
66
+ ```
67
+
68
+ A product with few impressions, such as one that rarely ranked high, keeps a rate near `mu`. A product with many impressions keeps a rate near its own. A bigger `nu` keeps rates nearer to `mu`. `nu` must be greater than 0.
69
+
70
+ Example (made-up counts). Take the `ctr` entry only (`nu` 50) and a dataset of three products. Then `mu = 8 / 22 = 0.3636` and `mu × nu = 18.18`.
71
+
72
+ | Product | `impression_count` | `view_count` | Raw rate | Smoothed `ctr` |
73
+ |---|---|---|---|---|
74
+ | Magnesium glycinate | 10 | 5 | 0.5 | 0.3864 |
75
+ | Magnesium citrate | 10 | 1 | 0.1 | 0.3197 |
76
+ | Magnesium oxide | 2 | 2 | 1.0 | 0.3881 |
77
+
78
+ For Magnesium oxide, `(2 + 18.18) / (2 + 50) = 0.3881`. Its raw rate is twice Magnesium glycinate's, but its smoothed rate is only 0.0017 higher. The smoothed rates sit in a narrow band, from 0.32 to 0.39. [Per-query transformers](label-transformers.md#per-query-transformers) explains why that matters for NDCG.
79
+
80
+ A smoothed rate is above 0 whenever its action occurs anywhere in the dataset, because `mu` is then above 0. So with the shipped targets, an examined document's `raw_label` is above 0 even when nobody acted on it. The gem has no filter for low labels.
81
+
82
+ ### Negatives
83
+
84
+ With `dataset_builder.cascade_cutoff: false`, the documents below the cutoff stay with `impression_count` 0. A document with 0 impressions in every session of its query is a negative. Keeping the negatives makes the aggregation tables about 6 times larger on a production pull.
85
+
86
+ Negatives skip `LabelCreator`. Smoothing would give a negative a rate of exactly `mu`, which is above the rate of a document that was seen and skipped. So the gem labels the examined documents alone, then appends the negatives with `raw_label` and `label` of 0. The examined documents get the labels of a run with the cutoff on. The negatives count toward `min_documents_per_query`.
87
+
88
+ `dataset_builder.negative_downsample_ratio` caps the negatives in each query at `ceil(ratio × examined documents)`. The gem keeps the negatives with the lowest hash rank. The rank hashes the top-level `seed` (shipped `1967`), the query's group key and the doc ID. Both engines compute the same rank, so they keep the same negatives. Setting the ratio while `cascade_cutoff` is on raises `Ltr::ConfigurationError` when the config loads.
89
+
90
+ ## Check a label with `debug_mode`
91
+
92
+ After labelling, `BehaviouralFeatureBuilder` replaces each `_count` column with the document's total across the train-split queries only, because inference serves that total as a feature. A document with no train rows is the exception. The feature store gets its totals over the val and test rows instead, saved under `fallback_feature_totals` in the serving file. The CSV does not hold them. The gem then drops `impression_count`. So a normal dataset does not hold the counts the label used.
93
+
94
+ `dataset_builder.debug_mode: true` skips `BehaviouralFeatureBuilder`. The `_count` columns and `impression_count` then stay at the `qid` and document level, so you can recompute `raw_label` from the rows. Never train on a `debug_mode` dataset. Its `_count` columns differ from what inference serves, and its `conversion_features` columns are missing. Training does not stop on a missing feature, so the gem logs a warning instead.
@@ -0,0 +1,119 @@
1
+ # Learning to rank
2
+
3
+ The gem trains an XGBoost LambdaMART model that reorders the products OpenSearch returns for a search. This page gives the main ideas: what the model does, how rows are grouped into queries, what the model optimizes, which metric the gem uses to judge it, and why the work runs as three pipelines. The pages assume you know the basics of learning to rank (LTR) and gradient-boosted trees.
4
+
5
+ ## Glossary
6
+
7
+ | Term | Meaning |
8
+ |---|---|
9
+ | BM25 | A text match score that OpenSearch computes for one field of a document, such as `bm25_name` for the product name. The host app logs it and sends it as a search-time feature. |
10
+ | Candidate | One document that OpenSearch returned for a search. The model gives each candidate a `score`. |
11
+ | 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. |
12
+ | Host app | The app that runs the search in OpenSearch, logs it to UBI and calls the gem to rerank the results. |
13
+ | `label` | The target value for training the model. |
14
+ | LambdaMART | The pairwise ranking method behind the XGBoost `rank:ndcg` objective. |
15
+ | NDCG | Normalized DCG, which is DCG divided by IDCG. It runs from 0 to 1. |
16
+ | `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. |
17
+ | Query group | All rows that share a `qid`. A group holds the candidate documents for one `user_query` and one value of each `dataset_builder.additional_qid_fields` field. XGBoost builds pairs only inside a group. |
18
+ | SSM | AWS Systems Manager Parameter Store. When `ssm.enabled` is `true`, the optimize pipeline writes its chosen features and hyperparameters there, and the modelling pipeline reads them. |
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
+ | XGBoost | The gradient-boosted tree library that trains the model and scores the candidates. The gem uses its `rank:ndcg` objective. |
21
+
22
+ The full list is in the [glossary](glossary.md).
23
+
24
+ ## What the model does
25
+
26
+ OpenSearch does the retrieval, and the gem only reorders what OpenSearch returns. The host app sends the candidates and their features to the model. The features include a BM25 score for each searched field of the product document, such as `bm25_name`. The model returns one `score` per candidate, and the candidates are sorted by that score, highest first.
27
+
28
+ In the example below, OpenSearch returns three made-up candidates for one search, and the model reorders them.
29
+
30
+ ```mermaid
31
+ ---
32
+ config:
33
+ flowchart:
34
+ wrappingWidth: 480
35
+ ---
36
+ flowchart LR
37
+ A["OpenSearch candidates<br>rank 1: Magnesium glycinate<br>rank 2: Vitamin D3<br>rank 3: Fish oil"] -->|"features"| B["LTR model"]
38
+ B -->|"scores"| C["Reranked list<br>rank 1: Vitamin D3<br>rank 2: Fish oil<br>rank 3: Magnesium glycinate"]
39
+ ```
40
+
41
+ The table gives made-up scores for the same three candidates.
42
+
43
+ | Product | BM25 score from OpenSearch | Model `score` | Rank before | Rank after |
44
+ |---|---|---|---|---|
45
+ | Magnesium glycinate | 12.4 | 0.31 | 1 | 3 |
46
+ | Vitamin D3 | 11.9 | 0.78 | 2 | 1 |
47
+ | Fish oil | 10.2 | 0.55 | 3 | 2 |
48
+
49
+ The model puts Vitamin D3 first even though its BM25 score is lower. Its features look more like the products that users engaged with in the training data. [Features](features.md) lists the kinds of feature, and [Labels from behavior](labels-from-behavior.md) explains how user events become labels.
50
+
51
+ ## Query groups (`qid`)
52
+
53
+ Each row in the dataset is one document for one query. Its `qid` says which query that is, so all rows that share a `qid` are ranked against each other. `QueryAggregator` gives each distinct `user_query`, plus any fields in `dataset_builder.additional_qid_fields`, its own `qid`. The default for `additional_qid_fields` is empty ([Config](config.md#dataset_builder)), and the shipped config does not set it. With the default, sessions that ran the same query text share one group.
54
+
55
+ In the example below, a small dataset holds two queries with made-up labels.
56
+
57
+ | `qid` | `user_query` | Product | `label` |
58
+ |---|---|---|---|
59
+ | 1 | magnesium | Magnesium glycinate | 0.9 |
60
+ | 1 | magnesium | Magnesium citrate | 0.4 |
61
+ | 1 | magnesium | Zinc | 0.1 |
62
+ | 2 | vitamin d | Vitamin D3 | 0.8 |
63
+ | 2 | vitamin d | Vitamin D3 with K2 | 0.5 |
64
+ | 2 | vitamin d | Fish oil | 0.2 |
65
+
66
+ Before training, `Ltr::Data::Dataframe.dmatrix_from_dataframe` sorts each split by `qid` and passes XGBoost the size of each group. For this table the group sizes are `[3, 3]`. XGBoost only builds pairs inside a group, so it never compares a magnesium product with a vitamin d product. The diagram lists the six training pairs that LambdaMART builds from this table.
67
+
68
+ ```mermaid
69
+ ---
70
+ config:
71
+ flowchart:
72
+ wrappingWidth: 480
73
+ ---
74
+ flowchart TB
75
+ subgraph G1["qid 2: vitamin d, 3 training pairs"]
76
+ D["Vitamin D3 (0.8)<br><i>should rank above</i><br>Vitamin D3 with K2 (0.5)"] ~~~ E["Vitamin D3 (0.8)<br><i>should rank above</i><br>Fish oil (0.2)"] ~~~ F["Vitamin D3 with K2 (0.5)<br><i>should rank above</i><br>Fish oil (0.2)"]
77
+ end
78
+ subgraph G0["qid 1: magnesium, 3 training pairs"]
79
+ A["Magnesium glycinate (0.9)<br><i>should rank above</i><br>Magnesium citrate (0.4)"] ~~~ B["Magnesium glycinate (0.9)<br><i>should rank above</i><br>Zinc (0.1)"] ~~~ C["Magnesium citrate (0.4)<br><i>should rank above</i><br>Zinc (0.1)"]
80
+ end
81
+ ```
82
+
83
+ Evaluation uses the same groups. It scores each query on its own and then averages the scores, as [Metrics](metrics.md#how-query-scores-are-averaged) explains.
84
+
85
+ ## What the model optimizes
86
+
87
+ The gem sets `objective: rank:ndcg`, which XGBoost implements as LambdaMART. LambdaMART pairs up documents in the same `qid` that 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. Only pairs that involve the top positions count, up to the cutoff that [`lambdarank_num_pair_per_sample`](config.md#model) sets. LambdaMART weights each pair by how much NDCG would change if the two documents swapped places. A swap near the top changes NDCG far more than a swap lower down, so most of the gradient goes to pairs at the top of the list. The labels are continuous decimals, so the gem sets `ndcg_exp_gain: false`. [Training objective](training-objective.md) explains the weighting and the settings.
88
+
89
+ ## The main metric, NDCG@k
90
+
91
+ Users read the top of a result list, so the main metric should reward a good top and care less about the tail. NDCG@k does this, because lower ranks count less and `@k` stops counting after `k` results. It also uses each label as a number, so the gap between two continuous labels counts. The shipped config uses `ndcg@12` in three places: `model.hyperparameters.eval_metric` for early stopping, `optimization.metric_to_optimize` for the feature and hyperparameter search, and `evaluation.metrics` for the reported metrics. Each of these stages reads its own data split, as [Data splits](data-splits.md) explains. [Metrics](metrics.md#formulas) has the formulas.
92
+
93
+ ## Three decoupled pipelines
94
+
95
+ The gem has three entry points, and none of them calls another. Each one is a class that you run with `.call(config)`. The diagram shows what each pipeline reads, and the table shows what it writes.
96
+
97
+ ```mermaid
98
+ ---
99
+ config:
100
+ flowchart:
101
+ wrappingWidth: 480
102
+ ---
103
+ flowchart TB
104
+ OS["UBI data in OpenSearch"] --> D["Dataset pipeline"]
105
+ D --> CSV[("CSV")]
106
+ CSV --> O["Optimize pipeline"]
107
+ O --> CFG[("Config file or SSM")]
108
+ CSV --> M["Modelling pipeline"]
109
+ CFG --> M
110
+ M --> OUT["Model, metrics, optional deployment"]
111
+ ```
112
+
113
+ | Pipeline | Entry point | Writes |
114
+ |---|---|---|
115
+ | Dataset | `Ltr::DatasetAggregation::DatasetPipeline` | A CSV at `training.modelling_dataset_path`, local or S3 |
116
+ | Optimize | `Ltr::Optimize::OptimizePipeline` | Chosen features and hyperparameters, in the config file and optionally SSM |
117
+ | Modelling | `Ltr::Train::ModellingPipeline` | A trained model, metrics and an optional deployment |
118
+
119
+ Each pipeline writes its result to a file or a setting that the next pipeline reads, so you can rerun one stage alone. The dataset pull from OpenSearch is the slowest stage and the optimize pipeline trains many models, so you run both less often than the cheap modelling pipeline. [Optimization](optimization.md) explains how the optimize pipeline picks the features and the hyperparameters.
data/docs/metrics.md ADDED
@@ -0,0 +1,166 @@
1
+ # Metrics
2
+
3
+ This page explains the five ranking metrics that the gem uses to score a trained model: `ndcg`, `precision`, `map`, `mrr` and `recall`. It covers which config keys take a metric name, how the gem turns the scores of single queries into one number, and the formula for each metric. [Relevance grades](relevance-grades.md) explains which documents count as relevant for `map`, `mrr`, `precision` and `recall`.
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
+ | `label` | The target value for training the model. |
12
+ | NDCG | Normalized DCG, which is DCG divided by IDCG. It runs from 0 to 1. |
13
+ | `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. |
14
+ | Relevance grade | The `label` at or above which a document counts as relevant for `map`, `mrr`, `precision` and `recall`. It comes from `evaluation.min_relevance_grade`, or from `evaluation.min_relevance_percentile`. `ndcg` does not use it. |
15
+ | Shipped | The value in `lib/ltr/configuration/example_config.yml`. It can differ from the value the code uses when the key is missing. |
16
+
17
+ The full list is in the [glossary](glossary.md).
18
+
19
+ ## Config keys that take a metric name
20
+
21
+ Three config keys take a metric name, and the table gives the rule for each one. `model.hyperparameters.eval_metric`, shipped as `ndcg@12`, is a separate setting that XGBoost computes during training for early stopping, as [Config](config.md#evaluation) explains. [Data splits](data-splits.md#which-split-each-stage-reads) says which split each key is scored on.
22
+
23
+ | Key | Shipped value | What it does | Rule |
24
+ |---|---|---|---|
25
+ | `evaluation.metrics` | `map@10`, `mrr@10`, `ndcg`, `ndcg@5`, `ndcg@12`, `precision`, `precision@5` and `recall@5` | Lists the metrics that `ltr:train` reports | No default. It must be a non-empty list when the `evaluation` section is set. The config load does not check the names, so `ltr:train` rejects a wrong name when it scores the model. |
26
+ | `deploy.metric` | `ndcg` | Picks the metric that both deploys compare with `deploy.minimum_metric_value` | No default. When `deploy.enabled` or `deploy.local` is `true`, it is required and must be one of `evaluation.metrics`. The config load does not check the name in any other way. |
27
+ | `optimization.metric_to_optimize` | `ndcg@12` | Scores every `ltr:optimize` trial | No default, and `ltr:optimize` raises an error when it is missing. The config load rejects a name that is not valid. |
28
+
29
+ ## How query scores are averaged
30
+
31
+ The gem scores one split at a time (train, test, val), and the table lists the steps it takes to turn the documents of that split into one number for each metric.
32
+
33
+ | Step | What the gem does |
34
+ |---|---|
35
+ | Group the rows | It puts the rows of the split into one group for each `qid`, so each group holds the documents of one query. |
36
+ | Rank each query | It sorts the documents of each query by the model's score, with the highest score at rank 1. For `map`, `mrr`, `precision` and `recall`, documents with equal scores come out in no fixed order. For `ndcg`, documents with equal scores share the average of their gains, so their order does not change the score. This is the tie rule of [scikit-learn's `ndcg_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ndcg_score.html). |
37
+ | Score each query | It computes each metric for each query and rounds it to 4 decimals. |
38
+ | Average the queries | It reports the mean over all queries, rounded to 4 decimals. Every query counts the same however many documents it has. A query with no relevant document counts as 0.0 for `map`, `mrr`, `precision` and `recall`. For `ndcg` it counts as 0.0 when no document in the top `k` has a label above 0. |
39
+
40
+ ## Formulas
41
+
42
+ Each formula scores one query. $`n`$ is the number of documents in the query. $`k`$ comes from the `@k` in the metric name, and it is $`n`$ when the name has no `@k`. $`m = \min(k, n)`$ is the number of ranks a metric looks at. The labels come from the `label` column of the scored split. A document is relevant when its label is at least the [relevance grade](relevance-grades.md).
43
+
44
+ ### Gain
45
+
46
+ The gain is what one document is worth before its rank counts. Set `model.hyperparameters.ndcg_exp_gain: false` for linear gain, which is the shipped value, or `true` for exponential gain. The reported NDCG uses the gain the model trained with.
47
+
48
+ ```math
49
+ \mathrm{gain}(\ell) = \begin{cases} \ell & \text{with linear gain (shipped)} \\ 2^{\ell} - 1 & \text{with exponential gain} \end{cases}
50
+ ```
51
+
52
+ - $`\ell`$ is the label of one document.
53
+
54
+ Linear gain is the label itself, and both forms give a higher gain to a higher label.
55
+
56
+ ### DCG and NDCG
57
+
58
+ DCG adds up the gain of each document in the top $`m`$ ranks. It divides each gain by $`\log_2(i + 1)`$, which grows with the rank $`i`$, so a document counts less the lower it sits. NDCG divides DCG by IDCG, which is the DCG of the same labels sorted from highest to lowest.
59
+
60
+ ```math
61
+ \mathrm{DCG}@k = \sum_{i=1}^{m} \frac{\mathrm{gain}(\mathit{rel}_i)}{\log_2(i + 1)}
62
+ \qquad
63
+ \mathrm{NDCG}@k = \begin{cases} \dfrac{\mathrm{DCG}@k}{\mathrm{IDCG}@k} & \text{when } \mathrm{IDCG}@k \neq 0 \\ 0.0 & \text{when } \mathrm{IDCG}@k = 0 \end{cases}
64
+ ```
65
+
66
+ - $`\mathit{rel}_i`$ is the label of the document at rank $`i`$, with ranks starting at 1.
67
+ - $`\mathrm{IDCG}@k`$ is $`\mathrm{DCG}@k`$ of the labels sorted from highest to lowest.
68
+
69
+ NDCG is high when the documents with high labels sit near the top. An NDCG of 1.0 means the model put the documents in the best order. An NDCG near 0 means the documents with high labels sit low, or outside the top $`k`$. A label that is not a number raises `ArgumentError`.
70
+
71
+ With labels of 0 or more, NDCG runs from 0.0 to 1.0. Both forms of gain are 0 or more for such a label, so DCG is 0 or more. IDCG gives the largest gains the largest discounts, so no order of the same labels has a larger DCG than IDCG.
72
+
73
+ ```math
74
+ 0 \le \mathrm{DCG}@k \le \mathrm{IDCG}@k
75
+ ```
76
+
77
+ [Training objective](training-objective.md#dcg-discount-and-idcg) works through DCG and IDCG for one query.
78
+
79
+ ### Precision
80
+
81
+ The precision, $`\mathrm{Precision}@k`$, is the share of the top $`k`$ documents that are relevant. A low value means the top $`k`$ holds many documents that are not relevant.
82
+
83
+ ```math
84
+ \mathrm{Precision}@k = \frac{1}{k} \sum_{i=1}^{m} \mathit{hit}_i
85
+ ```
86
+
87
+ - $`\mathit{hit}_i`$ is 1 when the document at rank $`i`$ is relevant, else 0.
88
+
89
+ ### Average precision
90
+
91
+ The average precision, $`\mathrm{AP}@k`$, adds up the precision at $`i`$, $`P(i)`$, at each rank that holds a relevant document, then divides by every relevant document in the query. It is high when the relevant documents sit at the top. `map` is the mean average precision, which is the mean of $`\mathrm{AP}@k`$ over the queries.
92
+
93
+ ```math
94
+ P(i) = \frac{1}{i} \sum_{j=1}^{i} \mathit{hit}_j
95
+ \qquad
96
+ \mathrm{AP}@k = \frac{1}{R} \sum_{i=1}^{m} \mathit{hit}_i \, P(i)
97
+ ```
98
+
99
+ - $`\mathit{hit}_i`$ is 1 when the document at rank $`i`$ is relevant, else 0.
100
+ - $`P(i)`$ is the precision at $`i`$, which is the share of the top $`i`$ documents that are relevant.
101
+ - $`R`$ is the number of relevant documents in the whole query. $`\mathrm{AP}@k`$ is 0.0 when $`R`$ is 0.
102
+
103
+ ### Reciprocal rank
104
+
105
+ The reciprocal rank, $`\mathrm{RR}@k`$, is 1 divided by the rank of the first relevant document. It is 1.0 when the top document is relevant, and 0.5 when the first relevant document is at rank 2. `mrr` is the mean reciprocal rank, which is the mean of $`\mathrm{RR}@k`$ over the queries.
106
+
107
+ ```math
108
+ \mathrm{RR}@k = \frac{1}{r}
109
+ ```
110
+
111
+ - $`r`$ is the rank of the first relevant document in ranks 1 to $`m`$. $`\mathrm{RR}@k`$ is 0.0 when there is none.
112
+
113
+ ### Recall
114
+
115
+ The recall, $`\mathrm{Recall}@k`$, is the share of the query's relevant documents that appear in the top $`k`$. A low value means many relevant documents sit below rank $`k`$.
116
+
117
+ ```math
118
+ \mathrm{Recall}@k = \frac{1}{R} \sum_{i=1}^{m} \mathit{hit}_i
119
+ ```
120
+
121
+ - $`\mathit{hit}_i`$ is 1 when the document at rank $`i`$ is relevant, else 0.
122
+ - $`R`$ is the number of relevant documents in the whole query. $`\mathrm{Recall}@k`$ is 0.0 when $`R`$ is 0.
123
+
124
+ ## Scoring one query with every metric
125
+
126
+ In the example below, a made-up query has five documents. The table lists them in the order the model ranked them, highest score first. With a relevance grade of 0.5, Magnesium glycinate and Magnesium oxide are relevant, so $`R`$ is 2.
127
+
128
+ | Rank | Product | Label | Relevant |
129
+ |---|---|---|---|
130
+ | 1 | Fish oil | 0.2 | No |
131
+ | 2 | Magnesium glycinate | 0.8 | Yes |
132
+ | 3 | Zinc | 0.1 | No |
133
+ | 4 | Magnesium oxide | 0.6 | Yes |
134
+ | 5 | Vitamin D3 | 0.0 | No |
135
+
136
+ The table below scores that order with each metric twice, once on the top 3 documents and once on all five. The scores come from `Ltr::Metrics::Metrics` run on these labels.
137
+
138
+ | Metric | Top 3 documents (`@3`) | All documents (no `@k`) | Reason |
139
+ |---|---|---|---|
140
+ | Normalized discounted cumulative gain (`ndcg`) | 0.5903 | 0.7666 | `@3` leaves Magnesium oxide (0.6) out of DCG, but IDCG@3 still counts 0.8, 0.6 and 0.2. |
141
+ | Precision (`precision`) | 0.3333 | 0.4000 | One of the top 3 documents and two of all 5 are relevant. |
142
+ | Mean average precision (`map`) | 0.2500 | 0.5000 | `@3` finds one relevant document, at rank 2 with $`P(2) = 0.5`$, and still divides by $`R = 2`$. |
143
+ | Mean reciprocal rank (`mrr`) | 0.5000 | 0.5000 | The first relevant document is at rank 2 in both. |
144
+ | Recall (`recall`) | 0.5000 | 1.0000 | The top 3 documents hold one of the 2 relevant documents, and all five hold both. |
145
+
146
+ ## How the metrics differ
147
+
148
+ The table compares the five metrics on the relevance grade, on a `k` larger than the query, and on a query with no relevant document.
149
+
150
+ | Metric | Uses the relevance grade | When `k` is larger than the number of documents | Score of a query with no relevant document |
151
+ |---|---|---|---|
152
+ | Normalized discounted cumulative gain (`ndcg`) | No | Same as no `@k` | 0.0 when no document in the top `k` has a label above 0 (without `@k`, when every label is 0), otherwise above 0 |
153
+ | Precision (`precision`) | Yes | Still divides by `k` | 0.0 |
154
+ | Mean average precision (`map`) | Yes | Same as no `@k` | 0.0 |
155
+ | Mean reciprocal rank (`mrr`) | Yes | Same as no `@k` | 0.0 |
156
+ | Recall (`recall`) | Yes | 1.0 when $`R`$ is above 0 | 0.0 |
157
+
158
+ Two of the metrics can't reach 1.0 for some queries. Average precision adds one $`P(i)`$ for each relevant document in the top $`m`$, and each $`P(i)`$ is at most 1. The top $`m`$ holds at most $`\min(m, R)`$ relevant documents. But average precision divides the sum by $`R`$, which counts every relevant document in the query. So when $`R`$ is larger than $`m`$, the score stays below 1.0. Precision divides by $`k`$, but at most $`\min(m, R)`$ of the top $`m`$ documents are relevant.
159
+
160
+ ```math
161
+ \mathrm{AP}@k \le \frac{\min(m, R)}{R}
162
+ \qquad
163
+ \mathrm{Precision}@k \le \frac{\min(m, R)}{k}
164
+ ```
165
+
166
+ So a query with 3 relevant documents scores at most 0.6667 on `map@2`, and a query with 3 documents scores at most 0.6 on `precision@5`. Without `@k`, recall and precision do not depend on the model's order. Recall is then 1.0 for every query with a relevant document, and precision is the share of relevant documents.
@@ -0,0 +1,73 @@
1
+ # Model and feature store files
2
+
3
+ The files that deployment writes: the model, `features.json` and the feature store JSON. The model file also holds the feature transform steps and the one-hot column names. A local model file holds the feature store too. The dataset they are built from is in [Modelling dataset CSV](dataset-csv.md).
4
+
5
+ ## Model file
6
+
7
+ - Format: XGBoost UBJSON.
8
+ - Local deployment writes the file to `deploy.local_path` when the `deploy.metric` score is at or above `deploy.minimum_metric_value` (see [Config](config.md#deploy)). `.ubj` is the extension in the shipped config. A relative path is resolved against the root directory set in the gem configuration.
9
+ - The deployer writes to a temp file and renames it over `deploy.local_path`. If that path is a symlink, the symlink is replaced. Its target is not changed.
10
+ - SageMaker deployment packages the model as `xgboost-model.ubj` in a `model.tar.gz`. The archive also holds `code/inference.py`, `code/features.json`, and `code/feature_store.json` when the feature store is included. The deploy builds the archive in a temp folder, not in the gem's install folder.
11
+ - Both deployments store the feature transform steps from training in the model file, as the XGBoost attribute `feature_transforms`. See [Feature transforms](#feature-transforms).
12
+ - Both deployments also store the one-hot column names from the dataset, as the XGBoost attribute `one_hot_columns`. See [One-hot columns](#one-hot-columns).
13
+ - Local deployment also stores the feature store in the model file, as the XGBoost attribute `feature_store`, when `feature_store.include_in_deployment` is `true`. See [Feature store JSON](#feature-store-json). The SageMaker model does not carry it, because the store is bundled as a file.
14
+ - The archive is uploaded to `s3://<deploy.sagemaker_bucket>/ltr/models/<model.name>-<unix time>/model.tar.gz`.
15
+ - The endpoint is named `<model.name>-endpoint`.
16
+
17
+ ## `features.json`
18
+
19
+ A JSON array of feature names. The endpoint uses it only when the model file has no feature names.
20
+
21
+ ```json
22
+ ["relevancy", "bm25_name", "bm25_name_rank", "view_count"]
23
+ ```
24
+
25
+ ## Dataset serving file
26
+
27
+ `ltr:aggregate` deletes the old `<modelling_dataset_path without .csv>.serving.json` after build and enrichment. It saves the CSV, then writes a new serving file next to it. The file holds the feature transform steps under `feature_transforms` and the one-hot column names under `one_hot_columns`. Both keys are required. The value of each key is a list, which can be empty.
28
+
29
+ Local and SageMaker deploys read this file before saving the model. If a local file is missing or S3 returns `NoSuchKey`, deploy raises `Ltr::ConfigurationError` and says to run `ltr:aggregate` again. Run it for any existing dataset that lacks the combined file. A file that omits either key raises `KeyError` before deploy changes the model.
30
+
31
+ For an S3 dataset, the runner needs `s3:PutObject` and `s3:DeleteObject` to write and clear the serving file. It needs `s3:GetObject` to read it. If the runner lacks `s3:ListBucket` on the dataset bucket, S3 can return `AccessDenied` for a missing key. Deploy passes `AccessDenied` through. It does not treat it as a missing file.
32
+
33
+ ## Feature transforms
34
+
35
+ The feature transforms that training applied, in the order it applied them. The list is empty when `feature_transformations` is not set. The scorer applies them to every value the request sends, including feature-store features. It does not apply them to a value it reads from the feature store, in either backend, because the store is built from the transformed dataset. A `z_score` step carries the mean and the standard deviation from the training data.
36
+
37
+ ```json
38
+ [
39
+ { "feature": "view_count", "transform": "log1p" },
40
+ { "feature": "view_count", "transform": "z_score", "mean": 4.1, "std": 1.7 }
41
+ ]
42
+ ```
43
+
44
+ Deploy copies the steps from the [dataset serving file](#dataset-serving-file) to the XGBoost attribute `feature_transforms` as a JSON string. `LocalReranker` and `inference.py` read the attribute when they load the model. A model saved without the attribute has no steps.
45
+
46
+ ## One-hot columns
47
+
48
+ A JSON array of the one-hot column names that `ltr:aggregate` made, such as `["query_type_brand", "query_type_freehand"]`. The scorer treats these columns as `0`, not as missing, when the request and the feature store leave them out. The `0` goes through the feature transform steps once.
49
+
50
+ Deploy copies the names from the [dataset serving file](#dataset-serving-file) to the XGBoost attribute `one_hot_columns` as a JSON string. `LocalReranker` and `inference.py` read the attribute when they load the model. A model saved without the attribute has no names.
51
+
52
+ ## Feature store JSON
53
+
54
+ The feature store holds per-document values that are not known at search time.
55
+ `Ltr::Deploy::FeatureStoreDeployer` builds it from the modelling dataset.
56
+ It maps each feature name to an object of doc id to value.
57
+
58
+ ```json
59
+ {
60
+ "view_count": { "prodA": 340.0, "prodB": 12.0 },
61
+ "purchase_count": { "prodA": 21.0 }
62
+ }
63
+ ```
64
+
65
+ - The features come from `feature_store.features`, or from SSM when SSM is enabled.
66
+ - The dataset must have the `doc_id_field` column and a column for each feature. The build raises a `RuntimeError` that names the missing columns when one is absent.
67
+ - Doc ids come from the `doc_id_field` column. The first row for a doc id supplies its values.
68
+ - Empty cells, `NaN`, and blank doc ids are skipped. A doc id with no value for a feature has no entry under that feature.
69
+ - Number-like text becomes a float. Other text stays text.
70
+ - The map is built in memory. Nothing is written to disk or uploaded on its own.
71
+ - When `feature_store.include_in_deployment` is `true`, the SageMaker deployment also bundles the file as `code/feature_store.json` in the model archive.
72
+ - When it is `true`, the local deployment stores the same map in the model file as a compact JSON string in the attribute `feature_store`, before it saves the model. It removes the attribute from the booster after the save. `LocalReranker` reads the attribute when it loads the model, so a new model is never served with an old store. The model file grows by the size of the JSON, and the store is in memory twice while the model is loaded. A model saved without the attribute has no store.
73
+ - Both deployers build the store without an upload. They need `feature_store.features` and the dataset. They need no `deploy.sagemaker_bucket`.
@@ -0,0 +1,72 @@
1
+ # Optimization
2
+
3
+ `ltr:optimize` runs `Ltr::Optimize::OptimizePipeline`, which picks the features and the XGBoost hyperparameters that `ltr:train` uses. This page explains what one trial is, the order of feature selection and the hyperparameter search, how the Bayesian search picks each hyperparameter point to try, and which config sections and AWS Systems Manager Parameter Store (SSM) parameters the pipeline writes.
4
+
5
+ ## What a trial is
6
+
7
+ A trial trains one XGBoost model on the `train` split, with early stopping on `training.early_stopping_split`. It then scores `optimization.metric_to_optimize` on `optimization.split`, averaged over the queries in that split. Both stages of the pipeline are a series of trials. The shipped config early stops on `test` and scores `ndcg@12` on `val`. [Data splits](data-splits.md#which-split-each-stage-reads) explains the split roles and the fallback to `test` when a split has no rows.
8
+
9
+ ## The order of the two stages
10
+
11
+ | Stage | Changes per trial | Fixed |
12
+ |---|---|---|
13
+ | 1. Feature selection, `OptimizeFeatures` | the feature set | `model.hyperparameters` |
14
+ | 2. Hyperparameter search, `OptimizeHyperparameters` | the `hyperparameter_search_space` values | the stage 1 features |
15
+
16
+ The pipeline runs each stage once, in this order, so stage 1 trains with the hyperparameters already in the config. When `ssm.enabled` is `true`, the hyperparameters in SSM replace `model.hyperparameters` before stage 1 starts. The YAML values are used only when the SSM parameter does not exist yet.
17
+
18
+ ## Feature selection
19
+
20
+ The candidate features are `optimization.search_time_features`, the features that `feature_engineering` derives from them (such as `bm25_name_rank`), and `optimization.feature_store_features`. A candidate that is not a column in the dataset is left out with a warning. For a text column from a `dataset_enricher`, list its `<column>_<value>` flag names. The source column is not in the dataset. The top-level `search_time_features` and `feature_store.features` are not candidates. They are what the pipeline writes at the end.
21
+
22
+ The strategy in `optimization.feature_selection.strategy` tries smaller sets, never below `optimization.min_features` features. It keeps the set with the highest penalized score, `raw_score - feature_count * complexity_penalty`. With the shipped `complexity_penalty: 0.0001`, each kept feature lowers the penalized score by 0.0001 `ndcg@12`. Set it below the metric gain one useful feature brings. A larger value pushes the set down to `min_features`. [Feature selection](feature-selection.md) shows how to pick it and compares the three strategies and their cost in trainings. Every optimize trial is seeded, so a different top-level `seed` can choose a different feature list.
23
+
24
+ ## The search space
25
+
26
+ Each key in `optimization.hyperparameter_search_space` has a `min` and a `max`, and `SearchSpace` gives each parameter one of two types and one of two scales:
27
+
28
+ - A parameter is an integer when both bounds are integers, like `max_depth: {min: 3, max: 10}`. Otherwise it is a float.
29
+ - A parameter uses a log scale when both bounds are positive and `max / min` is at least 20. Otherwise the scale is linear. None of the five shipped parameters has a ratio that large.
30
+
31
+ The search works on a unit cube. Each parameter maps to a number from 0 to 1, on its own scale, and integer parameters are rounded and kept inside their bounds when a unit-cube point turns back into parameter values. The Gaussian process measures distance between points in this cube, so every parameter has the same weight whatever its units.
32
+
33
+ ## The hyperparameter search
34
+
35
+ `BayesianOptimizer` minimizes, so each trial returns the negative of the metric. A hyperparameter trial merges the sampled values over the full `model.hyperparameters` hash, then trains and scores as above.
36
+
37
+ ```mermaid
38
+ flowchart TB
39
+ A["5 Latin hypercube points<br>one trial each"] --> B["Fit the Gaussian process<br>to every trial so far"]
40
+ B --> C["Score 1,000 candidates<br>by expected improvement"]
41
+ C --> D["Run a trial on the candidate<br>with the highest score"]
42
+ D --> E{{"50 guided trials, or 10 in a row<br>with tiny expected improvement?"}}
43
+ E -->|"no"| B
44
+ E -->|"yes"| F["Keep the trial<br>with the best metric"]
45
+ ```
46
+
47
+ **Starting points.** `optimization.n_init: 5` trials come from a Latin hypercube. Each parameter's 0 to 1 range is cut into 5 equal slices, and each slice gives one value at a random place inside it. The slices are shuffled separately for each parameter, so each trial gets a different mix.
48
+
49
+ **The Gaussian process.** `GaussianProcess` fits an RBF kernel to the unit-cube points and their trial values. Before guided trials 1, 11, 21, 31 and 41, it tries 24 pairs of length scale and variance and keeps the pair with the highest log marginal likelihood. `optimization.bayesian_optimizer.optimize_hyperparameters_every` sets that interval. It defaults to 10. `kernel_lengthscale: 0.3` and `kernel_variance: 1.0` are used as-is only when the interval is `0`. When the interval is positive, the first guided trial refits the kernel first, so the default refit replaces them.
50
+
51
+ **Expected improvement.** `ExpectedImprovement` scores a point by how far its predicted value is expected to fall below a target. The target is the best trial value so far minus a margin `xi`. `xi` is in units of the score std. It starts at `optimization.bayesian_optimizer.ei_xi: 0.5` and falls in a straight line to `ei_xi / iterations` on the last step, which is 0.01 with 50 trials.
52
+
53
+ **Candidates.** `CandidateSelector` scores `optimization.bayesian_optimizer.candidates_per_iteration: 1000` points on each guided trial. 800 are random points in the space. The other 200 are random changes to the 5 random points with the highest expected improvement in that same batch. Each change moves every unit-cube value by up to a radius, and the radius falls from 0.2 on the first guided trial to 0.02 on the last. The candidate with the highest expected improvement is the next trial. The top-level `seed` seeds the starting points and the candidates. Each trial trains XGBoost with the same top-level `seed`.
54
+
55
+ **Stopping.** The search stops after `optimization.iterations: 50` guided trials, so a full search is 55 trainings. It stops early after 10 guided trials in a row where the highest expected improvement is below 0.0001 times the range of trial values seen so far.
56
+
57
+ The result is the best trial that actually ran, not a point that the Gaussian process predicts. Its values are merged over `model.hyperparameters`. [Config](config.md#optimization) lists every key in this section and its default.
58
+
59
+ ## What gets written back
60
+
61
+ `UpdateConfig` rewrites four sections of the override config file, or of the base file when there is no override:
62
+
63
+ | Section | New value |
64
+ |---|---|
65
+ | `search_time_features` | the kept search-time features and the kept derived features |
66
+ | `feature_store.features` | the kept feature-store features |
67
+ | `optimized_features` | the full kept feature list, the same list that is saved to SSM as `all_features` |
68
+ | `model.hyperparameters` | the full hash, including the keys that were not searched |
69
+
70
+ It rewrites the lines under each key and keeps the comments. It adds a section that is missing. [Config](config.md#change-the-config-from-ruby) lists its matching rules and where it adds a section.
71
+
72
+ When `ssm.enabled` is `true`, `Ssm::Saver` then writes three JSON values to the paths in the `ssm` section. These are the full kept feature list, the kept feature-store features and the hyperparameters. The kept feature-store list may be empty. Each write replaces the old value. With SSM enabled, `ltr:train` reads these parameters and ignores the YAML features and `model.hyperparameters`. See [Config](config.md#ssm).
@@ -0,0 +1,67 @@
1
+ # Public API stability
2
+
3
+ These entry points are used by host apps. Their signatures must stay stable.
4
+
5
+ ## Pipelines and inference
6
+
7
+ - `Ltr::DatasetAggregation::DatasetPipeline.call(config)`, `Ltr::Optimize::OptimizePipeline.call(config)` and `Ltr::Train::ModellingPipeline.call(config)`. Each returns a `Ltr::PipelineResult`. The keys are in [Host integration](host-run-pipelines.md#run-the-pipelines-from-ruby). The `metrics` and `optimization_split_metrics` hashes of `ModellingPipeline` use lowercase metric names as keys, such as `"ndcg@5"`, whatever case the config uses.
8
+ - `Ltr::Inference::Base.call(payload, config, backend_type = nil, **options)`. The local backend reads `options[:custom_model_path]`. The SageMaker backend reads `options[:custom_model_endpoint]`.
9
+ - `Ltr::Inference::SagemakerClient.call(payload, config, custom_model_endpoint)` (`config` may be `nil` when `custom_model_endpoint` is given)
10
+ - `Ltr::Inference::LocalReranker.call(payload, config, custom_model_path = nil)`
11
+ - `Ltr::Inference::LocalReranker.reset!` clears the cached models. See [Inference](inference.md).
12
+
13
+ ## Configuration and tasks
14
+
15
+ - `Ltr.configure` and the settings it yields: `logger`, `s3_client_builder`, `opensearch_connect_options_builder`, `error_reporter` and `root`
16
+ - `Ltr::ConfigLoader.new(base_config_path:, override_config_path: nil, validate: true)`, `#reload!` and `#save!`
17
+ - `Ltr::ConfigLoader` accessors (`model_name`, `seed`, `ssm`, `deploy`, `query_id_field`, `doc_id_field`, ...) and the writers `hyperparameters=`, `search_time_features=`, `feature_store_features=` and `optimized_features=`. `#all_features` returns `optimized_features` as is when it is set
18
+ - `Ltr::PipelineResult`, with `#[]` and `#to_h`
19
+ - `Ltr::Ssm::Loader.call(config, load_all_features:, load_feature_store_features:, load_hyperparameters:)`. All three keywords default to `false`.
20
+ - The `ltr:aggregate`, `ltr:optimize` and `ltr:train` rake tasks and their arguments. See [Rake tasks](rake-tasks.md).
21
+
22
+ ## Errors
23
+
24
+ - `Ltr::Error`, `Ltr::ConfigurationError`, `Ltr::InvalidDatasetError`, `Ltr::DeployError` and `Ltr::SqliteError`. `SqliteError` has `#statement` and `#error_code`. See [Errors](errors.md).
25
+
26
+ ## Subclassing hooks
27
+
28
+ - `Ltr::DatasetAggregation::DatasetEnricher.call(dataset, config:)` and `#fetch_features`. It receives the doc ids as they are in the dataset and returns a frame keyed by `dataset_builder.doc_id_field`. See [Dataset enrichers](dataset-enrichers.md).
29
+ - `Ltr::DatasetAggregation::LabelTransformer#transform(aggregated_data)`. It takes an `Ltr::Data::RowStore` and returns the labelled `RowStore`. See [Label transformers](label-transformers.md).
30
+ - `Ltr::DatasetAggregation::PerQueryLabelTransformer#query_labels(values)`. A subclass overrides this private method. It gets the `raw_label` floats of one query and returns one label per value, in the same order. Do not override `transform`, because it groups the rows by `qid` and calls `query_labels` once per query. See [Label transformers](label-transformers.md#write-a-per-query-transformer).
31
+ - `Ltr::DatasetAggregation::PerQueryLabelTransformer.settings_from(label_transformer)`. A subclass may override it. It gets the `label_transformer` settings hash and returns the settings that `query_labels` reads from `settings`. The default returns `{}`. `ConfigValidator` also calls it when the config loads, so it runs before any dataset exists. Raise `Ltr::ConfigurationError` for a bad value.
32
+ - `Ltr::DatasetAggregation::LabelTransformer` helpers `config`, `pluck_column`, `set_labels` and `zero_labels`. Subclasses call them inside `transform`.
33
+
34
+ ## Host entry points
35
+
36
+ - `Ltr::DatasetAggregation::UbiDataLoader.call(config, start_date: nil, end_date: nil, n_events: nil, custom_queries_filters: nil, custom_events_filters: nil)`. It loads UBI events and their queries from OpenSearch into memory. It fetches only events whose action is a cascade action, so `n_events` counts only those. It returns a hash with `:queries` and `:events`, which are arrays of hashes. Each query hash holds only the query id field, `user_query`, `query_attributes`, `timestamp`, the hit ids field and each `dataset_builder.additional_qid_fields` name. Each event hash holds only the query id field, `action_name` and `event_attributes`. A keyword left as `nil` gets a default. `start_date` and `end_date` must be plain `Date` objects. A `Time`, `DateTime` or `TimeWithZone` raises `ArgumentError`. Both are read as UTC dates. The window runs from `start_date` at `00:00:00Z` to `end_date` at `23:59:59Z`. When `start_date` is `nil`, it is `ubi_data_loader.max_days_ago` days before the current UTC date, so that key is required. When `end_date` is `nil`, it is the current UTC date. `n_events` is `ubi_data_loader.n_events`, so that key is required when `n_events` is `nil`. Each custom filter list is read from the file at `config.custom_filters`, or is `[]` when no file is set. It raises `Ltr::ConfigurationError` when `dataset_builder.conversion_rate_targets` is missing or empty, or a `conversion_features` action is neither `impression` nor a cascade action, or a cascade action's `<action>_count` column is not a usable name, or `dataset_builder.additional_qid_fields` is not an array of strings, holds a bad, reserved or repeated name, or holds a name equal to an `<action>_count` column. It raises `ArgumentError` when the dates or the event count are invalid, when a custom filter list is not an `Array`, or when `ubi_data_loader.opensearch.url` is blank. A connection error, a timeout, an HTTP 5xx error, a 408 or a 429 is tried up to 5 times in total, then raised. Any other OpenSearch error is raised at once, including every HTTP 4xx error except 408 and 429. See [Errors](errors.md).
37
+ - `Ltr::Metrics::MetricScores.call(preds, labels, metrics, min_relevance_grade: 1, ndcg_exp_gain: false)`. It scores one list of predictions against its labels. `metrics` is a list of specs such as `ndcg@10`. The names are `ndcg`, `map`, `mrr`, `precision` and `recall`. Without a cutoff, a spec uses every item. The case of a name does not matter, and the keys are lowercase. It returns a hash of spec to score, rounded to 4 places. It raises `ArgumentError` for any other name.
38
+
39
+ ## Data helpers
40
+
41
+ - `Ltr::Data::Csv.read(config)`. `config` must respond to `modelling_dataset_path` and `doc_id_field`, as `Ltr::ConfigLoader` does. The `doc_id_field` column always loads as text. Its values are `String`, or `nil` for an empty cell. See [Modelling dataset CSV](dataset-csv.md#reading-rules).
42
+ - `Ltr::Data::Csv.standardize_nans(df)`
43
+ - `Ltr::Train::Utils.filter_features(df, features, mode)`
44
+
45
+ ## UBI logging
46
+
47
+ - `Ltr::Ubi.query(config:, query_id:, user_query:, timestamp:, scores:, hit_ids:, application: nil, client_id: nil, query_response_id: nil)`
48
+ - `Ltr::Ubi.event(config:, query_id:, action_name:, doc_id:, timestamp:)`
49
+
50
+ `config:` is the `Ltr::ConfigLoader` of the model. Both methods raise `ArgumentError` when it is not one.
51
+
52
+ Anything else may change in a minor release. Breaking changes are listed in the [changelog](../CHANGELOG.md).
53
+
54
+ ## Internal
55
+
56
+ These classes are called by the gem itself. The docs do not tell a host to call them. Each one may change in a minor release.
57
+
58
+ - `Ltr::PipelineTask.call(name, base_config_path: nil, override_config_path: nil)` (`lib/ltr/support/pipeline_task.rb`) is what the `ltr:*` rake tasks call. When `LTR_CONFIG` is set and only one path is passed, that path is the override and `LTR_CONFIG` is the base. `name` is `:aggregate`, `:optimize` or `:train`. It builds a `ConfigLoader`, runs the pipeline and logs a summary. It raises `ArgumentError` for an unknown name or when no config path is set. To run a pipeline from Ruby, call the pipeline class instead. See [Host integration](host-run-pipelines.md#run-the-pipelines-from-ruby). The path rules are in [Rake tasks](rake-tasks.md).
59
+ - `Ltr::Ssm::Saver.call(config)` (`lib/ltr/ssm/saver.rb`) is called by `OptimizePipeline` when `ssm.enabled` is the boolean `true`. It writes `all_features`, `feature_store_features` and `hyperparameters` to the three `ssm.*_param_path` parameters as JSON. It overwrites old values. It raises `ArgumentError` when a path is blank, when `all_features` or `hyperparameters` is empty, when `feature_store_features` is `nil`, or when a JSON value is over 8192 bytes. It writes with the `Intelligent-Tiering` tier, so a value over 4096 characters becomes an Advanced parameter. A host reads the values back with `Ssm::Loader` (above).
60
+ - `Ltr::Data::DatasetLoader.load(config)` (`lib/ltr/data/dataset_loader.rb`) is called by the optimize and train pipelines. It calls `Data::Csv.read` and `Data::Csv.standardize_nans`, then checks that the dataset has `qid`, `label` and `split`. It is also called by `XgbTrainer` and `XgbEvaluator` when they get no `df`. It raises `Ltr::InvalidDatasetError` for a missing column. It raises the same error for a missing local file, a missing header row and a non-numeric value in a numeric column. A host that wants a dataframe should call `Data::Csv.read` (above).
61
+ - `Ltr::Callable` (`lib/ltr/support/callable.rb`) gives a class the class method `.call(*args, **kwargs, &block)`. It runs `new(*args, **kwargs).call(&block)`. The base classes `DatasetEnricher` and `LabelTransformer` extend it, so a host subclass inherits `.call`. The pipeline calls `.call` on your class, so do not override `.call` or `#call`. Override `fetch_features` or `transform`.
62
+ - `Ltr::Optimize::UpdateConfig.call(config, paths: ...)` (`lib/ltr/optimize/update_config.rb`) is called by `ConfigLoader#save!`, which `OptimizePipeline` calls after it sets the new values on the loader. `paths:` limits the rewrite to those sections. A section the file lacks is added. It rewrites the `search_time_features`, `optimized_features`, `features` and `hyperparameters` sections of `config.writable_config_path` by matching lines, not YAML. Its rules and known limitations are in [Config](config.md#change-the-config-from-ruby).
63
+ - `Ltr::Deploy::SagemakerDeployer` is called by `Train::DeployGate`. Its hash is `result[:deployment][:endpoint]`. See [Host integration](host-run-pipelines.md#deployment-results).
64
+ - `Ltr::Deploy::LocalDeployer` is called by `ModellingPipeline`. Its hash does not reach the result. `ModellingPipeline` builds `result[:local_deployment]` as `{ deployed: true, reason: :local_saved, path: info[:path] }`. It builds `{ deployed: false, reason: :not_configured }` when `deploy.local` is not `true`. It builds `{ deployed: false, reason: :below_threshold, metric:, score:, threshold: }` when the `deploy.metric` score is below `deploy.minimum_metric_value`.
65
+ - `Ltr::Deploy::FeatureStoreDeployer` is called through `FeatureStoreDeployer.for_deployment` for `SagemakerDeployer` and `LocalDeployer`. Its hash never reaches the result.
66
+ - `Ltr::Data::Splits` (`lib/ltr/data/splits.rb`) holds the split names `TRAIN` (`"train"`), `VAL` (`"val"`) and `TEST` (`"test"`), the list `NAMES`, and `FALLBACK` (`TEST`). Its class methods pick a split for early stopping, optimization and evaluation. The rules are in [Modelling dataset CSV](dataset-csv.md#split-values).
67
+ - `Ltr::Optimize::FeatureSelection::Strategy` (`lib/ltr/optimize/feature_selection/strategy.rb`) is the base class of the strategies. Its `STRATEGIES` hash is closed. A host picks a strategy by name in config. See [Feature selection](feature-selection.md#choose-a-strategy).