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,584 @@
1
+ # Run the pipelines locally
2
+
3
+ This guide trains a ranking model on your laptop and uses it to rerank one search. It needs no AWS account.
4
+
5
+ You will run OpenSearch in Docker and load fake search and click data. Then you run the three pipelines. At the end you compare the old and new order of one search. Expect about 20 minutes. Most of it is `bundle install` and the Docker image download. The three pipelines take about 30 seconds on the fake data. On the test machine, with the Docker image and gems already downloaded, the whole guide ran in about 95 seconds.
6
+
7
+ Every block is meant to be pasted in order, in one terminal. Each step ends with a check and the output it should print. The output is trimmed.
8
+
9
+ When you are done, the [AWS guide](run-on-aws.md) runs the same steps against S3, SSM and a SageMaker endpoint.
10
+
11
+ ```mermaid
12
+ flowchart LR
13
+ A[OpenSearch in Docker] --> B[scripts/seed_ubi.rb]
14
+ B --> C[ltr:aggregate]
15
+ C --> D[tmp/ltr/data/ltr_dataset.csv.gz]
16
+ D --> E[ltr:optimize]
17
+ E --> F[config/ltr/local.yml]
18
+ F --> G[ltr:train]
19
+ G --> H[tmp/ltr/models/ltr_model.ubj]
20
+ H --> I[scripts/rerank.rb]
21
+ ```
22
+
23
+ To learn the ideas behind each step, read [Learning to rank](learning-to-rank.md), [Labels from behavior](labels-from-behavior.md), [Features](features.md) and [Metrics](metrics.md). This guide does not repeat them.
24
+
25
+ ## Before you start
26
+
27
+ You need Ruby 3.3 or newer, Bundler, and Docker with at least 4 GB of memory.
28
+
29
+ ```bash
30
+ ruby -v
31
+ bundle -v
32
+ docker info --format '{{.MemTotal}}'
33
+ ```
34
+
35
+ Expect (your versions can differ):
36
+
37
+ ```text
38
+ ruby 3.3.3 (2024-06-12 revision f1c7b6f435) [arm64-darwin23]
39
+ 4.0.23
40
+ 8321138688
41
+ ```
42
+
43
+ The last number is the memory Docker can use, in bytes. It must be at least `4294967296`. On macOS, raise it in Docker Desktop under Settings, Resources.
44
+
45
+ The `xgb` gem needs the OpenMP library. On macOS, install it:
46
+
47
+ ```bash
48
+ brew install libomp
49
+ ```
50
+
51
+ On Linux, OpenMP usually comes with the system. If Ruby later fails with a `libgomp` load error, install `libgomp1` (Debian and Ubuntu).
52
+
53
+ ## Make a project
54
+
55
+ ```bash
56
+ mkdir ltr-demo && cd ltr-demo
57
+ mkdir -p scripts config/ltr
58
+ cat > Gemfile <<'EOF'
59
+ source "https://rubygems.org"
60
+
61
+ gem "ltr"
62
+ gem "opensearch-ruby", ">= 4.0.0.pre.beta.5", "< 5.a"
63
+ gem "rake"
64
+ EOF
65
+ ```
66
+
67
+ GCC 15 and newer need a flag to build `numo-narray` 0.9.2.1.
68
+ Run `bundle config set --local build.numo-narray --with-cflags=-std=gnu17` before `bundle install`.
69
+ GCC 14 and macOS need no flag.
70
+
71
+ ```bash
72
+ bundle install
73
+ bundle exec ruby -e 'require "ltr"; puts Ltr::VERSION'
74
+ ```
75
+
76
+ Expect:
77
+
78
+ ```text
79
+ 0.1.0
80
+ ```
81
+
82
+ ## Start OpenSearch
83
+
84
+ ```bash
85
+ cat > docker-compose.yml <<'EOF'
86
+ services:
87
+ opensearch:
88
+ image: opensearchproject/opensearch:2.19.0
89
+ environment:
90
+ - discovery.type=single-node
91
+ - DISABLE_SECURITY_PLUGIN=true
92
+ - DISABLE_INSTALL_DEMO_CONFIG=true
93
+ - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m
94
+ ports:
95
+ - "9200:9200"
96
+ volumes:
97
+ - opensearch-data:/usr/share/opensearch/data
98
+
99
+ volumes:
100
+ opensearch-data:
101
+ EOF
102
+ ```
103
+
104
+ The security plugin is off. This node is for your laptop only.
105
+
106
+ ```bash
107
+ docker compose up -d
108
+ ```
109
+
110
+ ```bash
111
+ until curl -s localhost:9200 >/dev/null; do sleep 2; done
112
+ export OPENSEARCH_URL=http://localhost:9200
113
+ curl -s 'localhost:9200/_cluster/health?filter_path=status'
114
+ ```
115
+
116
+ The config reads `OPENSEARCH_URL`. The `export` stops a value left in your shell from pointing the tools at another cluster. In a new terminal, run it again.
117
+
118
+ Expect `green` or `yellow`. Both are fine for one node:
119
+
120
+ ```text
121
+ {"status":"yellow"}
122
+ ```
123
+
124
+ ## Create the UBI indices
125
+
126
+ The gem reads search and click data from two indices. Create them with explicit mappings.
127
+
128
+ ```bash
129
+ cat > config/ltr/ubi_queries.mapping.json <<'EOF'
130
+ {
131
+ "settings": { "number_of_replicas": 0 },
132
+ "mappings": {
133
+ "properties": {
134
+ "query_id": { "type": "keyword" },
135
+ "user_query": { "type": "keyword" },
136
+ "timestamp": { "type": "date" },
137
+ "query_attributes": { "type": "object", "enabled": false },
138
+ "query_response_hit_ids": { "type": "keyword" }
139
+ }
140
+ }
141
+ }
142
+ EOF
143
+ cat > config/ltr/ubi_events.mapping.json <<'EOF'
144
+ {
145
+ "settings": { "number_of_replicas": 0 },
146
+ "mappings": {
147
+ "properties": {
148
+ "query_id": { "type": "keyword" },
149
+ "action_name": { "type": "keyword" },
150
+ "event_attributes": { "properties": { "doc_id": { "type": "keyword" } } },
151
+ "timestamp": { "type": "date" }
152
+ }
153
+ }
154
+ }
155
+ EOF
156
+ curl -s -X PUT localhost:9200/ubi_queries -H 'Content-Type: application/json' -d @config/ltr/ubi_queries.mapping.json
157
+ echo
158
+ curl -s -X PUT localhost:9200/ubi_events -H 'Content-Type: application/json' -d @config/ltr/ubi_events.mapping.json
159
+ echo
160
+ ```
161
+
162
+ Four fields need a specific type. [Required field types](ubi-documents.md#required-field-types) says which and what breaks without them. The mappings above already set them.
163
+
164
+ Expect:
165
+
166
+ ```text
167
+ {"acknowledged":true,"shards_acknowledged":true,"index":"ubi_queries"}
168
+ {"acknowledged":true,"shards_acknowledged":true,"index":"ubi_events"}
169
+ ```
170
+
171
+ ## Load sample data
172
+
173
+ This script writes 3000 searches for 40 queries, with 30 products each. It uses the seed `1967`, so you get the same data as this guide.
174
+
175
+ Each product has a hidden quality from 0 to 1. The `bm25_name`, `bm25_description` and `relevancy` scores follow the quality, with noise. So the page order is good but not perfect.
176
+
177
+ Each search shows the products in `relevancy` order. A user looks down the page and reaches lower products less often. Better products get more `view`, `add_to_cart` and `purchase` events.
178
+
179
+ The seed script needs a loader for the field names. This file builds it as `UBI_CONFIG`. It points at the gem's `example_config.yml`, so it works before `config/ltr/base.yml` exists.
180
+
181
+ ```bash
182
+ cat > config/ltr_host.rb <<'EOF'
183
+ require "ltr"
184
+
185
+ UBI_CONFIG = Ltr::ConfigLoader.new(
186
+ base_config_path: File.join(Gem.loaded_specs["ltr"].full_gem_path, "lib/ltr/configuration/example_config.yml"),
187
+ validate: false,
188
+ )
189
+ EOF
190
+ ```
191
+
192
+ The script builds every document with `Ltr::Ubi.query` and `Ltr::Ubi.event`. It passes `UBI_CONFIG` as `config:` on each call. You can use the same two methods to log real searches. It also saves the hidden quality to `tmp/ltr/truth.json`, so the last step can score the new order.
193
+
194
+ Copy [`scripts/seed_ubi.rb`](../scripts/seed_ubi.rb) from the installed gem into `scripts/`. Then run it:
195
+
196
+ ```bash
197
+ cp "$(bundle exec ruby -e 'require "ltr"; print File.join(Gem.loaded_specs["ltr"].full_gem_path, "scripts/seed_ubi.rb")')" scripts/seed_ubi.rb
198
+ bundle exec ruby scripts/seed_ubi.rb
199
+ ```
200
+
201
+ Run the script once. A second run adds the same searches again. To start over, delete both indices and create them again.
202
+
203
+ Expect:
204
+
205
+ ```text
206
+ queries: 3000
207
+ events: 42614
208
+ ```
209
+
210
+ Check it from outside Ruby:
211
+
212
+ ```bash
213
+ curl -s 'localhost:9200/ubi_events/_count?filter_path=count'
214
+ ```
215
+
216
+ Expect:
217
+
218
+ ```text
219
+ {"count":42614}
220
+ ```
221
+
222
+ The timestamps fall in the last 7 days. The loader reads only the UTC days that run from `max_days_ago` days (30 by default) before the current UTC date through the current UTC date. The data also stays under `n_events`, which the next step raises.
223
+
224
+ ## Write the config
225
+
226
+ The rake tasks never use the gem's own `example_config.yml`. A single config path must be a complete config. So copy the gem's default config into your project as `base.yml`. Then write a small override file with your settings.
227
+
228
+ ```bash
229
+ cp "$(bundle exec ruby -e 'require "ltr"; print File.join(Gem.loaded_specs["ltr"].full_gem_path, "lib/ltr/configuration/example_config.yml")')" config/ltr/base.yml
230
+ cat > config/ltr/local.yml <<'EOF'
231
+ model:
232
+ name: ltr-demo
233
+ hyperparameters:
234
+ n_estimators: 100
235
+
236
+ search_time_features:
237
+ - relevancy
238
+ - bm25_name
239
+ - bm25_description
240
+
241
+ feature_store:
242
+ features:
243
+ - view_count
244
+ - add_to_cart_count
245
+ - purchase_count
246
+
247
+ ubi_data_loader:
248
+ n_events: 50000
249
+ opensearch:
250
+ url: <%= ENV.fetch("OPENSEARCH_URL", "http://localhost:9200") %>
251
+ username:
252
+ password:
253
+
254
+ optimization:
255
+ iterations: 10
256
+ search_time_features:
257
+ - relevancy
258
+ - bm25_name
259
+ - bm25_description
260
+ feature_store_features:
261
+ - view_count
262
+ - add_to_cart_count
263
+ - purchase_count
264
+ - cart_conversion
265
+ - purchase_conversion
266
+
267
+ deploy:
268
+ local: true
269
+ EOF
270
+ ```
271
+
272
+ The override lists only the keys that differ from `base.yml`, plus the three sections that `ltr:optimize` rewrites. `ltr:optimize` also adds an `optimized_features` list at the end of the file. It is merged over `base.yml`. Hashes merge key by key. Lists are replaced whole.
273
+
274
+ The override holds `model.hyperparameters`, `search_time_features` and `feature_store.features` on purpose. `ltr:optimize` rewrites those three sections in this file. It adds a section that is missing.
275
+
276
+ Every key is listed in the [Config reference](config.md). Other settings worth knowing:
277
+
278
+ - `iterations: 10` makes the optimizer finish in seconds. The default is 50.
279
+ - `n_events: 50000` is above the 42614 seeded events. The default is 10000, which would cut some of them.
280
+ - `deploy.local: true` saves the model to `tmp/ltr/models/ltr_model.ubj` when the `deploy.metric` score is at or above `deploy.minimum_metric_value`. See [Config](config.md#deploy).
281
+ - `dataset_builder.doc_id_field` stays `doc_id`, as in `base.yml`. `Ltr::Ubi.event` reads the loader that the seed script passes as `config:`. That loader must keep the same `doc_id_field` as the rake config. If you rename the field only in your override, the rake run reads a key the seeded events do not have, and `ltr:aggregate` stops with the `ArgumentError` listed under Troubleshooting.
282
+
283
+ ## Add the rake tasks
284
+
285
+ ```bash
286
+ cat > Rakefile <<'EOF'
287
+ require "bundler/setup"
288
+ require "ltr"
289
+ load "ltr/tasks/ltr.rake"
290
+ EOF
291
+ bundle exec rake -T ltr
292
+ ```
293
+
294
+ Expect:
295
+
296
+ ```text
297
+ rake ltr:aggregate[base_config,override_config] # Run the LTR dataset aggregation pipeline
298
+ rake ltr:optimize[base_config,override_config] # Run the LTR feature and hyperparameter optimization pipeline
299
+ rake ltr:train[base_config,override_config] # Run the LTR training pipeline and deploy when the gates pass
300
+ ```
301
+
302
+ ## Build the dataset
303
+
304
+ ```bash
305
+ bundle exec rake "ltr:aggregate[config/ltr/base.yml,config/ltr/local.yml]" 2>&1 | grep "ltr:aggregate" | sed 's/.*INFO -- : //'
306
+ ```
307
+
308
+ Expect:
309
+
310
+ ```text
311
+ ltr:aggregate base config: config/ltr/base.yml, override config: config/ltr/local.yml
312
+ ltr:aggregate wrote 1182 rows to tmp/ltr/data/ltr_dataset.csv
313
+ ```
314
+
315
+ The file on disk is `tmp/ltr/data/ltr_dataset.csv.gz`. Look at a few columns:
316
+
317
+ ```bash
318
+ gzip -dc tmp/ltr/data/ltr_dataset.csv.gz | sed -n '1,3p' | cut -d, -f1-3,6-8,14
319
+ ```
320
+
321
+ Expect:
322
+
323
+ ```text
324
+ qid,user_query,doc_id,purchase_count,add_to_cart_count,view_count,label
325
+ 9,gaba,p38-09,0.0,0.0,3.0,1.0235659679258786
326
+ 9,gaba,p38-08,4.0,11.0,26.0,1.0079293494519408
327
+ ```
328
+
329
+ The columns of the file are listed in [Data contracts](dataset-csv.md).
330
+
331
+ ## Pick features and hyperparameters
332
+
333
+ Save a copy of the override first. Then the change is easy to see.
334
+
335
+ ```bash
336
+ cp config/ltr/local.yml tmp/ltr/local.before.yml
337
+ bundle exec rake "ltr:optimize[config/ltr/base.yml,config/ltr/local.yml]" 2>&1 | grep "ltr:optimize" | sed 's/.*INFO -- : //'
338
+ ```
339
+
340
+ Expect:
341
+
342
+ ```text
343
+ ltr:optimize base config: config/ltr/base.yml, override config: config/ltr/local.yml
344
+ ltr:optimize search_time_features: ["bm25_name", "relevancy_rank", "bm25_name_rank", "bm25_description_rank", "bm25_name_relative_score", "bm25_description_relative_score"]
345
+ ltr:optimize feature_store_features: ["view_count", "add_to_cart_count", "purchase_count", "cart_conversion"]
346
+ ltr:optimize hyperparameters: {:eval_metric=>"ndcg@12", ..., :learning_rate=>0.1548363423787587, :max_depth=>8, ..., :min_child_weight=>8, :subsample=>0.7853837193293272, :colsample_bytree=>0.6416115033241546}
347
+ ```
348
+
349
+ This step took about 4 seconds on the test machine. The optimizer dropped the features that did not help. It also tuned five hyperparameters. It wrote the result back into `config/ltr/local.yml`:
350
+
351
+ ```bash
352
+ diff -U1 tmp/ltr/local.before.yml config/ltr/local.yml || true
353
+ ```
354
+
355
+ Expect:
356
+
357
+ ```text
358
+ --- tmp/ltr/local.before.yml
359
+ +++ config/ltr/local.yml
360
+ @@ -3,8 +3,23 @@
361
+ hyperparameters:
362
+ + eval_metric: ndcg@12
363
+ + lambdarank_unbiased: true
364
+ + ndcg_exp_gain: false
365
+ + objective: rank:ndcg
366
+ n_estimators: 100
367
+ + learning_rate: 0.1548363423787587
368
+ + max_depth: 8
369
+ + lambdarank_num_pair_per_sample: 12
370
+ + early_stopping_rounds: 20
371
+ + verbose_eval: 10
372
+ + min_child_weight: 8
373
+ + subsample: 0.7853837193293272
374
+ + colsample_bytree: 0.6416115033241546
375
+
376
+ search_time_features:
377
+ - - relevancy
378
+ - bm25_name
379
+ - - bm25_description
380
+ + - relevancy_rank
381
+ + - bm25_name_rank
382
+ + - bm25_description_rank
383
+ + - bm25_name_relative_score
384
+ + - bm25_description_relative_score
385
+
386
+ @@ -15,2 +30,3 @@
387
+ - purchase_count
388
+ + - cart_conversion
389
+
390
+ @@ -38 +54,13 @@
391
+ local: true
392
+ +
393
+ +optimized_features:
394
+ + - bm25_name
395
+ + - relevancy_rank
396
+ + - bm25_name_rank
397
+ + - bm25_description_rank
398
+ + - bm25_name_relative_score
399
+ + - bm25_description_relative_score
400
+ + - view_count
401
+ + - add_to_cart_count
402
+ + - purchase_count
403
+ + - cart_conversion
404
+ ```
405
+
406
+ The optimizer writes the full set of hyperparameters, not only the tuned ones. So `objective` and `eval_metric` stay in the file. It also appends `optimized_features`, the exact list that `ltr:train` trains on.
407
+
408
+ Your numbers can differ from the ones above if the data differs. With the seed `1967` they should match.
409
+
410
+ ## Train
411
+
412
+ ```bash
413
+ bundle exec rake "ltr:train[config/ltr/base.yml,config/ltr/local.yml]" 2>&1 | grep "ltr:train" | sed 's/.*INFO -- : //'
414
+ ```
415
+
416
+ Expect:
417
+
418
+ ```text
419
+ ltr:train base config: config/ltr/base.yml, override config: config/ltr/local.yml
420
+ ltr:train metrics: {"map@10"=>0.5348, "mrr@10"=>1.0, "ndcg"=>0.9829, "ndcg@5"=>0.9462, "ndcg@12"=>0.952, "precision"=>0.3955, "precision@5"=>0.8667, "recall@5"=>0.394}
421
+ ltr:train sagemaker deploy: deployed=false, reason=disabled
422
+ ltr:train local deploy: deployed=true, reason=local_saved, path=/.../ltr-demo/tmp/ltr/models/ltr_model.ubj
423
+ ```
424
+
425
+ The `ndcg@12` is near 1. That is too good to be true, and it is. The label and the stored features (such as `cart_conversion`) both come from the same click events. A real dataset scores lower. Treat the number as a sign that the pipeline ran, not as a measure of quality.
426
+
427
+ The model score that matters is the last step, where the new order is checked against the hidden quality.
428
+
429
+ ## Rerank a search
430
+
431
+ `scripts/rerank.rb` takes one query. It reads the latest search for that query from OpenSearch. It sends the products and their features to `Ltr::Inference::Base.call`. Then it prints the new order and scores both orders against the hidden quality.
432
+
433
+ ### What the script sends for a stored feature
434
+
435
+ The saved model holds a feature store, because `base.yml` sets `feature_store.include_in_deployment: true`. The script reads the stored features (here `view_count`, `add_to_cart_count`, `purchase_count` and `cart_conversion`) from the first dataset row of each product and sends them with the product. `Ltr::Data::Csv.read` reads an empty cell in that row as `Float::NAN`. `LocalReranker` reads a `NaN` the same as a left-out field, so it looks the feature up in the store. The table shows what the model gets for one stored feature of one product.
436
+
437
+ | Product | Script sends | Model gets |
438
+ |---|---|---|
439
+ | In the dataset, with a value in its first row | that value | that value |
440
+ | In the dataset, with `NaN` in its first row, and the store has a value | `NaN` | the store value |
441
+ | In the dataset, with `NaN` in its first row, and the store has no value | `NaN` | a missing value, as XGBoost saw for an empty cell in training |
442
+ | Absent from the dataset | `0` | `0`, because the reranker reads the store only when no number is sent |
443
+
444
+ This copy is right only because the walkthrough sets no `feature_transformations`. See the [request rules](inference.md#rules-for-fields).
445
+
446
+ ```bash
447
+ cat > scripts/rerank.rb <<'EOF'
448
+ require "bundler/setup"
449
+ require "ltr"
450
+ require "opensearch"
451
+
452
+ Ltr.config.logger = Logger.new(nil)
453
+ config = Ltr::ConfigLoader.new(base_config_path: "config/ltr/base.yml", override_config_path: "config/ltr/local.yml")
454
+ client = OpenSearch::Client.new(Ltr.config.opensearch_connect_options(
455
+ ENV.fetch("OPENSEARCH_URL", "http://localhost:9200"), ENV["OPENSEARCH_USERNAME"], ENV["OPENSEARCH_PASSWORD"]
456
+ ))
457
+ quality = JSON.parse(File.read("tmp/ltr/truth.json"))
458
+
459
+ doc_id_field = config.doc_id_field
460
+ stored = {}
461
+ Ltr::Data::Csv.read(config).to_a.each do |row|
462
+ stored[row[doc_id_field]] ||= row.slice(*config.feature_store_features)
463
+ end
464
+ no_history = config.feature_store_features.to_h { |name| [name, 0] }
465
+
466
+ def ndcg_at(k, ids, quality)
467
+ dcg = ->(list) { list.first(k).each_with_index.sum { |id, i| quality.fetch(id) / Math.log2(i + 2) } }
468
+ dcg.call(ids) / dcg.call(ids.sort_by { |id| -quality[id] })
469
+ end
470
+
471
+ def rerank(user_query, client, config, stored, no_history)
472
+ search = client.search(
473
+ index: "ubi_queries",
474
+ body: { size: 1, query: { term: { user_query: user_query } }, sort: [{ timestamp: :desc }] }
475
+ ).dig("hits", "hits", 0, "_source") or abort "no search found for #{user_query.inspect}"
476
+ hit_ids = search.fetch("query_response_hit_ids")
477
+ scores = search.dig("query_attributes", "scores")
478
+
479
+ items = hit_ids.map do |id|
480
+ features = scores.fetch(id).merge(stored.fetch(id, no_history))
481
+ { "id" => id, "fields" => features.map { |name, value| { "name" => name, "value" => value } } }
482
+ end
483
+ response = Ltr::Inference::Base.call(items, config)
484
+ [hit_ids, response.fetch("items").map { |item| item["item"] }]
485
+ end
486
+
487
+ if ARGV.first == "--all"
488
+ user_queries = client.search(index: "ubi_queries", body: { size: 0, aggs: { q: { terms: { field: "user_query", size: 100 } } } })
489
+ .dig("aggregations", "q", "buckets").map { |bucket| bucket["key"] }
490
+ results = user_queries.map do |user_query|
491
+ old_ids, new_ids = rerank(user_query, client, config, stored, no_history)
492
+ [ndcg_at(10, old_ids, quality), ndcg_at(10, new_ids, quality)]
493
+ end
494
+ puts format("queries: %d, improved: %d", results.size, results.count { |old, new| new > old })
495
+ puts format("mean NDCG@10 old order: %.3f", results.sum { |old, _| old } / results.size)
496
+ puts format("mean NDCG@10 new order: %.3f", results.sum { |_, new| new } / results.size)
497
+ else
498
+ user_query = ARGV.fetch(0) { abort 'usage: bundle exec ruby scripts/rerank.rb "magnesium" or --all' }
499
+ old_ids, new_ids = rerank(user_query, client, config, stored, no_history)
500
+ puts format("%-10s %9s %9s %8s", "product", "old rank", "new rank", "quality")
501
+ new_ids.first(10).each do |id|
502
+ puts format("%-10s %9d %9d %8.3f", id, old_ids.index(id) + 1, new_ids.index(id) + 1, quality.fetch(id))
503
+ end
504
+ puts format("NDCG@10 old order: %.3f", ndcg_at(10, old_ids, quality))
505
+ puts format("NDCG@10 new order: %.3f", ndcg_at(10, new_ids, quality))
506
+ end
507
+ EOF
508
+ bundle exec ruby scripts/rerank.rb magnesium
509
+ ```
510
+
511
+ Expect:
512
+
513
+ ```text
514
+ product old rank new rank quality
515
+ p01-15 3 1 0.864
516
+ p01-29 2 2 0.973
517
+ p01-23 1 3 0.944
518
+ p01-25 6 4 0.918
519
+ p01-11 4 5 0.739
520
+ p01-06 8 6 0.757
521
+ p01-16 5 7 0.523
522
+ p01-24 7 8 0.668
523
+ p01-00 13 9 0.814
524
+ p01-07 15 10 0.775
525
+ NDCG@10 old order: 0.944
526
+ NDCG@10 new order: 0.972
527
+ ```
528
+
529
+ The table lists the top 10 products of the new order. `old rank` is where the page showed the product. `quality` is the hidden quality. Good products move up. NDCG@10 is 1 when the order matches the hidden quality.
530
+
531
+ Run it over all 40 queries:
532
+
533
+ ```bash
534
+ bundle exec ruby scripts/rerank.rb --all
535
+ ```
536
+
537
+ Expect:
538
+
539
+ ```text
540
+ queries: 40, improved: 39
541
+ mean NDCG@10 old order: 0.878
542
+ mean NDCG@10 new order: 0.960
543
+ ```
544
+
545
+ One query gets worse. The model sees only a few stored features, and the click counts are noisy. The model also trained on most of these queries, so this score looks better than it would on new queries.
546
+
547
+ [Inference](inference.md) explains how to call the model from your own code, and [the request and response](inference.md#inference-request) are listed there.
548
+
549
+ ## Next steps
550
+
551
+ - Log real searches and clicks with `Ltr::Ubi.query` and `Ltr::Ubi.event`. The seed script shows the call.
552
+ - For a large pull from OpenSearch, set `dataset_builder.aggregation_engine: sqlite`. It keeps the events on disk, not in memory. Add `gem "sqlite3", "~> 2.0"` to your `Gemfile` first.
553
+ - Try another label with `label_transformer.class`. [Labels from behavior](labels-from-behavior.md) explains the options.
554
+ - Set `dataset_builder.cascade_cutoff: false` to keep products that users never reached. They become label 0 examples.
555
+ - Run the same pipelines on AWS with the [AWS guide](run-on-aws.md).
556
+
557
+ ## Clean up
558
+
559
+ ```bash
560
+ docker compose down -v
561
+ rm -rf tmp/ltr
562
+ ```
563
+
564
+ `down -v` also deletes the OpenSearch data volume.
565
+
566
+ ## Troubleshooting
567
+
568
+ | What you see | Cause | Fix |
569
+ |---|---|---|
570
+ | A load error that names `libomp.dylib` or `libgomp` | The OpenMP library is missing. | macOS: `brew install libomp`. Debian or Ubuntu: `apt install libgomp1`. |
571
+ | `bind: address already in use` for port 9200 | Another OpenSearch is running. | Stop it, or change `"9200:9200"` in `docker-compose.yml` and use the new port in `OPENSEARCH_URL`. |
572
+ | The OpenSearch container exits with code 137 | Docker ran out of memory. | Give Docker at least 4 GB, then run `docker compose up -d` again. |
573
+ | `OpenSearch URL is required` | `ubi_data_loader.opensearch.url` is empty. | Use the override from this guide. It sets the URL. |
574
+ | `ltr:train needs a config path` | The task got no config path. | Pass both paths: `"ltr:train[config/ltr/base.yml,config/ltr/local.yml]"`. |
575
+ | A run uses the wrong config when you pass one path | `LTR_CONFIG` is set in your shell. The one path then counts as the override. | Run `unset LTR_CONFIG`, or pass both paths. |
576
+ | `ArgumentError: UBI queries cannot be empty` and `Events loaded: 0 total events` in the log (`ruby` engine) | The index is empty, its events are outside the date range, or none has an action the loader counts. The loader ignores `impression` events. | Count events with `curl 'localhost:9200/ubi_events/_count'`. Check the `timestamp` values and raise `ubi_data_loader.max_days_ago` in the override if the events are too old. Check that events use an action named by a numerator or denominator in `dataset_builder.conversion_rate_targets`. |
577
+ | `ArgumentError: UBI events cannot be empty (no cascade-action events staged)` and `Staged 0 cascade-action event rows, 0 unique query IDs` in the log (`sqlite` engine) | No event matched the date and action filters, or every matching event has a blank query ID. The log has no `Events loaded` line. | Start with the checks for the `ruby` engine. Check that matching events have a query ID in the field named by `dataset_builder.query_id_field` (default `query_id`). |
578
+ | `Faraday::ConnectionFailed: Failed to open TCP connection to <host>:<port>` after 5 `OpenSearch request failed (attempt n/5)` warnings, with 100 seconds of waits between attempts, plus the time each attempt takes | Nothing answers at the URL in `ubi_data_loader.opensearch.url`. The error names the host and port but not the key. | Check `ubi_data_loader.opensearch.url` and `OPENSEARCH_URL`. Run `docker compose up -d` if the container is down. The old dataset and model stay in place. |
579
+ | `ltr:aggregate` ends without a line saying it wrote the dataset | The command filters for `ltr:aggregate`, which hides warnings such as `OpenSearch request failed`. | Rerun the `ltr:aggregate` command without the `grep` and `sed` pipes to see the full output. |
580
+ | <code>ArgumentError: No ubi_queries record has query_response_hit_ids. Check dataset_builder.hit_ids_field.</code> | No query document has hit ids under that field. | Check `dataset_builder.hit_ids_field`. Index queries with `Ltr::Ubi.query`. It requires `hit_ids:`. |
581
+ | <code>ArgumentError: None of the &lt;n&gt; events has `event_attributes.&lt;field&gt;`.</code> | No cascade-action event has the doc id under that field. This is the value of `dataset_builder.doc_id_field`. Events of other actions are not counted. | Check `dataset_builder.doc_id_field`. Index events with `Ltr::Ubi.event`. |
582
+ | `search_phase_execution_exception` with `No mapping found for [timestamp] in order to sort on` | The events index was created without the `timestamp` mapping. OpenSearch answers with HTTP 400, so the loader raises it at once. | Delete both indices. Create them again with the mapping files above. |
583
+ | `bulk load failed: ... Limit of total fields [1000]` | `ubi_queries` has no mapping, or `query_attributes` is not `enabled: false`. | Delete both indices. Create them again with the mappings above. |
584
+ | `Missing features in dataset: ...` warning in the log | A feature in the config is not a column of the CSV. The listed features are skipped. | Check the feature names in the config against the CSV columns. |