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
data/docs/config.md ADDED
@@ -0,0 +1,516 @@
1
+ # Config
2
+
3
+ Every key the gem reads from the pipeline YAML.
4
+
5
+ The gem ships `lib/ltr/configuration/example_config.yml` as a template.
6
+ Copy it into your app and edit the copy.
7
+ The gem never loads it as a base file.
8
+
9
+ This page lists keys, types, and what happens when a key is missing.
10
+ It does not explain the ranking math.
11
+ For that, see [Features](features.md), [Labels from behavior](labels-from-behavior.md), and [Metrics](metrics.md).
12
+
13
+ Contents:
14
+
15
+ 1. [How a file is loaded](#how-a-file-is-loaded)
16
+ 2. [Top-level name](#top-level-name)
17
+ 3. [seed](#seed)
18
+ 4. [model](#model)
19
+ 5. [training](#training)
20
+ 6. [search_time_features](#search_time_features)
21
+ 7. [feature_engineering](#feature_engineering)
22
+ 8. [feature_store](#feature_store)
23
+ 9. [feature_transformations](#feature_transformations)
24
+ 10. [evaluation](#evaluation)
25
+ 11. [optimization](#optimization)
26
+ 12. [ubi_data_loader](#ubi_data_loader)
27
+ 13. [dataset_builder](#dataset_builder)
28
+ 14. [dataset_aggregation](#dataset_aggregation)
29
+ 15. [dataset_enricher](#dataset_enricher)
30
+ 16. [label_transformer](#label_transformer)
31
+ 17. [deploy](#deploy)
32
+ 18. [inference](#inference)
33
+ 19. [ssm](#ssm)
34
+
35
+ ## How a file is loaded
36
+
37
+ `Ltr::ConfigLoader` reads the base file in `lib/ltr/configuration/config_loader.rb`.
38
+ It runs the file as ERB first.
39
+ `<%= ENV["OPENSEARCH_URL"] %>` is legal.
40
+ It then parses the result as YAML.
41
+ An unquoted date loads as a `Date` and an unquoted timestamp loads as a `Time`.
42
+ Quote a value to keep it a string.
43
+ No key the gem reads is a date today.
44
+
45
+ The table shows how each key in an override file merges into the base file.
46
+
47
+ | Case | Merged value |
48
+ |---|---|
49
+ | A key is in both files and the override gives it no value or `~` | The base value stays. For example, `seed: ~` keeps an existing base `seed`. |
50
+ | A key is only in the override | The override adds the key, even if its value is null. |
51
+ | Both values are hashes | The hashes merge key by key using these same rules. |
52
+ | Any other value for a key in both files | The override value replaces the base value, including when it is a list. Use `[]` to empty a list or `false` to turn off a boolean setting. |
53
+
54
+ `Ltr::ConfigValidator` then checks the merged hash.
55
+ A bad value raises `Ltr::ConfigurationError` at load.
56
+ A key the gem does not know logs a warning and the load goes on.
57
+ The warning names the key path, for example ``Unknown config key `ssm.enable` ``.
58
+ The check skips the contents of `model.hyperparameters`, `optimization.hyperparameter_search_space` and `dataset_builder.split_ratios`.
59
+ It also skips `label_transformer` when `class` is not an `Ltr::DatasetAggregation::` transformer, because a custom transformer reads its own keys.
60
+ `validate: false` skips both checks.
61
+ A missing top-level section is skipped by the validator.
62
+ The pipeline that needs that section raises later.
63
+ Pass `validate: false` to `ConfigLoader.new` to skip the validator.
64
+ `validate: false` does not skip `FeatureEngineering.validate_methods!`. `reload!` still runs it, so an unknown `feature_engineering` method still raises `ArgumentError`.
65
+
66
+ `Ltr::ConfigLoader.new` needs `base_config_path:`. It has no default path.
67
+ `override_config_path:` is optional. `validate:` defaults to `true`.
68
+ `reload!` and `save!` are instance methods. `reload!` reads the files again. Both `new` and `reload!` raise `Ltr::ConfigurationError` when a config file is missing or cannot be loaded. `save!` writes the keys the writers changed to `writable_config_path`.
69
+ The gem keeps no global loader. Pass a loader to `Ltr::Ubi` as `config:`. See [Host integration](host-integration.md#one-host-two-models).
70
+
71
+ ### Change the config from Ruby
72
+
73
+ `OptimizePipeline` uses four writers to put its results on the loader. They change the loader in memory only.
74
+
75
+ | Writer | Sets | Needs |
76
+ |---|---|---|
77
+ | `hyperparameters=` | `model.hyperparameters` | the `model` section |
78
+ | `search_time_features=` | `search_time_features` | nothing. It creates the key. |
79
+ | `feature_store_features=` | `feature_store.features` | the `feature_store` section |
80
+ | `optimized_features=` | `optimized_features` | nothing. It creates the key. |
81
+
82
+ `hyperparameters=` and `feature_store_features=` raise `NoMethodError` when their section is missing, because they index into `nil`. They do not validate the value.
83
+
84
+ `save!` writes only the keys that the writers changed to `writable_config_path`. That is the override file when there is one, else the base file. It edits the text of that file with `Ltr::Optimize::UpdateConfig`, so it does not run ERB and does not parse the file. ERB tags, other keys and comments outside the changed sections stay as they were. A changed section is written whole from the value you set. ERB tags inside it are lost, and values read from the loader are written already resolved. So a value copied from the base, such as `hyperparameters.merge(...)`, ends up in the override file. A changed key the file does not have is added. A nested key goes under its parent key, and the parent is added when it is missing. `reload!` also forgets the changed keys, so a later `save!` writes nothing. A `save!` with no changed keys does not touch the file.
85
+
86
+ `hyperparameters=` converts the keys to strings. So `save!` writes `max_depth: 9`, and `ConfigLoader` loads it again. `OptimizePipeline.call(loader)` calls `save!` itself, so a `save!` after it writes nothing.
87
+
88
+ `save!` and the four writers are part of the [public API](public-api.md), as `ConfigLoader` accessors. `OptimizePipeline` calls `save!`, which uses `Ltr::Optimize::UpdateConfig` (`lib/ltr/optimize/update_config.rb`). That class rewrites the file by line pattern, not by YAML. These are its rules and known limitations of the current code.
89
+
90
+ - It matches `search_time_features:` and `optimized_features:` at column 0, and the two-space keys ` features:` and ` hyperparameters:`.
91
+ - The `features:` and `hyperparameters:` patterns match under any top-level section.
92
+ - After a matched key it drops the lines under it. Those are the lines indented deeper than the key, blank lines, and list items at the key's own indent.
93
+ - The first other line ends the section. A sibling key after `features:` or `hyperparameters:`, such as `include_in_deployment: true`, is kept. So is a comment right before it.
94
+ - A list at the key's own indent is replaced too (column 0 for `search_time_features`). Psych writes that layout, so `ltr:optimize` works on a file that Psych wrote.
95
+ - A comment belongs to the section when the next line that is not blank or a comment does. A comment before a line outside the section stays where it is.
96
+ - The comments in the section are kept. They are written right after the key, before the new content, in their original order.
97
+ - Exactly one blank line follows a replaced section, even when the file had none.
98
+ - A missing section is added: a top-level key at the end of the file, and a nested key right under its parent key.
99
+ - A parent key with a comment on its line, such as `model: # tuned`, is found. A parent with a value on the same line, such as `model: {}`, raises `Ltr::ConfigurationError`. A parent whose children are not indented by two spaces raises `Ltr::ConfigurationError`.
100
+ - It leaves a key that has a value or comment on the same line, such as `hyperparameters: # tuned`.
101
+ - It replaces a one-line list or hash, such as `search_time_features: [a]` or `features: []`. It leaves a flow list that spans lines.
102
+ - It writes a hyperparameter string bare only when it has no space and reloads as itself. Any other string is written as a double-quoted JSON string.
103
+ - It writes hyperparameter keys bare. List items follow the same string rule as hyperparameter values.
104
+ - An empty or nil list is written as `key: []`, and empty hyperparameters as `hyperparameters: {}`.
105
+ - A hyperparameter value that is a hash or an array raises `Ltr::ConfigurationError` that names the key.
106
+
107
+ For the terms used here, see the [Glossary](glossary.md).
108
+ To change the gem, see [Contributing](../CONTRIBUTING.md).
109
+
110
+ The rake tasks `ltr:aggregate`, `ltr:optimize`, and `ltr:train` do not open the shipped file by themselves.
111
+ Each task needs a path.
112
+ See `lib/ltr/support/pipeline_task.rb`.
113
+
114
+ In the tables below, "Missing" gives the fallback for a key that is absent from the merged config.
115
+ Many settings also use the same fallback when the key is present with a null value. For example, `search_time_features: ~` uses `[]`.
116
+ Some settings use their default only when the key is absent. These are examples, not a full list.
117
+ Examples are `optimization.iterations`, `optimization.n_init`, `optimization.bayesian_optimizer.noise_variance`, `label_transformer.groups` and the `inference.sagemaker` settings.
118
+ Do not set them to null.
119
+ The optimizer validation rejects a null `optimization.iterations`, `optimization.n_init` or `optimization.bayesian_optimizer.noise_variance`.
120
+ The per-query k-means transformer rejects a null `label_transformer.groups` with `Ltr::ConfigurationError`.
121
+ A null `inference` section is read as `{}`, so the defaults still apply.
122
+ A null `inference.sagemaker.open_timeout` or `inference.sagemaker.read_timeout` passes `nil` to the AWS client.
123
+ A null `inference.sagemaker` section raises `NoMethodError`, because `lib/ltr/inference/sagemaker_client.rb` calls `fetch` on it.
124
+ For a present null that validation rejects, see the `seed` row.
125
+ The tables list the shipped value when it differs from the fallback.
126
+
127
+ The Ruby writers raise `ArgumentError` for a `nil` hyperparameter value before they write any file, so write `false` to clear it.
128
+
129
+ ## Top-level name
130
+
131
+ | Key | Type | Missing | What it does |
132
+ |---|---|---|---|
133
+ | `name` | string | `nil` | `ConfigLoader#name` returns it. No pipeline in this gem branches on it. The shipped file does not set it. |
134
+
135
+ ## seed
136
+
137
+ | Key | Type | Missing | What it does |
138
+ |---|---|---|---|
139
+ | `seed` | integer | `1967` | Seeds the query shuffle before the split, negative downsampling on both engines, the hyperparameter search, and XGBoost in every training and trial. With validation on, `seed` must be an integer if it is present after the merge. A null value, a string or a float raises `Ltr::ConfigurationError` at load. With `validate: false`, a null `seed` uses `1967`. A different `seed` can select a different feature list in `ltr:optimize`, because every feature-selection trial is seeded. |
140
+
141
+ `dataset_builder.random_seed` and `optimization.random_seed` are unknown keys. Each logs an `Unknown config key` warning, and the gem ignores it.
142
+ `model.hyperparameters.seed` is replaced by the top-level `seed` before each training, with no warning.
143
+
144
+ ## model
145
+
146
+ The validator requires this section's `name` when the section is present.
147
+ `type` is not checked.
148
+
149
+ | Key | Type | Missing | What it does |
150
+ |---|---|---|---|
151
+ | `model.name` | string | Load fails if the `model` section exists. | Endpoint name is `"#{model.name}-endpoint"`. Training and deploy read it. The shipped file sets `ltr-model`. |
152
+ | `model.type` | string | `nil` | No pipeline reads it or branches on it. The shipped file sets `xgboost`. |
153
+ | `model.hyperparameters` | hash | `{}` | Must be a hash when present. The whole hash is the `params` argument to `XGBoost.train` in `lib/ltr/train/xgb_trainer.rb`. |
154
+
155
+ The gem itself reads these hyperparameter keys.
156
+ They are still passed through to XGBoost as well.
157
+
158
+ | Key | Missing | What the gem does with it |
159
+ |---|---|---|
160
+ | `n_estimators` | `100` | `num_boost_round` for `XGBoost.train`. |
161
+ | `early_stopping_rounds` | no early stopping | Passed as `early_stopping_rounds`. When it is set and the best round is before the last round, the final training runs again for `best_iteration + 1` rounds with early stopping off. That second run is only `early_stopping_rounds` rounds shorter than the first, so the final training takes close to twice as long. `ltr:optimize` trials are not affected. The deployed model holds only the rounds up to the best round, so serving uses every tree in it. |
162
+ | `verbose_eval` | `false` | Log the eval metric to `Ltr.config.logger` every N rounds, where N is this value. `true` logs every round. `false` logs none. The lines reach stdout only when the logger writes there, as the default logger does outside Rails. |
163
+ | `eval_metric` | see `objective` | Decides whether XGBoost should maximize the eval metric. The metric name before `@` (a trailing `-` is ignored) must be one of `auc`, `aucpr`, `map`, `ndcg`, `pre`, `recall` to maximize. |
164
+ | `objective` | maximize when the value starts with `rank:` | Used for that same maximize flag only when `eval_metric` is blank. |
165
+ | `ndcg_exp_gain` | treated as `true` | XGBoost's default is `true`, so a missing key trains with `2^label - 1`. The shipped example config sets `false`. The reported NDCG uses the gain the booster saved, not this value. XGBoost raises on fractional labels when the gain is exponential, so set `false` for fractional labels. See [Metrics](metrics.md). |
166
+
167
+ The shipped file also sets `lambdarank_unbiased`, `learning_rate`, `max_depth`, `lambdarank_num_pair_per_sample`, `min_child_weight`, `subsample`, and `colsample_bytree`.
168
+ The gem does not read those keys. XGBoost does.
169
+ The gem passes any other key in the hash to XGBoost the same way.
170
+ The one exception is `seed`. The top-level `seed` replaces it before each training, and the training log shows the top-level value.
171
+
172
+ These are the shipped hyperparameters. See [Training objective](training-objective.md) for the ideas behind them.
173
+
174
+ | Key | Shipped value | What it does |
175
+ |---|---|---|
176
+ | `objective` | `rank:ndcg` | The LambdaMART objective that targets NDCG. |
177
+ | `eval_metric` | `ndcg@12` | The metric XGBoost reports each round and uses for early stopping. |
178
+ | `ndcg_exp_gain` | `false` | The gain of a document is its label. When `true` it is `2^label - 1`. |
179
+ | `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 12 positions get a pairwise gradient. |
180
+ | `lambdarank_unbiased` | `true` | Turns on XGBoost's position-debiasing option. |
181
+ | `n_estimators` | `500` | Maximum number of boosting rounds. |
182
+ | `early_stopping_rounds` | `20` | Stop after this many rounds with no gain on the early-stopping split. |
183
+ | `verbose_eval` | `10` | Log the eval metric to the gem's logger every 10 rounds. |
184
+ | `learning_rate` | `0.1` | Scales the output of each new tree before it is added. |
185
+ | `max_depth` | `6` | Maximum depth of each tree. |
186
+ | `min_child_weight` | `1` | Minimum sum of instance weight in a leaf. XGBoost does not split a node when a child would fall below it. |
187
+ | `subsample` | `0.5` | Fraction of training rows that each tree samples. |
188
+ | `colsample_bytree` | `0.6` | Fraction of features that each tree samples. |
189
+
190
+ `training.nthread` is not a hyperparameter.
191
+ The trainer adds it onto the hash at train time.
192
+
193
+ ## training
194
+
195
+ | Key | Type | Missing | What it does |
196
+ |---|---|---|---|
197
+ | `training.nthread` | integer | XGBoost keeps its own thread count. | Added onto the hyperparameter hash as `nthread` when it is set. The shipped file sets `ENV["LTR_NTHREAD"]` or `4`. |
198
+ | `training.early_stopping_split` | string | `test` | Which split XGBoost watches while training. Must be `train`, `val`, or `test` when set. If the dataset has no rows for it, training uses `test` and logs a warning. If `test` is also missing, it raises `Ltr::InvalidDatasetError`. |
199
+ | `training.modelling_dataset_path` | string | Load fails if the `training` section exists. | CSV path written by dataset aggregation and read by training. Must end in `.csv`. Aggregation writes `<path>.gz`, and training reads the `.gz` first, then the plain file. See [Modelling dataset CSV](dataset-csv.md). The shipped file sets `tmp/ltr/data/ltr_dataset.csv`. A relative path starts at `Ltr.config.root`, like `deploy.local_path`. An absolute path and an `s3://` URL stay as they are. |
200
+ | `training.s3_region` | string | `nil` | Region passed to `Ltr::Deploy::SagemakerDeployer`. The shipped file sets `us-east-1`. |
201
+
202
+ ## search_time_features
203
+
204
+ A list of score names logged on the UBI query and sent again at query time.
205
+ Missing means `[]`.
206
+
207
+ `rank` and `relative_score` add columns named `<feature>_rank` and `<feature>_relative_score`.
208
+ Those columns are part of the model.
209
+ They are not listed here.
210
+ See [Features](features.md).
211
+
212
+ The shipped file sets `relevancy`, `bm25_name`, and `bm25_description`.
213
+
214
+ ## optimized_features
215
+
216
+ The exact feature list that `ltr:optimize` chose.
217
+ Missing means the model uses the search-time features, the derived columns and the feature-store features.
218
+ When it is set, `all_features` returns this list as is.
219
+ Training and deployment read `all_features`, so they use only these names.
220
+ A derived feature that selection dropped stays dropped.
221
+ `ltr:optimize` writes it to the config file, and adds the key at the end of the file when it is missing.
222
+ It is the same list that `ltr:optimize` saves to SSM as `all_features`.
223
+ An empty list counts as missing.
224
+ When `ssm.enabled` is off, the loader logs a warning when this list differs from `search_time_features` plus `feature_store.features`.
225
+ Re-run `ltr:optimize` after you edit those lists.
226
+
227
+ ## feature_engineering
228
+
229
+ A list of methods.
230
+ Missing or `[]` adds no columns.
231
+ An unknown name raises `ArgumentError` at load.
232
+
233
+ | Value | What it adds |
234
+ |---|---|
235
+ | `rank` | `<feature>_rank` inside each query. |
236
+ | `relative_score` | `<feature>_relative_score` inside each query. |
237
+
238
+ The methods run on `relevancy` and on names that start with `bm25_`.
239
+ `bm25_fields_matched` is skipped.
240
+ See [Features](features.md).
241
+
242
+ The shipped file sets both methods.
243
+
244
+ ## feature_store
245
+
246
+ Per-document columns computed before query time.
247
+ See [Features](features.md).
248
+
249
+ | Key | Type | Missing | What it does |
250
+ |---|---|---|---|
251
+ | `feature_store.features` | list of strings | `[]` | Columns written into the feature store. `[]` is what the getter returns when the key is missing. Deploy only reads the key when `include_in_deployment` is `true`. Then a missing key, `null`, `{}` or `""` raises. An empty list `[]` builds no feature store. With `ssm.enabled`, deploy still needs the YAML key, but builds the store from the SSM list. An empty SSM list builds none. |
252
+ | `feature_store.include_in_deployment` | boolean | treated as `false` | Only `true` makes `SagemakerDeployer` bundle the feature store with the model, and `LocalDeployer` save it in the model file. |
253
+
254
+ The shipped file sets `purchase_count`, `add_to_cart_count`, and `view_count`, with `include_in_deployment: true`.
255
+
256
+ ## feature_transformations
257
+
258
+ Not in the shipped file.
259
+ Missing means the columns are left as stored.
260
+
261
+ The value is a hash.
262
+ Each key is a transform name.
263
+ Each value is a list of feature names.
264
+
265
+ | Key | What it does |
266
+ |---|---|
267
+ | `log1p` | `log(value + 1)` for each listed feature. A negative or non-numeric value is left as it is. |
268
+ | `sqrt` | Square root. A negative or non-numeric value is left as it is. |
269
+ | `z_score` | `(value - mean) / stddev` over the dataset. `NaN` values are left out of the mean and stddev and stay `NaN`. A column whose stddev is 0 makes each present value `0.0`. A `NaN` stays `NaN`. A column with no value other than `NaN` gets no step. |
270
+
271
+ The transforms run in key order, and a feature can be under more than one. A `z_score` mean and standard deviation are taken after the transforms before it.
272
+ `ltr:aggregate` saves what it applied. Deploy ships it, and inference repeats it on the request values. See [Features](features.md#feature-transforms).
273
+
274
+ Any other key raises `ArgumentError` when the dataset is finalized.
275
+ A name that is not in the model's feature list is skipped with a warning.
276
+
277
+ ## evaluation
278
+
279
+ The validator requires `evaluation.metrics` to be a non-empty list when the section is present.
280
+ Metric names are `ndcg`, `map`, `mrr`, `precision`, or `recall`, plus an optional `@k`.
281
+ See [Metrics](metrics.md).
282
+
283
+ | Key | Type | Missing | What it does |
284
+ |---|---|---|---|
285
+ | `evaluation.metrics` | list of strings | The evaluator raises if the key is missing. | Metrics computed after training. The shipped file sets `map@10`, `mrr@10`, `ndcg`, `ndcg@5`, `ndcg@12`, `precision`, `precision@5`, and `recall@5`. |
286
+ | `evaluation.split` | string | `test` | Which split is scored. Must be `train`, `val`, or `test` when set. A missing split falls back to `test` the same way `training.early_stopping_split` does. |
287
+ | `evaluation.min_relevance_grade` | number | The percentile is used. If both this key and the percentile are missing, the evaluator raises `ArgumentError`. | A document counts as relevant for MAP, MRR, precision, and recall when its label is at least this number. When both this key and the percentile are set, this key wins. NDCG does not use it. |
288
+ | `evaluation.min_relevance_percentile` | number | The evaluator raises if the grade is also missing. | Turned into a label threshold on the scored split. When set, it must be greater than 0 and less than 100. The shipped file sets `60`. |
289
+
290
+ `model.hyperparameters.eval_metric`, for example `ndcg@12`, is XGBoost's own metric for early stopping. XGBoost computes it. It does not use the code in `evaluation`, so its value can differ slightly from the gem's NDCG.
291
+
292
+ ## optimization
293
+
294
+ Feature selection and the hyperparameter search. [Optimization](optimization.md) explains how they run.
295
+ When the section is present, the validator checks `optimization.split`, `optimization.feature_selection.strategy`, and `optimization.n_init`.
296
+ It also checks `optimization.metric_to_optimize`, `optimization.hyperparameter_search_space`, `optimization.iterations`, and the `optimization.bayesian_optimizer` options, so a bad value raises `Ltr::ConfigurationError` at load and not hours into a run.
297
+
298
+ | Key | Type | Missing | What it does |
299
+ |---|---|---|---|
300
+ | `optimization.split` | string | `val` | Split the search scores. Must be `train`, `val`, or `test` when set. Same fallback as `evaluation.split`. |
301
+ | `optimization.metric_to_optimize` | string | The hyperparameter search raises. | Metric to maximize. One of `ndcg`, `map`, `mrr`, `precision`, `recall`, with an optional `@` and a cutoff of at least 1. It does not have to be listed in `evaluation.metrics`. The shipped file sets `ndcg@12`. |
302
+ | `optimization.complexity_penalty` | number | `0` | Subtracted as features are added, so a smaller set can win. The shipped file sets `0.0001`. |
303
+ | `optimization.min_features` | integer | `1` | The search stops shrinking at this many features. The shipped file sets `4`. |
304
+ | `optimization.feature_selection.strategy` | string | `greedy_backward` | One of `greedy_backward`, `importance_ranked`, `rfe`. Anything else raises `Ltr::ConfigurationError`. With `validate: true` it raises at load. With `validate: false` it raises in `OptimizeFeatures#select_features`, before any training. |
305
+ | `optimization.search_time_features` | list of strings | `[]` | Candidate search-time features. This list is separate from the top-level `search_time_features`. |
306
+ | `optimization.feature_store_features` | list of strings | `[]` | Candidate feature-store features. Separate from `feature_store.features`. |
307
+ | `optimization.iterations` | integer | `50` | Steps in the hyperparameter search. An integer of at least 0. |
308
+ | `optimization.n_init` | integer | `5` | Random points before the search starts using the model. An integer of at least 1. |
309
+
310
+ `optimization.hyperparameter_search_space` is a hash.
311
+ Each key is a hyperparameter name.
312
+ Each value is a hash with a numeric `min` and `max`, and `min` must be at most `max`.
313
+ The search samples those ranges and merges the sample onto `model.hyperparameters`.
314
+ The key is required when the hyperparameter search runs.
315
+ An empty hash raises.
316
+
317
+ The shipped file searches `colsample_bytree`, `learning_rate`, `max_depth`, `min_child_weight`, and `subsample`.
318
+
319
+ ### optimization.bayesian_optimizer
320
+
321
+ A hash of extra optimizer settings.
322
+ Missing means the defaults in `lib/ltr/optimize/bayesian_optimizer.rb`.
323
+
324
+ `iterations` and `n_init` come only from `optimization.iterations` and `optimization.n_init`. `seed` comes from the top-level `seed`.
325
+ Any key that is not in the table logs an unknown-key warning and is ignored.
326
+
327
+ | Key | Missing | What it does |
328
+ |---|---|---|
329
+ | `candidates_per_iteration` | `1000` | Points scored each step while picking the next sample. An integer of at least 1. The shipped file sets `1000`. |
330
+ | `noise_variance` | `0.1` | Noise assumed on each observed score, after the scores are standardized to mean 0 and std 1. The shipped file sets `0.1`. |
331
+ | `kernel_lengthscale` | `0.3` | RBF length scale. The default refit replaces it at the first guided step. It is used as-is when `optimize_hyperparameters_every` is `0`. A number above 0. The shipped file sets `0.3`. |
332
+ | `kernel_variance` | `1.0` | RBF variance. The default refit replaces it at the first guided step. It is used as-is when `optimize_hyperparameters_every` is `0`. A number above 0. The shipped file sets `1.0`. |
333
+ | `ei_xi` | `0.5` | Exploration term, in units of the score std. It falls in a straight line to `ei_xi / iterations` on the last step. The shipped file sets `0.5`. |
334
+ | `early_stopping_patience` | `10` | Stop after this many steps in a row with expected improvement under the threshold. An integer of at least 1. The run also stops when every candidate sampled for a step was already evaluated. |
335
+ | `early_stopping_threshold` | `0.0001` | A step counts as flat when expected improvement is below this fraction of the score range seen so far. A number of at least 0. |
336
+ | `local_refinement_fraction` | `0.2` | Share of `candidates_per_iteration` spent near the random candidates with the highest expected improvement in the same batch. At least 0 and below 1. |
337
+ | `local_refinement_top_k` | `5` | How many of those random candidates get that local search. An integer of at least 1. |
338
+ | `local_refinement_radius_start` | `0.2` | Starting size of the local nudge, in unit space. A number of at least 0. |
339
+ | `local_refinement_radius_end` | `0.02` | Ending size of the local nudge. A number of at least 0. |
340
+ | `optimize_hyperparameters_every` | `10` | Re-fit the kernel every this many steps. An integer of at least 0. `0` turns that off. |
341
+
342
+ ## ubi_data_loader
343
+
344
+ OpenSearch source for query and event documents.
345
+ See [UBI documents](ubi-documents.md).
346
+
347
+ | Key | Type | Missing | What it does |
348
+ |---|---|---|---|
349
+ | `ubi_data_loader.n_events` | integer | The loader raises. | How many events to pull. Only events of cascade actions count. Must be a positive number. The shipped file sets `10000`. See [UBI documents](ubi-documents.md#which-documents-the-pipeline-reads). |
350
+ | `ubi_data_loader.max_days_ago` | integer | The loader raises. | Number of whole UTC days the window reaches back from the current UTC date. The window runs from `00:00:00Z` on the first day to `23:59:59Z` on the current UTC date. The host time zone does not change either bound. The shipped file sets `30`. |
351
+ | `ubi_data_loader.batch_size` | integer | `100` on the ruby engine. `10000` on the sqlite engine. | Page size for the OpenSearch scroll. The shipped file sets `10000`. |
352
+ | `ubi_data_loader.opensearch.url` | string | The loader raises `ArgumentError`. | OpenSearch URL. The shipped file reads `ENV["OPENSEARCH_URL"]`. |
353
+ | `ubi_data_loader.opensearch.username` | string | passed as `nil` | Passed to `Ltr.config.opensearch_connect_options`. The shipped file reads `ENV["OPENSEARCH_USERNAME"]`. |
354
+ | `ubi_data_loader.opensearch.password` | string | passed as `nil` | Same, from `ENV["OPENSEARCH_PASSWORD"]`. |
355
+ | `ubi_data_loader.index.queries` | string | the search fails | Query index name. The shipped file sets `ubi_queries`. |
356
+ | `ubi_data_loader.index.events` | string | the search fails | Event index name. The shipped file sets `ubi_events`. |
357
+ | `ubi_data_loader.custom_filters` | string | no extra filters | Path to a YAML file. `YAML.load_file` reads it. The file has two keys, `queries` and `events`. Each value is a list of OpenSearch filter clauses. Those clauses are added to the bool filter. A value that is not a list raises `ArgumentError`. |
358
+
359
+ ## dataset_builder
360
+
361
+ | Key | Type | Missing | What it does |
362
+ |---|---|---|---|
363
+ | `dataset_builder.aggregation_engine` | string | `ruby` | `ruby` or `sqlite`. Anything else fails at load. |
364
+ | `dataset_builder.split_ratios` | hash | `train: 0.7`, `val: 0.15`, `test: 0.15` | Shares of queries assigned to each split. The keys must be exactly `train`, `val`, and `test`. Each value is from 0 to 1. They must sum to 1. `train` must be greater than 0. |
365
+ | `dataset_builder.query_id_field` | string | `query_id` | Field that joins a query document to its events. |
366
+ | `dataset_builder.doc_id_field` | string | `doc_id` | Field on the event that names the document. |
367
+ | `dataset_builder.hit_ids_field` | string | `query_response_hit_ids` | Query field whose order is the order the page showed. Position is the index in that list plus 1. A scored document missing from the list is not a row. A query without the field is skipped with a warning. The run raises only when no query has it. |
368
+ | `dataset_builder.additional_qid_fields` | list of strings | `[]` | Extra fields appended to the query grouping key, after `user_query`. Both engines add them to the query `_source`. The values are compared as text, so `1` and `"1"` are one value. Each name must match `[a-z_][a-z0-9_]*`, must not be reserved (such as `qid`, `rn` or `positives`), must not be listed twice, and must not equal an `<action>_count` column. A bad name raises `Ltr::ConfigurationError` before the download. See [aggregation-engines.md](aggregation-engines.md). |
369
+ | `dataset_builder.should_shuffle_data` | boolean | shuffle stays on | Only `false` keeps query order. Any other value shuffles before the split. The shuffle uses the top-level `seed`. |
370
+ | `dataset_builder.min_documents_per_query` | integer | `3` | Queries with fewer documents are dropped. When set, it must be a positive integer. |
371
+ | `dataset_builder.label_quantiles` | integer | `10` | Bucket count for `QuantileLabelTransformer` only. Other transformers ignore it. When set, it must be an integer of at least 3. With `validate: true` it raises `Ltr::ConfigurationError` at load. With `validate: false` it raises when `QuantileLabelTransformer` runs. |
372
+ | `dataset_builder.cascade_cutoff` | boolean | cutoff stays on | Only `false` turns it off. When set, it must be `true` or `false`. On, rows below the deepest action in the session are dropped. Off, those rows stay, and a document never examined in any session is a label of 0. |
373
+ | `dataset_builder.negative_downsample_ratio` | number | keep every negative | Only read when `cascade_cutoff` is `false`. Must be a positive number. Each query keeps at most `ceil(ratio × positives)` negatives, the ones with the lowest hash rank from the top-level `seed`. Setting it while the cutoff is on fails at load. |
374
+ | `dataset_builder.debug_mode` | boolean | off | Only `true` turns it on. When set, it must be `true` or `false`. On, `BehaviouralFeatureBuilder` does not run. Each `*_count` column stays at the per-query grain, `impression_count` is kept, and `conversion_features` are absent. Do not train on that file. Training warns about each missing feature, drops it, and trains on the rest. It raises `ArgumentError` only when no feature is left. |
375
+
376
+ ### dataset_builder.conversion_rate_targets
377
+
378
+ How `raw_label` is built.
379
+ Each entry is one rate.
380
+ The label is the weighted sum of those rates.
381
+ See [Labels from behavior](labels-from-behavior.md).
382
+
383
+ Aggregation needs the key. A missing or empty list raises `Ltr::ConfigurationError` when `ltr:aggregate` starts, before any OpenSearch call.
384
+ A config used only to log events, train or deploy does not need it.
385
+ When the key is present it must be a non-empty list of hashes.
386
+
387
+ | Key | Required | What it does |
388
+ |---|---|---|
389
+ | `name` | yes | Name used in errors and logs. |
390
+ | `numerator` | yes | Count column for the top of the rate. |
391
+ | `denominator` | no | Count column for the bottom of the rate. Missing means `impression_count`. Must be a string when set. |
392
+ | `weight` | yes | Multiplies the rate. A number, 0 or greater. |
393
+ | `nu` | yes | Smoothing strength. A number greater than 0. |
394
+ | `allow_invariant_violation` | no | `true` or `false`. A numerator above its denominator raises unless this is `true`. Then the row is logged and kept. |
395
+
396
+ The shipped file sets `ctr` (weight 1, nu 50), `atcr` (weight 2, nu 100), and `cvr` (weight 3, nu 150).
397
+ None of them set `denominator` or `allow_invariant_violation`.
398
+
399
+ ### dataset_builder.conversion_features
400
+
401
+ Ratios written as feature-store columns.
402
+ Missing means none.
403
+
404
+ Each entry is a hash with `name`, `numerator`, and `denominator`.
405
+ The value is `numerator / denominator` after counts are summed across the train-split queries for that document. A document with no train rows gets no ratio value in the dataset. The feature store uses the ratio from the val and test totals when the denominator is above 0.
406
+ Each `numerator` and `denominator` must be `impression` or a cascade action. Any other action raises `Ltr::ConfigurationError` when `ltr:aggregate` starts, before any OpenSearch call, because the loader does not build a count column for it. A config used only to train or deploy is not checked.
407
+ A missing column logs a warning and skips that feature.
408
+ A `name` of `split`, `label`, or the configured `query_id_field` or `doc_id_field` raises `Ltr::ConfigurationError`.
409
+ These columns are not written when `debug_mode` is `true`.
410
+
411
+ The shipped file sets `cart_conversion` (`add_to_cart_count / view_count`) and `purchase_conversion` (`purchase_count / view_count`).
412
+
413
+ ## dataset_aggregation
414
+
415
+ Used by the sqlite engine.
416
+ The ruby engine does not read it.
417
+
418
+ | Key | Type | Missing | What it does |
419
+ |---|---|---|---|
420
+ | `dataset_aggregation.staging_root` | string | the system temp directory | Directory for the scratch SQLite file. A relative path is joined to `Ltr.config.root`. An absolute path is used as given. A blank value, which is what the shipped file has, uses the temp directory. |
421
+ | `dataset_aggregation.sqlite.cache_size_mb` | integer | `256` | SQLite cache size in megabytes. When set, it must be a positive integer. |
422
+ | `dataset_aggregation.sqlite.page_size` | integer | `8192` | SQLite page size. When set, it must be a positive integer, a power of two, from 512 to 65536. |
423
+
424
+ The section itself must be a hash when present.
425
+
426
+ ## dataset_enricher
427
+
428
+ | Key | Type | Missing | What it does |
429
+ |---|---|---|---|
430
+ | `dataset_enricher.class` | string | no enricher runs | Class name resolved with `constantize` when the dataset pipeline runs. A name that does not resolve raises `Ltr::ConfigurationError` before any download. The class implements `Ltr::DatasetAggregation::DatasetEnricher#fetch_features` and returns its frame keyed by `dataset_builder.doc_id_field`. The shipped file leaves it commented out. |
431
+
432
+ ## label_transformer
433
+
434
+ Turns `raw_label` into `label` before training.
435
+ A blank `class` uses `Ltr::DatasetAggregation::IdentityLabelTransformer`.
436
+ The shipped file sets `Ltr::DatasetAggregation::SqrtLabelTransformer`.
437
+
438
+ A class that does not resolve raises `Ltr::ConfigurationError` when `ltr:aggregate` starts, before any download. It is not checked at config load.
439
+ Settings on the two per-query classes are checked at load.
440
+
441
+ | `class` | What it writes |
442
+ |---|---|
443
+ | `Ltr::DatasetAggregation::SqrtLabelTransformer` | `sqrt(raw_label)`. A negative value is left as it is. Shipped default. |
444
+ | `Ltr::DatasetAggregation::IdentityLabelTransformer` | `raw_label` unchanged. Also the fallback when `class` is blank. |
445
+ | `Ltr::DatasetAggregation::LogPlusOneLabelTransformer` | `log(1 + raw_label)`. A negative value is left as it is. |
446
+ | `Ltr::DatasetAggregation::QuantileLabelTransformer` | Quantile buckets. The bucket count is `dataset_builder.label_quantiles`. |
447
+ | `Ltr::DatasetAggregation::PerQueryKMeansLabelTransformer` | Bins each query on its own. |
448
+ | `Ltr::DatasetAggregation::PerQueryMinMaxLabelTransformer` | Rescales each query on its own. |
449
+ | Your class | Extend `Ltr::DatasetAggregation::LabelTransformer`. Read `:raw_label`. Write `:label`. |
450
+
451
+ Per-query settings.
452
+ Other classes ignore them.
453
+ A bad value fails at load.
454
+
455
+ | Key | Class | Missing | Rule |
456
+ |---|---|---|---|
457
+ | `label_transformer.groups` | k-means | `5` | Integer of at least 2. Labels run from `offset` to at most `offset + groups - 1`. |
458
+ | `label_transformer.offset` | k-means | `0` | Integer of 0 or more. Added to every label. |
459
+ | `label_transformer.range` | min-max | `[0, 1]` | `[low, high]` with `0 <= low < high`. |
460
+
461
+ [Label transformers](label-transformers.md) explains what each class writes, how the per-query settings change NDCG, and how to write your own class.
462
+
463
+ ## deploy
464
+
465
+ `deploy.local` and `deploy.enabled` are separate switches.
466
+
467
+ Both deploys compare the `deploy.metric` score to `deploy.minimum_metric_value`. A deploy runs when the score is at or above the minimum.
468
+
469
+ `deploy.local: true` writes the booster to `deploy.local_path` after training, whatever `deploy.enabled` is.
470
+ Below the minimum, it writes no file and `result[:local_deployment]` has `reason: :below_threshold`.
471
+ A relative path is joined to `Ltr.config.root`.
472
+ If `deploy.local_path` is a symlink, the saved file replaces the symlink. Its target is not changed.
473
+ `deploy.local_path` is required when `deploy.local` is `true`.
474
+
475
+ `deploy.enabled: true` calls `Ltr::Deploy::SagemakerDeployer`.
476
+ Training requires `deploy.enabled` to be exactly `true` or `false`.
477
+ A missing `deploy` section fails at train time with `deploy.enabled must be true or false`.
478
+
479
+ | Key | Type | Missing | What it does |
480
+ |---|---|---|---|
481
+ | `deploy.enabled` | boolean | Train fails. | Gates the SageMaker deploy. The shipped file sets `false`. |
482
+ | `deploy.local` | boolean | local save is skipped | Gates the local file save. The save also needs the score to meet `deploy.minimum_metric_value`. The shipped file sets `false`. |
483
+ | `deploy.local_path` | string | required when `deploy.local` is `true` | File the booster is written to. The shipped file sets `tmp/ltr/models/ltr_model.ubj`. |
484
+ | `deploy.sagemaker_bucket` | string | SageMaker deploy and feature-store deploy raise. | S3 bucket. The shipped file reads `SAGEMAKER_BUCKET` and has no default. It must be set, for example to `my-ltr-bucket`. |
485
+ | `deploy.execution_role` | string | required when `deploy.enabled` is `true` | IAM role for the endpoint. The shipped `example_config.yml` fills it from `SAGEMAKER_EXECUTION_ROLE` through ERB. A host config without that line gets no fallback. |
486
+ | `deploy.instance_type` | string | `ml.m5.large` | SageMaker instance type. |
487
+ | `deploy.instance_count` | integer | `1` | SageMaker instance count. |
488
+ | `deploy.image_uri` | string | The AWS `sagemaker-xgboost:3.0-5` image for `training.s3_region`, from the account in `Ltr::Deploy::SagemakerEndpoint::IMAGE_REGISTRY_ACCOUNTS`. A region not in that list raises `Unsupported region` without this key. An empty string counts as unset. | Inference image the endpoint runs. It must be an ECR image on the host `<account>.dkr.ecr.<region>.amazonaws.com` for the endpoint's region. Any other value raises before the upload. Use a `sagemaker-xgboost` image from the [AWS XGBoost container page](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html). The registry account differs by region. `code/inference.py` needs the XGBoost container. It does not run on a PyTorch image. |
489
+ | `deploy.metric` | string | required when `deploy.enabled` or `deploy.local` is `true` | Metric that gates both deploys. It must be one of `evaluation.metrics` when that list is non-empty. It must also be a key the evaluator returned. The shipped file sets `ndcg`. |
490
+ | `deploy.minimum_metric_value` | number | required when `deploy.enabled` or `deploy.local` is `true` | Each deploy runs when the metric is greater than or equal to this number. The shipped file sets `0.5`. |
491
+
492
+ ## inference
493
+
494
+ | Key | Type | Missing | What it does |
495
+ |---|---|---|---|
496
+ | `inference.sagemaker.open_timeout` | number | `0.5` | HTTP open timeout, in seconds, for `Ltr::Inference::SagemakerClient`. |
497
+ | `inference.sagemaker.read_timeout` | number | `0.5` | HTTP read timeout, in seconds, for the same client. |
498
+
499
+ The shipped file sets both to `0.5`.
500
+ Other keys under `inference` are not read.
501
+
502
+ ## ssm
503
+
504
+ When `ssm.enabled` is `true`, training reads the feature list and the hyperparameters from SSM Parameter Store.
505
+ It does not use the lists in the YAML.
506
+ Optimize writes those parameters when it is enabled.
507
+ `ltr:optimize` also reads them. It replaces `model.hyperparameters` with the SSM values before it searches, and falls back to the YAML values only when the parameter does not exist yet.
508
+
509
+ The validator requires the three paths when `enabled` is `true`.
510
+
511
+ | Key | Type | Missing | What it does |
512
+ |---|---|---|---|
513
+ | `ssm.enabled` | boolean | treated as `false` | Turns SSM reads and writes on. Only the boolean `true` turns them on. The string `"true"` does not. The shipped file sets `false`. |
514
+ | `ssm.all_features_param_path` | string | required when enabled | Parameter that stores the full feature list. The shipped file sets `/ltr/optimization/all_features`. |
515
+ | `ssm.feature_store_features_param_path` | string | required when enabled | Parameter that stores the feature-store feature list. The shipped file sets `/ltr/optimization/feature_store_features`. |
516
+ | `ssm.hyperparameters_param_path` | string | required when enabled | Parameter that stores the hyperparameter hash. The shipped file sets `/ltr/optimization/hyperparameters`. |
@@ -0,0 +1,94 @@
1
+ # Data contracts
2
+
3
+ This page lists what each stage of the gem hands to the next stage: who writes each file or document, who reads it, and which config key says where it lives. It follows the doc id and the feature names that must match from the User Behavior Insights (UBI) documents to an inference request. The [UBI documents](ubi-documents.md) page gives the shape and the rules of the UBI query and event documents. The [dataset CSV](dataset-csv.md), the [model files](model-files.md) and the [inference payload](inference.md) each have their own page.
4
+
5
+ ## Glossary
6
+
7
+ | Term | Meaning |
8
+ |---|---|
9
+ | Feature store | A table of feature-store values that deploy ships with the model when `feature_store.include_in_deployment` is `true`. Inference looks up a value in it by feature name and doc id, only when the request fields have no value for that feature. |
10
+ | 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. |
11
+ | Host app | The app that runs the search in OpenSearch, logs it to UBI and calls the gem to rerank the results. |
12
+ | Modelling CSV | The gzipped CSV that `ltr:aggregate` writes to `training.modelling_dataset_path` with `.gz` added. It has one row for each document in each query group, and a column for each feature. |
13
+ | 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. |
14
+ | Search-time feature | A score the search engine computes for each query and document, such as `bm25_name`. The host logs it in `query_attributes.scores` for training and sends it in the request fields at query time. `search_time_features` lists them. |
15
+ | Serving file | The `<modelling_dataset_path without .csv>.serving.json` file that `ltr:aggregate` writes next to the modelling CSV. It holds the feature transform steps and the one-hot column names. Deploy copies both into the model file. |
16
+ | 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. |
17
+ | 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`. |
18
+
19
+ The full list is in the [glossary](glossary.md).
20
+
21
+ ## What passes between the stages
22
+
23
+ The table shows each file or document that one stage writes and a later stage reads.
24
+
25
+ | Contract | Written by | Read by | Where | Detail |
26
+ |---|---|---|---|---|
27
+ | User Behavior Insights query documents | Host app (`Ltr::Ubi.query`) | Dataset pipeline | Index `ubi_data_loader.index.queries` (shipped `ubi_queries`) | [UBI query documents](ubi-documents.md#query-documents) |
28
+ | User Behavior Insights event documents | Host app (`Ltr::Ubi.event`) | Dataset pipeline | Index `ubi_data_loader.index.events` (shipped `ubi_events`) | [UBI event documents](ubi-documents.md#event-documents) |
29
+ | Modelling dataset CSV | Dataset pipeline | Optimize and modelling pipelines, feature store build | `training.modelling_dataset_path` with `.gz` added, local or S3 | [Modelling dataset CSV](dataset-csv.md) |
30
+ | Dataset serving file | Dataset pipeline | Local and [SageMaker](https://docs.aws.amazon.com/sagemaker/) deploys | `training.modelling_dataset_path` with `.csv` replaced by `.serving.json`, local or S3 | [Dataset serving file](model-files.md#dataset-serving-file) |
31
+ | Features and hyperparameters | Optimize pipeline | Modelling pipeline and deployment | The config file, and SSM when `ssm.enabled` is `true` | [Optimization](optimization.md) |
32
+ | Model file | Modelling pipeline | Local reranker or SageMaker endpoint | `deploy.local_path`, or `model.tar.gz` in `deploy.sagemaker_bucket` | [Model and feature store files](model-files.md) |
33
+ | `features.json` | Modelling pipeline, on every SageMaker deploy | SageMaker endpoint | `code/` inside `model.tar.gz` | [Model and feature store files](model-files.md) |
34
+ | Feature store | Modelling pipeline, on a deploy with `feature_store.include_in_deployment: true` | Local reranker or SageMaker endpoint | The `feature_store` attribute of the local model file, or `code/feature_store.json` inside `model.tar.gz` | [Model and feature store files](model-files.md) |
35
+ | Inference request | Host app | Local reranker or SageMaker endpoint | The `payload` of `Ltr::Inference::Base.call` | [Inference](inference.md) |
36
+
37
+ ## Names that must match
38
+
39
+ The host app writes each doc id and score name into the UBI documents at search time. The diagram below is an example that follows one doc, `prodA`, to a request on the SageMaker endpoint. The values are made up, and `view_count` in the CSV is the doc's total over the train-split searches.
40
+
41
+ ```mermaid
42
+ ---
43
+ config:
44
+ flowchart:
45
+ wrappingWidth: 480
46
+ ---
47
+ flowchart LR
48
+ subgraph LOG["Logged at search time"]
49
+ direction TB
50
+ Q("<b>UBI query document</b><br>scores of prodA:<br>bm25_name 0.9")
51
+ E("<b>UBI event document</b><br>event_attributes.doc_id: prodA<br>action_name: view")
52
+ end
53
+ subgraph TRAIN["Built by the dataset pipeline"]
54
+ direction TB
55
+ R("<b>Dataset CSV row</b><br>doc_id: prodA<br>bm25_name: 0.9<br>view_count: 340")
56
+ end
57
+ subgraph DEPLOY["Built by deploy"]
58
+ direction TB
59
+ FS("<b>Feature store JSON</b><br>view_count of prodA: 340.0")
60
+ end
61
+ subgraph SEND["Sent at query time"]
62
+ direction TB
63
+ H("<b>Host app request</b><br>id: prodA<br>bm25_name: 0.9")
64
+ end
65
+ EP("<b>SageMaker endpoint</b><br>bm25_name from the request<br>view_count from the feature store")
66
+
67
+ LOG --> R
68
+ R --> FS
69
+ H --> EP
70
+ FS --> EP
71
+
72
+ classDef logged fill:#e8f0fe,stroke:#3b5bdb,stroke-width:1.5px,color:#1b2a5c
73
+ classDef built fill:#e6f4ea,stroke:#2b8a3e,stroke-width:1.5px,color:#14391f
74
+ classDef sent fill:#fdf2e3,stroke:#d9730d,stroke-width:1.5px,color:#4a2a07
75
+ classDef endpoint fill:#eceff1,stroke:#455a64,stroke-width:2px,color:#1c262b
76
+ class Q,E logged
77
+ class R,FS built
78
+ class H sent
79
+ class EP endpoint
80
+ style LOG fill:#f5f8ff,stroke:#3b5bdb,stroke-width:1px,color:#1b2a5c
81
+ style TRAIN fill:#f4faf6,stroke:#2b8a3e,stroke-width:1px,color:#14391f
82
+ style DEPLOY fill:#f4faf6,stroke:#2b8a3e,stroke-width:1px,color:#14391f
83
+ style SEND fill:#fffaf2,stroke:#d9730d,stroke-width:1px,color:#4a2a07
84
+ ```
85
+
86
+ The table shows where each name sits at each stage. `<doc_id_field>` is the value of `dataset_builder.doc_id_field`, which defaults to `doc_id`.
87
+
88
+ | Stage | Document id | Search-time feature, such as `bm25_name` | Behavior feature, such as `view_count` |
89
+ |---|---|---|---|
90
+ | User Behavior Insights query document | A key in `query_attributes.scores`, and an entry in the hit ids | A key in that doc's score object | None |
91
+ | User Behavior Insights event document | `event_attributes.<doc_id_field>` | None | `action_name: view` |
92
+ | Dataset CSV | The `<doc_id_field>` column | A column of the same name | The `view_count` column |
93
+ | Feature store file | The inner key | None | The outer key |
94
+ | Inference request | The item `id` | `fields[].name` | Can be left out when the model was deployed with the feature store. Otherwise send it in `fields`. |