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,128 @@
1
+ # Host integration
2
+
3
+ This page shows how to set up the `ltr` gem in the app that runs your search. It covers the gem settings, the config loader for User Behavior Insights (UBI), the optional gems and the services the pipelines use. For the pipeline's YAML settings, see [Config](config.md).
4
+
5
+ ## Glossary
6
+
7
+ | Term | Meaning |
8
+ |---|---|
9
+ | Config loader | An `Ltr::ConfigLoader`, the object that holds the pipeline config. It reads the base YAML file, merges an optional override file on top, runs ERB and checks the values. |
10
+ | Host app | The app that runs the search in OpenSearch, logs it to UBI and calls the gem to rerank the results. |
11
+ | Pipeline | One of the three entry points: dataset, optimize and modelling. None of them calls another. |
12
+ | S3 | Amazon S3, the AWS file storage service. It can hold the modelling CSV, the serving file and the model package. |
13
+ | 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. |
14
+ | 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`. |
15
+
16
+ The full list is in the [glossary](glossary.md).
17
+
18
+ ## What the host app provides
19
+
20
+ The host app runs searches and records the results and user actions as UBI query and event documents in [OpenSearch](https://opensearch.org/). `Ltr::Ubi` builds the documents, but the host app writes them to the indices. The pipelines use those documents to train a model. The host app then sends search results to the model for reranking.
21
+
22
+ [Logging UBI documents](ubi-logging.md) shows how to build and index the documents. [Inference](inference.md) shows how to send results to a model. To try the full process on a laptop, follow [Run the pipelines locally](run-locally.md).
23
+
24
+ ## Add the gems
25
+
26
+ Add `ltr` to your app's `Gemfile`. Add the optional gems for the features you use. The table shows the supported versions and when the gem loads each one.
27
+
28
+ | Gem | Version | Needed for |
29
+ |---|---|---|
30
+ | `opensearch-ruby` | `>= 4.0.0.pre.beta.5`, `< 5.a` | Loading UBI documents from OpenSearch |
31
+ | `sqlite3` | `~> 2.0` | The `sqlite` aggregation engine |
32
+ | `aws-sdk-s3` | `~> 1` | The default S3 client, for datasets, serving files and SageMaker model packages |
33
+ | `aws-sdk-ssm` | `~> 1` | Reading or writing SSM parameters |
34
+ | `aws-sdk-sagemaker` | `~> 1` | Deploying a model to SageMaker |
35
+ | `aws-sdk-sagemakerruntime` | `~> 1` | Calling a SageMaker endpoint |
36
+
37
+ A missing or unsupported optional gem raises `Ltr::MissingDependencyError` when its feature runs. The error gives the `Gemfile` line to add. A host that supplies its own S3 client through `s3_client_builder` does not need the default S3 client.
38
+
39
+ `require "ltr"` loads only the ActiveSupport core extensions that the gem uses. A host that needs another extension must require it itself.
40
+
41
+ ## Configure the gem
42
+
43
+ Copy `lib/ltr/configuration/example_config.yml` into your app and set the pipeline values as [Config](config.md) describes. The gem does not load that file unless you pass its path.
44
+
45
+ `Ltr.configure` sets the host settings that every pipeline shares. The gem has a default for each of the five settings below, so set only the ones your app needs. `Ltr.reset_config!` restores all of them to their defaults.
46
+
47
+ | Setting | Default | Change it when |
48
+ |---|---|---|
49
+ | `root` | `Dir.pwd`. A relative value is made absolute when you set it. | Your app does not start from the folder that holds its config files. A relative config path, `deploy.local_path` and `dataset_aggregation.staging_root` start at `root`. |
50
+ | `logger` | `Rails.logger` when Rails is loaded, otherwise a `Logger` on stdout | You want the gem's log lines to go to another logger. |
51
+ | `s3_client_builder` | Not set. The gem builds one `Aws::S3::Client` and reuses it. | You need your own S3 client, for example one per region. The gem calls the builder each time it needs a client. |
52
+ | `opensearch_connect_options_builder` | Not set. The gem builds one host from the URL with a 20 second request timeout and a 60 second open timeout. | Your OpenSearch client needs other options. The builder gets the URL, username and password and returns the hash for `OpenSearch::Client.new`. |
53
+ | `error_reporter` | `nil`, so errors are not reported | You want the feature store errors to go to an error tracker. The gem calls it with the error and a context hash, then raises the original error again. |
54
+
55
+ `root` does not change `training.modelling_dataset_path`. A relative dataset path starts at the process's working directory.
56
+
57
+ ## Build the loader for Ltr::Ubi
58
+
59
+ Pass an `Ltr::ConfigLoader` as `config:` on each `Ltr::Ubi.query` and `Ltr::Ubi.event` call. The gem keeps no global loader. A missing `config:` or a value that is not an `Ltr::ConfigLoader` raises `ArgumentError`.
60
+
61
+ Build the loader from the same base file and override file that the model's pipeline uses. The override file is deep-merged over the base file, so it only holds the values that differ for one variant, such as a region, a user group or an app. [Config](config.md#how-a-file-is-loaded) explains the merge and the validation.
62
+
63
+ In the example below, a host has one base file for its catalog search and one override file for its US users. The loader reads both files as soon as it is built, so a missing file raises `Ltr::ConfigurationError` at that point. A relative path starts at `Ltr.config.root`.
64
+
65
+ ```ruby
66
+ CATALOG_US_LTR = Ltr::ConfigLoader.new(
67
+ base_config_path: "config/ltr/catalog/config_base.yml",
68
+ override_config_path: "config/ltr/catalog/us_catalog_config.yml",
69
+ )
70
+ ```
71
+
72
+ `Ltr::Ubi` uses the loader to name the fields of its documents. The pipeline reads the same three `dataset_builder` keys back by those names, which is why both must come from the same files. [Logging UBI documents](ubi-logging.md#renaming-the-keys) shows how to rename them.
73
+
74
+ | Config key | Default | Field it names |
75
+ |---|---|---|
76
+ | `dataset_builder.query_id_field` | `query_id` | The query id in query and event documents |
77
+ | `dataset_builder.doc_id_field` | `doc_id` | The doc id in `event_attributes` |
78
+ | `dataset_builder.hit_ids_field` | `query_response_hit_ids` | The ordered list of document ids in a query document |
79
+
80
+ ### One host, two models
81
+
82
+ A host with several models builds one loader for each model. In the example below, the query ids and document ids are made up. Each call uses the loader of the model that will train on that search.
83
+
84
+ ```ruby
85
+ CATALOG_LTR = Ltr::ConfigLoader.new(
86
+ base_config_path: "config/ltr/catalog/config_base.yml",
87
+ override_config_path: "config/ltr/catalog/us_catalog_config.yml",
88
+ )
89
+ AUTOCOMPLETE_LTR = Ltr::ConfigLoader.new(
90
+ base_config_path: "config/ltr/autocomplete/config_base.yml",
91
+ override_config_path: "config/ltr/autocomplete/us_autocomplete_config.yml",
92
+ )
93
+
94
+ Ltr::Ubi.event(config: CATALOG_LTR, query_id: "q1", action_name: "view", doc_id: "prodA", timestamp: Time.now)
95
+ Ltr::Ubi.event(config: AUTOCOMPLETE_LTR, query_id: "q2", action_name: "view", doc_id: "itemA", timestamp: Time.now)
96
+ ```
97
+
98
+ ## Set up the services
99
+
100
+ The services you need depend on where you store data and serve the model. The table shows what each service does.
101
+
102
+ | Service | Used for |
103
+ |---|---|
104
+ | OpenSearch | The UBI query and event indices that the dataset pipeline reads |
105
+ | S3 | Datasets and serving files when their path starts with `s3://`, and the SageMaker model package |
106
+ | SSM Parameter Store | Chosen features and hyperparameters when `ssm.enabled` is `true` |
107
+ | SageMaker | Deploying a model to an endpoint and calling that endpoint |
108
+
109
+ The default S3 client and the SSM and SageMaker Runtime clients use the [AWS SDK for Ruby](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/credential-providers.html) defaults for credentials and region. The SageMaker deployer uses `training.s3_region` for its region. [Run the pipelines from a host app](host-run-pipelines.md#aws-resources) covers the resources. [Run the pipelines on AWS](run-on-aws.md#before-you-start) shows how to set them up.
110
+
111
+ ## Set the environment variables
112
+
113
+ The rake tasks read `LTR_CONFIG`. The other variables in the table are read by ERB in `lib/ltr/configuration/example_config.yml`. They apply to a config copied from that file, unless you change its ERB.
114
+
115
+ | Variable | What it sets | Rule |
116
+ |---|---|---|
117
+ | `LTR_CONFIG` | Base config path for the rake tasks | See [Pass the config paths](rake-tasks.md#pass-the-config-paths) for how it combines with task arguments. |
118
+ | `LTR_NTHREAD` | `training.nthread` | The example uses `4` when the variable is unset. |
119
+ | `OPENSEARCH_URL` | `ubi_data_loader.opensearch.url` | The UBI loader needs a URL. |
120
+ | `OPENSEARCH_USERNAME`, `OPENSEARCH_PASSWORD` | `ubi_data_loader.opensearch.username`, `ubi_data_loader.opensearch.password` | Passed to the OpenSearch options builder. |
121
+ | `SAGEMAKER_BUCKET` | `deploy.sagemaker_bucket` | Required when `deploy.enabled` is `true`. |
122
+ | `SAGEMAKER_EXECUTION_ROLE` | `deploy.execution_role` | Required when `deploy.enabled` is `true`. |
123
+
124
+ ## Next steps
125
+
126
+ - Log searches and user actions with [Logging UBI documents](ubi-logging.md).
127
+ - Run the pipelines with [Rake tasks](rake-tasks.md) or [from Ruby](host-run-pipelines.md#run-the-pipelines-from-ruby).
128
+ - Send search results to the model as [Inference](inference.md) describes. [Features](features.md) lists the values the host sends.
@@ -0,0 +1,48 @@
1
+ # Run the pipelines from a host app
2
+
3
+ This page lists the AWS resources the gem uses, how to call each pipeline from Ruby, and what the deployment results hold. For the host settings and environment variables, see [Host integration](host-integration.md).
4
+
5
+ ## AWS resources
6
+
7
+ - **S3**: dataset read and write, [dataset serving files](model-files.md#dataset-serving-file), model tarballs, and feature store JSON (client from `Ltr.config.s3_client`)
8
+ - **SSM Parameter Store**: optimized features and hyperparameters (paths under `ssm.*_param_path`). The saver uses the `Intelligent-Tiering` tier, so a value over 4096 characters becomes an Advanced parameter. Advanced is billed per parameter per month, and SSM cannot move it back to Standard.
9
+ - **SageMaker**: model and endpoint deployment, and runtime invocation
10
+ - **OpenSearch**: the UBI `queries` and `events` indices
11
+
12
+ S3, SSM and SageMaker Runtime use the AWS SDK default credential and region chain. The deployer reads its region from `training.s3_region` instead. It has a built-in container image for each region in `Ltr::Deploy::SagemakerEndpoint::IMAGE_REGISTRY_ACCOUNTS`. Any other region raises `Unsupported region` unless `deploy.image_uri` is set.
13
+
14
+ [Run the pipelines on AWS](run-on-aws.md#before-you-start) shows how to create each one.
15
+
16
+ ## Run the pipelines from Ruby
17
+
18
+ Each pipeline is `Pipeline.call(config)`. It returns a `Ltr::PipelineResult`. Read an output with `result[:key]`. Use `result.to_h` for a mutable copy of the output hash. A failed pipeline raises.
19
+
20
+ | Pipeline | Keys |
21
+ |---|---|
22
+ | `DatasetPipeline` | `rows`, `columns`, `enriched`, `dataset_path` |
23
+ | `OptimizePipeline` | `features`, `hyperparameters`, `ssm_saved` |
24
+ | `ModellingPipeline` | `metrics`, `optimization_split_metrics`, `deployed`, `deployment`, `local_deployment` |
25
+
26
+ `result[:deployed]` is true when the deploy gate sent the model to SageMaker. `result[:deployment]` and `result[:local_deployment]` are hashes with `deployed:` and `reason:` keys. They hold the outcome of the SageMaker deploy and of the local save. A `:below_threshold` hash also has `metric:`, `score:` and `threshold:` keys.
27
+
28
+ ### Deployment results
29
+
30
+ `result[:deployment]` comes from `Ltr::Train::DeployGate` (`lib/ltr/train/deploy_gate.rb`). Its `reason` is one of three values:
31
+
32
+ | `reason` | `deployed` | Other keys |
33
+ |---|---|---|
34
+ | `:disabled` | `false` | none. `deploy.enabled` is `false`. |
35
+ | `:below_threshold` | `false` | `metric`, `score`, `threshold` |
36
+ | `:threshold_met` | `true` | `endpoint`, the hash that `SagemakerDeployer` returns |
37
+
38
+ `endpoint` has the keys `endpoint_name`, `endpoint_arn`, `status`, `creation_time` and `last_modified_time` (`lib/ltr/deploy/sagemaker_endpoint.rb`).
39
+
40
+ `result[:local_deployment]` comes from `ModellingPipeline` (`lib/ltr/train/modelling_pipeline.rb`). Its `reason` is one of three values:
41
+
42
+ | `reason` | `deployed` | Other keys |
43
+ |---|---|---|
44
+ | `:not_configured` | `false` | none. `deploy.local` is not `true`. |
45
+ | `:below_threshold` | `false` | `metric`, `score`, `threshold`. The `deploy.metric` score is below `deploy.minimum_metric_value`, so no file is written. A file from an earlier run stays in place and keeps being served. With no earlier file, `Ltr::Inference::LocalReranker` raises an XGBoost error when it loads the missing path. Check `result[:local_deployment][:reason]` before you rerank. |
46
+ | `:local_saved` | `true` | `path`, the file the model was saved to |
47
+
48
+ These hashes may change in a minor release.
data/docs/index.md ADDED
@@ -0,0 +1,50 @@
1
+ # Documentation
2
+
3
+ ## Guides
4
+
5
+ - [Run the pipelines locally](run-locally.md): train and use a model on a laptop with Docker. No AWS.
6
+ - [Run the pipelines on AWS](run-on-aws.md): use S3, SSM and a SageMaker endpoint.
7
+
8
+ ## Concepts
9
+
10
+ - [Learning to rank](learning-to-rank.md): what the gem trains, how rows are grouped into queries, and why the work is split into three pipelines.
11
+ - [Training objective](training-objective.md): how LambdaMART weights its pairs, and why the labels need `ndcg_exp_gain: false`.
12
+ - [Data splits](data-splits.md): how queries are split, and which split each stage reads.
13
+ - [Optimization](optimization.md): how `ltr:optimize` picks the features and then the hyperparameters, and what it writes back.
14
+ - [Labels from behavior](labels-from-behavior.md): how clicks and purchases become `raw_label`, with cascade impressions, smoothing, negatives and `debug_mode`.
15
+ - [Glossary](glossary.md): short definitions of the terms the docs use.
16
+ - [Architecture](../ARCHITECTURE.md): how the gem is built inside.
17
+
18
+ ## Using the gem
19
+
20
+ - [Host integration](host-integration.md): set up the host app, optional gems, `Ltr.configure`, the `Ltr::Ubi` loader, services and environment variables.
21
+ - [Run the pipelines from a host app](host-run-pipelines.md): AWS resources, pipeline calls from Ruby and deployment results.
22
+ - [Rake tasks](rake-tasks.md): run the pipelines on a schedule.
23
+ - [Inference](inference.md): rerank results with a trained model.
24
+ - [Dataset enrichers](dataset-enrichers.md): join host-app features into the dataset.
25
+ - [Label transformers](label-transformers.md): what label each built-in transformer writes, why `sqrt` is the default, why the per-query transformers make NDCG more sensitive to the order, and how to write your own.
26
+ - [Logging UBI documents](ubi-logging.md): log searches and user actions with `Ltr::Ubi`, including the keys it writes, how to rename them, the timestamps it accepts, and which actions to send.
27
+ - [Public API stability](public-api.md): the entry points that must not change, and the internal classes that may.
28
+
29
+ ## Reference
30
+
31
+ - [Config](config.md)
32
+ - [Data contracts](data-contracts.md)
33
+ - [UBI documents](ubi-documents.md)
34
+ - [Modelling dataset CSV](dataset-csv.md)
35
+ - [Model and feature store files](model-files.md)
36
+ - [Metrics](metrics.md)
37
+ - [Relevance grades](relevance-grades.md)
38
+ - [Aggregation engines](aggregation-engines.md)
39
+ - [Dataset builder steps](dataset-builder-steps.md)
40
+ - [Feature selection](feature-selection.md)
41
+ - [Features](features.md)
42
+ - [Errors](errors.md)
43
+
44
+ ## Contributing
45
+
46
+ - [Contributing](../CONTRIBUTING.md): set up the project and open a pull request.
47
+ - [Agent and contributor guide](../AGENTS.md): layout, conventions and testing rules.
48
+ - [Writing the docs](AGENTS.md): how a page under `docs/` is laid out and worded.
49
+ - [Changelog](../CHANGELOG.md): breaking changes and release notes.
50
+ - [Code map](../lib/ltr/README.md): what each folder under `lib/ltr/` holds. Most folders have their own `README.md`.
data/docs/inference.md ADDED
@@ -0,0 +1,164 @@
1
+ # Inference
2
+
3
+ Call a trained model to rerank search results. This page owns the request and response formats.
4
+
5
+ ```ruby
6
+ # Dispatches to local inference when deploy.local is true, otherwise SageMaker:
7
+ Ltr::Inference::Base.call(payload, config)
8
+
9
+ # Or call a backend directly:
10
+ Ltr::Inference::SagemakerClient.call(payload, config)
11
+ Ltr::Inference::SagemakerClient.call(payload, nil, "custom-endpoint-name")
12
+ Ltr::Inference::LocalReranker.call(payload, config)
13
+ ```
14
+
15
+ `config` may be `nil` when you pass a custom endpoint name to `SagemakerClient`.
16
+
17
+ For a working call against a deployed endpoint, see [Call the endpoint](run-on-aws.md#call-the-endpoint). For the local backend, see [Rerank a search locally](run-locally.md#rerank-a-search).
18
+
19
+ ## Inference request
20
+
21
+ `Ltr::Inference::Base.call(payload, config, backend_type = nil, **options)` picks the backend.
22
+ With no `backend_type`, it uses the local reranker when `deploy.local` is `true`. Otherwise it calls SageMaker.
23
+ Pass `"local"` or `"sagemaker"` to choose directly.
24
+
25
+ The payload for the two backends differs.
26
+
27
+ | Backend | `payload` |
28
+ |---|---|
29
+ | `local` | An array of items. |
30
+ | `sagemaker` | An object with an `items` array. Other keys are allowed and are passed through. |
31
+
32
+ `Base.call` options:
33
+
34
+ | Option | Backend | Meaning |
35
+ |---|---|---|
36
+ | `custom_model_path:` | `local` | Model file to load instead of `deploy.local_path`. |
37
+ | `custom_model_endpoint:` | `sagemaker` | Endpoint name to call instead of `<model.name>-endpoint`. |
38
+
39
+ `SagemakerClient` accepts a `nil` config when you pass `custom_model_endpoint`. It then uses a 0.5 second open timeout and read timeout. Through `Base.call`, a `nil` config needs the `"sagemaker"` backend type as the third argument, such as `Base.call(payload, nil, "sagemaker", custom_model_endpoint: name)`. Without it, `Base.call` raises `NoMethodError`. You can also call `SagemakerClient` directly.
40
+
41
+ ### Item
42
+
43
+ ```json
44
+ {
45
+ "id": "prodA",
46
+ "fields": [
47
+ { "name": "bm25_name", "value": 0.9 },
48
+ { "name": "relevancy", "value": 12.1 },
49
+ { "name": "view_count", "value": 340 }
50
+ ]
51
+ }
52
+ ```
53
+
54
+ | Field | Type | Rule |
55
+ |---|---|---|
56
+ | `id` | string or number | Returned as a string in the response. |
57
+ | `fields` | array | One object per feature, each with `name` (string) and `value` (number). |
58
+
59
+ ### Local payload
60
+
61
+ ```json
62
+ [
63
+ { "id": "prodA", "fields": [ { "name": "bm25_name", "value": 0.9 } ] },
64
+ { "id": "prodB", "fields": [ { "name": "bm25_name", "value": 0.7 } ] }
65
+ ]
66
+ ```
67
+
68
+ ### SageMaker payload
69
+
70
+ ```json
71
+ {
72
+ "items": [
73
+ { "id": "prodA", "fields": [ { "name": "bm25_name", "value": 0.9 } ] },
74
+ { "id": "prodB", "fields": [ { "name": "bm25_name", "value": 0.7 } ] }
75
+ ]
76
+ }
77
+ ```
78
+
79
+ The client sends the payload as the JSON request body with content type `application/json`.
80
+ A body without an `items` key is rejected by the endpoint with HTTP 400.
81
+
82
+ The endpoint runs the SageMaker XGBoost container. The container calls `transform_fn` in `code/inference.py` for each request. `transform_fn` returns a 400 response for bad input. Any other error is an HTTP 500, because the container turns every other exception into a 500.
83
+
84
+ ### Rules for fields
85
+
86
+ - Send raw feature values, such as `bm25_name`. This holds for feature-store features too. Never copy a value from `feature_store.json` or the modelling CSV into `fields`, because both hold transformed values. A host whose feature-store feature has a transform must compute the raw value itself. Both backends transform every value in `fields` with the saved steps. Do not send `_rank` or `_relative_score` values. Both backends compute them across all items in the request, when the model needs them.
87
+ - The model decides which features are used and in what order. Fields it does not use do not affect scoring, but a boolean `value` in any field still raises.
88
+ - An item with no `fields` key or `"fields": null` is scored as if it had `"fields": []`. Every base feature is then missing and comes from the feature store. Both backends add no `_rank` or `_relative_score` field to that item, so those features are `NaN` for it. An item with `"fields": []` does get them, computed from a score of 0.
89
+ - A feature that the model needs and the item lacks, or sends as `null` or `NaN`, is read from the feature store by both backends, with the item id as a string. The store is there when the model was deployed with `feature_store.include_in_deployment: true`. If the item id is not in the store, the value is missing, and XGBoost treats it as missing.
90
+ - The SageMaker endpoint reads the store from `code/feature_store.json` in the model package.
91
+ - The local reranker reads the store from the `feature_store` attribute in the model file. `LocalDeployer` saves it there, so deploy again after the store data changes.
92
+ - A missing or `null` score that the model ranks gives `NaN` for `<name>_rank` and `<name>_relative_score` in both backends, and the endpoint scores the item.
93
+ - The endpoint answers bad input with HTTP 400 and the reason in the body. Bad input is a body that is not JSON, a content type other than `application/json`, a payload that is not an object, `items` missing or not a list, an item that is not an object or has a missing or `null` `id`, `fields` that is not a list, a field that is not an object or has a `name` that is not a string, and an `Accept` other than `application/json` or `*/*`. A missing `Accept` is read as `application/json`. A `value` that is bad input has its own rows in the table below. A fault in the model or the handler stays HTTP 500.
94
+ - The local reranker raises `ArgumentError` for a payload that is not an array. It raises `Ltr::ConfigurationError` when neither `deploy.local` with `deploy.local_path` nor `custom_model_path` is set.
95
+ - Both backends return an empty `items` array for an empty request.
96
+ - The request is sent as one batch. Ranks and relative scores are computed only among the items in that batch.
97
+ - The local reranker adds the computed `_rank` and `_relative_score` fields to your `fields` arrays. It changes the objects you pass in.
98
+ - A candidate with no base score, or a `null` one, gets `NaN` in its `_rank` and `_relative_score` fields. The gem never turns the items into JSON, but a host that does must pass `allow_nan: true` to `JSON.generate`. Without it, Ruby raises `JSON::GeneratorError`. The gem loads ActiveSupport's JSON extension. With that extension, `to_json` writes `NaN` as `null` instead of raising.
99
+
100
+ ### How each backend reads a field value
101
+
102
+ The table shows what the SageMaker endpoint and the local reranker do with each kind of `value` in a field the model uses. A `NaN` or `null` value is missing. XGBoost reads a missing value as missing, so it is neither scored as a number nor rejected. Each backend clamps a value twice, because XGBoost rejects an infinity when it builds the matrix. It clamps once when it reads the request value, before the rank and relative score are computed, and once on the final matrix value after the transform steps. The limit is `FLOAT32_MAX` in `inference.py` and `Ltr::Features::Float32Range::FLOAT32_MAX` in Ruby. Both are 3.4028234663852886e38.
103
+
104
+ | Value sent | SageMaker endpoint | Local reranker |
105
+ |---|---|---|
106
+ | A number in the float32 range | Used as it is, then transformed. | Used as it is, then transformed. |
107
+ | A numeric string | Becomes a float. | Becomes a float. |
108
+ | Text that is not a number, a list or an object | HTTP 400. An empty string or an empty list is rejected even when the field only feeds a `_rank` or `_relative_score` feature. | Raises `ArgumentError` for text and `TypeError` for a list or an object. |
109
+ | The text `"inf"` or `"Infinity"` | Clamped to plus or minus `FLOAT32_MAX` and scored. | Raises `ArgumentError`, because `Float` rejects it. |
110
+ | The text `"nan"` | Missing, the same as `null`. | Raises `ArgumentError`, because `Float` rejects it. |
111
+ | A `NaN` number, which is a bare `NaN` in the JSON body on the endpoint and `Float::NAN` locally | Missing, the same as `null`. It takes the feature store value, or the transformed 0 for a one-hot column. | Missing, the same as `nil`. It takes the feature store value, or the transformed 0 for a one-hot column. |
112
+ | An infinity, a number or integer past the float32 range such as `1e39` or `10**400`, and the text `"1e999"` | Clamped to plus or minus `FLOAT32_MAX` and scored. | Clamped to plus or minus `FLOAT32_MAX` and scored. |
113
+ | A value that a `z_score` step pushes past the float32 range | Clamped to plus or minus `FLOAT32_MAX` and scored. | Clamped to plus or minus `FLOAT32_MAX` and scored. |
114
+ | A boolean, in any field | HTTP 400 with the message `Field <name> of item <id> is a boolean. Send a number.` | Raises `ArgumentError` with the same message. |
115
+ | `null`, a field with no `value` key, and a field the item leaves out | Missing. It takes the feature store value, or the transformed 0 for a one-hot column, or else `NaN`. | Missing. It takes the feature store value, or the transformed 0 for a one-hot column, or else `nil`. |
116
+
117
+ ## Inference response
118
+
119
+ Both backends return the same shape.
120
+
121
+ ```json
122
+ {
123
+ "items": [
124
+ { "item": "prodA", "score": 0.81 },
125
+ { "item": "prodB", "score": 0.34 }
126
+ ],
127
+ "took_seconds": 0.0006
128
+ }
129
+ ```
130
+
131
+ | Field | Type | Meaning |
132
+ |---|---|---|
133
+ | `items` | array | All request items, sorted by `score` from high to low. Items with equal scores keep the request order. |
134
+ | `items[].item` | string | The request `id`, as a string. |
135
+ | `items[].score` | number | The model score. Scores are comparable only within one response. They can be negative. |
136
+ | `took_seconds` | number | Time spent on scoring inside the backend. It does not include network time. |
137
+
138
+ `SagemakerClient` returns the endpoint's JSON as a Hash with string keys.
139
+ `LocalReranker` returns the same keys as a Hash with string keys.
140
+
141
+ ## Local model cache
142
+
143
+ `LocalReranker` loads the model once per path and keeps it until `Ltr::Inference::LocalReranker.reset!` is called. It reads the feature transform steps, the one-hot column names and the feature store stored in the model file at the same time and keeps them with the model, so a new model is never scored with an old store. `LocalDeployer` saves the model to a temp file and renames it over `deploy.local_path`, so a reader never sees a half-written model. The host reloads only through `reset!`. After a local deploy, call it in each process, or restart the process. Each process in a multi-process server has its own cache.
144
+
145
+ Every value in the request is transformed with the saved steps, feature-store features included, so send raw values. A value that either backend reads from the feature store is not transformed, because the store already holds transformed values. A one-hot column that the request leaves out or sends as `null`, and that the store does not have, is treated as a raw `0` and goes through the saved steps. One lock guards every prediction in the process, so threads score one at a time.
146
+
147
+ ## Failures
148
+
149
+ `SagemakerClient` does not rescue AWS errors. The open and read timeouts are 0.5 seconds unless [`inference.sagemaker`](config.md#inference) sets them. A host should rescue the error and keep the original order.
150
+
151
+ ```ruby
152
+ begin
153
+ Ltr::Inference::SagemakerClient.call(payload, config)
154
+ rescue Aws::Errors::ServiceError, Seahorse::Client::NetworkingError
155
+ original_items
156
+ end
157
+ ```
158
+
159
+ This rescue covers the SageMaker backend only.
160
+ The local backend raises XGBoost or file errors, not AWS errors.
161
+
162
+ ## Reuse the config
163
+
164
+ `ConfigLoader.new` reads, runs ERB on and validates the YAML every time. Build it once at boot and pass the same object to each call.
@@ -0,0 +1,242 @@
1
+ # Label transformers
2
+
3
+ A label transformer turns `raw_label` into the `label` the model trains on. This page explains what label each built-in transformer writes, why `sqrt` spreads the training weight across more pairs, when to use a per-query transformer, and how to write your own. [Labels from behavior](labels-from-behavior.md) explains how `raw_label` is built.
4
+
5
+ ## Glossary
6
+
7
+ | Term | Meaning |
8
+ |---|---|
9
+ | DCG, IDCG | Discounted Cumulative Gain adds up each document's gain times $`1 / \log_2(\text{rank} + 1)`$. IDCG is the DCG of the best possible (or Ideal) order for the query. |
10
+ | Gain | The amount a document adds to DCG before the rank discount. With `ndcg_exp_gain: false`, as in the shipped config, the gain is the label. Otherwise it is $`2^{\text{label}} - 1`$. |
11
+ | `label` | The target value for training the model. |
12
+ | LambdaMART | The pairwise ranking method behind the XGBoost `rank:ndcg` objective. |
13
+ | Negative | A document with 0 impressions in every session of its query group. It is kept only when `dataset_builder.cascade_cutoff` is `false`. Its `raw_label` and `label` are 0. |
14
+ | `qid` | The id of one query group. The gem numbers the kept groups from 1 with no gaps, after `min_documents_per_query` drops the small ones. |
15
+ | `raw_label` | The sum of `weight × smoothed rate` over the conversion-rate targets. It is the label before any transformer. |
16
+ | Shipped | The value in `lib/ltr/configuration/example_config.yml`. It can differ from the value the code uses when the key is missing. |
17
+
18
+ The full list is in the [glossary](glossary.md).
19
+
20
+ ## Built-in transformers
21
+
22
+ `label_transformer.class` names the class. Every built-in class is in the `Ltr::DatasetAggregation::` namespace.
23
+
24
+ | Class | `label` | Fitted on |
25
+ |---|---|---|
26
+ | `SqrtLabelTransformer` | $`\sqrt{\text{raw\_label}}`$. Shipped default. | each row |
27
+ | `IdentityLabelTransformer` | `raw_label`. Used when `label_transformer.class` is blank or unset. | each row |
28
+ | `LogPlusOneLabelTransformer` | $`\ln(1 + \text{raw\_label})`$. | each row |
29
+ | `QuantileLabelTransformer` | An integer bucket from the quantiles of the raw labels above 0. It runs from 1 to `dataset_builder.label_quantiles - 1`. That is 9 with the shipped `label_quantiles` of `10`. A `raw_label` of 0 gets 0. | the whole dataset |
30
+ | `PerQueryMinMaxLabelTransformer` | Each query's raw labels rescaled so the lowest gets `low` and the highest gets `high`. The `range: [low, high]` setting sets them. The default is `[0, 1]`. | each query |
31
+ | `PerQueryKMeansLabelTransformer` | Each query's raw labels binned into integer grades from 0 to `groups - 1`, plus `offset`. | each query |
32
+
33
+ ### Calculating the smoothed rate of a document
34
+
35
+ `LabelCreator` works out a smoothed rate for each document and each target in `dataset_builder.conversion_rate_targets`. The rate mixes the document's own counts with two numbers that belong to the target. The first is `nu`, which you set as `dataset_builder.conversion_rate_targets[].nu`. It has no default, and it must be a number above 0. The second is the prior, which the gem works out from the dataset and has no config key. The prior is the target's numerator total divided by its denominator total, over all the labelled rows. A document's smoothed rate for one target is:
36
+
37
+ ```math
38
+ r = \frac{n + \mu \nu}{m + \nu}
39
+ ```
40
+
41
+ - $`r`$ is the smoothed rate of the document.
42
+ - $`n`$ is the document's numerator count, such as `view_count`.
43
+ - $`m`$ is the document's denominator count. The default denominator is `impression_count`.
44
+ - $`\mu`$ is the target's prior.
45
+ - $`\nu`$ is the target's `nu`.
46
+
47
+ Take the four documents A to D from [Per-query transformers](#per-query-transformers), with the shipped targets `ctr`, `atcr` and `cvr`. Their numerators are `view_count`, `add_to_cart_count` and `purchase_count`, so the table calls them the view rate, the add-to-cart rate and the purchase rate. Each document has an `impression_count` of 10. So the labelled rows hold 40 impressions, 9 views, 3 add-to-carts and 1 purchase. Document D has no actions, so $`n = 0`$ for every target. `LabelCreator` gives D these rates:
48
+
49
+ | Target | `weight` | `nu` | Prior | D's numerator count | D's `impression_count` | Smoothed rate | `weight × rate` |
50
+ |---|---|---|---|---|---|---|---|
51
+ | View rate | 1 | 50 | 9 ÷ 40 = 0.225 | 0 | 10 | 0.1875 | 0.1875 |
52
+ | Add-to-cart rate | 2 | 100 | 3 ÷ 40 = 0.075 | 0 | 10 | 0.0682 | 0.1364 |
53
+ | Purchase rate | 3 | 150 | 1 ÷ 40 = 0.025 | 0 | 10 | 0.0234 | 0.0703 |
54
+ | D's `raw_label` | | | | | | | 0.3942 |
55
+
56
+ D has no actions, but its `raw_label` is above 0. Each prior is above 0, so $`\mu \nu`$ is above 0 and each of D's rates is above 0.
57
+
58
+ #### When is a `raw_label` 0?
59
+
60
+ A smoothed rate is 0 only when $`n = 0`$ and the prior is 0. A prior is 0 when no labelled row has the target's numerator action, or when the target's denominator total is 0. Take the four documents again, but with no purchase in any labelled row. The purchase rate prior is 0 ÷ 40 = 0, so D's purchase rate is 0. D's `raw_label` drops to 0.1875 + 0.1364 = 0.3239, and it stays above 0 because the other two priors are above 0. So a `raw_label` is 0 only when every target with a `weight` above 0 has a prior of 0. Then every labelled row has a `raw_label` of 0.
61
+
62
+ ### The range of `raw_label`
63
+
64
+ `raw_label` adds up each target's `weight` times the document's smoothed rate for that target. Each smoothed rate is between 0 and 1, so `raw_label` is between 0 and the sum of the weights:
65
+
66
+ ```math
67
+ \text{raw\_label} = \sum_{t} w_t \, r_t, \qquad 0 \le r_t \le 1, \qquad 0 \le \text{raw\_label} \le \sum_{t} w_t
68
+ ```
69
+
70
+ - $`t`$ is one target in `dataset_builder.conversion_rate_targets`.
71
+ - $`w_t`$ is the `weight` of target $`t`$. It must be 0 or more.
72
+ - $`r_t`$ is the document's smoothed rate for target $`t`$, from [Calculating the smoothed rate of a document](#calculating-the-smoothed-rate-of-a-document).
73
+
74
+ A smoothed rate is never below 0, because every count and every prior is 0 or more. A smoothed rate is at most 1, because the top of the fraction $`(n + \mu \nu) / (m + \nu)`$ is never larger than the bottom. That holds for two reasons:
75
+
76
+ - `LabelCreator` raises `ArgumentError` when a row's numerator count is above its denominator count, so $`n \le m`$. A target that sets `allow_invariant_violation: true` gets a warning and no error, and its rates can go above 1.
77
+ - The prior is a numerator total divided by a denominator total. Each numerator count is at most its denominator count, so the prior is also at most 1, and $`\mu \nu \le \nu`$.
78
+
79
+ The table shows the largest amount each shipped target can add to `raw_label`:
80
+
81
+ | Target | `weight` | Largest smoothed rate | Largest amount added to `raw_label` |
82
+ |---|---|---|---|
83
+ | View rate | 1 | 1 | 1 |
84
+ | Add-to-cart rate | 2 | 1 | 2 |
85
+ | Purchase rate | 3 | 1 | 3 |
86
+ | Total | 1 + 2 + 3 = 6 | | 6 |
87
+
88
+ So with the shipped `conversion_rate_targets`, `raw_label` runs from 0 to 6. It reaches 6 only when all three smoothed rates are 1.
89
+
90
+ ### Documents below the cascade cutoff
91
+
92
+ The cascade is the rule that decides which documents a user examined in a session. A cascade action is an action named as a `numerator` or a `denominator` in `dataset_builder.conversion_rate_targets`, other than `impression`. With the shipped targets, the cascade actions are `view`, `add_to_cart` and `purchase`. In each session, the [cascade cutoff](labels-from-behavior.md#cascade-impressions) is the deepest position with a cascade action. Each document at or above the cutoff gets an `impression_count` of 1. A session with no cascade action adds no rows.
93
+
94
+ In the example below, the search result has six documents. The session is made up. The user views P2 and adds P4 to the cart, so the cutoff is position 4.
95
+
96
+ | Position | Document | Cascade action | `impression_count` with `cascade_cutoff: true` | `impression_count` with `cascade_cutoff: false` |
97
+ |---|---|---|---|---|
98
+ | 1 | P1 | | 1 | 1 |
99
+ | 2 | P2 | `view` | 1 | 1 |
100
+ | 3 | P3 | | 1 | 1 |
101
+ | 4 | P4 | `add_to_cart` (cutoff) | 1 | 1 |
102
+ | 5 | P5 | | no row | 0 |
103
+ | 6 | P6 | | no row | 0 |
104
+
105
+ So the gem keeps the documents below the cutoff, with an `impression_count` of 0, only when `dataset_builder.cascade_cutoff` is `false`. The gem then adds up each document's rows over all the sessions of its query. If P5 was at or above the cutoff in another session of the query, its `impression_count` total is above 0, and it gets a label like any other row. A document whose `impression_count` total is 0 was below the cutoff in every session. These documents are the [negatives](labels-from-behavior.md#negatives). They skip the label step and the transformer. After the transformer runs, the gem appends them with a `raw_label` of 0 and a `label` of 0. [Config](config.md#label_transformer) lists the keys and their rules.
106
+
107
+ ## Why `sqrt` is the default
108
+
109
+ With `ndcg_exp_gain: false` (shipped), the gain of a document is its label. The gain rule is in XGBoost's [`src/objective/lambdarank_obj.h`](https://github.com/dmlc/xgboost/blob/v3.4.0/src/objective/lambdarank_obj.h#L42-L60). LambdaMART weights a pair by the change in NDCG when the two documents swap, as [Training objective](training-objective.md#how-lambdamart-weights-a-pair) explains. For documents $`i`$ and $`j`$ in the same query, that weight is:
110
+
111
+ ```math
112
+ w_{ij} = \frac{\lvert (g_i - g_j)(d_i - d_j) \rvert}{\mathrm{IDCG}}
113
+ ```
114
+
115
+ - $`g_i`$ is the gain of document $`i`$, which is its label.
116
+ - $`d_i = 1 / \log_2(r_i + 1)`$ is the discount of document $`i`$, where $`r_i`$ is its rank, starting at 1.
117
+ - $`\mathrm{IDCG}`$ is the DCG of the best order of the query's documents.
118
+
119
+ The weight of a pair grows with the gap between the two gains. Take two pairs of one query with the same discount gap. If the label gap of one pair is 10 times the label gap of the other, its weight is 10 times as large.
120
+
121
+ `sqrt` shrinks the gaps between high labels more than the gaps between low labels. Take a made-up query with 50 documents in the best order:
122
+
123
+ | Group | Documents | `raw_label` | `sqrt` label |
124
+ |---|---|---|---|
125
+ | Bought | 1 | 3.0 | 1.7321 |
126
+ | Viewed | 9 | 1.0 | 1.0 |
127
+ | Seen and skipped | 40 | 0.8 | 0.8944 |
128
+
129
+ The top gap is bought minus viewed. The bottom gap is viewed minus seen and skipped. With `raw_label`, the top gap is 2.0 ÷ 0.2 = 10 times the bottom gap. With `sqrt`, it is 0.7321 ÷ 0.1056 = 6.9 times the bottom gap.
130
+
131
+ The 50 documents make 409 pairs with different labels. The table puts the pairs into groups by the two documents in each pair. It gives each group's share of the total pair weight, from the formula above.
132
+
133
+ | Pair group | Pairs | Share with `raw_label` | Share with `sqrt` |
134
+ |---|---|---|---|
135
+ | Bought and viewed | 1 × 9 = 9 | 11.6% | 10.6% |
136
+ | Bought and seen and skipped | 1 × 40 = 40 | 74.2% | 70.6% |
137
+ | All pairs with the bought document | 9 + 40 = 49 | 85.8% | 81.3% |
138
+ | Viewed and seen and skipped | 9 × 40 = 360 | 14.2% | 18.7% |
139
+ | All pairs | 49 + 360 = 409 | 100% | 100% |
140
+
141
+ So with `sqrt`, the 360 pairs of a viewed document and a seen and skipped document get more of the weight. Their share grows from 14.2% to 18.7%.
142
+
143
+ ## Per-query transformers
144
+
145
+ The smoothed rate formula in [Calculating the smoothed rate of a document](#calculating-the-smoothed-rate-of-a-document) adds `nu` made-up impressions at the prior's rate to each document. When `nu` is large relative to a document's `impression_count`, there are many more made-up impressions than real ones. So the document's rate stays close to the target's prior. Documents with few impressions then get nearly the same rates, and so nearly the same `raw_label`. Take a made-up dataset with one query of four documents and the shipped `conversion_rate_targets`. Each document was seen in 10 sessions:
146
+
147
+ | Document | `view_count` | `add_to_cart_count` | `purchase_count` | `raw_label` | `PerQueryMinMaxLabelTransformer` label |
148
+ |---|---|---|---|---|---|
149
+ | A | 5 | 2 | 1 | 0.5326 | 1.0 |
150
+ | B | 3 | 1 | 0 | 0.4624 | 0.4925 |
151
+ | C | 1 | 0 | 0 | 0.4108 | 0.1204 |
152
+ | D | 0 | 0 | 0 | 0.3942 | 0.0 |
153
+
154
+ Every raw label is at least 0.3942. That shared amount adds to the DCG of every order, so even the worst order gets an NDCG close to 1. With their defaults, both per-query transformers give each query's lowest document a label of 0. The table scores the worst order, D, C, B, A, with `ndcg_exp_gain: false`:
155
+
156
+ | Gain | D | C | B | A | NDCG of D, C, B, A |
157
+ |---|---|---|---|---|---|
158
+ | `raw_label` | 0.3942 | 0.4108 | 0.4624 | 0.5326 | 0.9287 |
159
+ | `PerQueryMinMaxLabelTransformer` label | 0.0 | 0.1204 | 0.4925 | 1.0 | 0.5492 |
160
+
161
+ Both per-query transformers fit each `qid` on its own. So a label can only be compared with labels of the same query. Within a query, a higher raw label never gets a lower label.
162
+
163
+ `PerQueryMinMaxLabelTransformer` writes this label for each document:
164
+
165
+ ```math
166
+ y = l + (h - l) \frac{x - x_{\min}}{x_{\max} - x_{\min}}
167
+ ```
168
+
169
+ - $`y`$ is the label of the document.
170
+ - $`x`$ is the `raw_label` of the document.
171
+ - $`x_{\min}`$ and $`x_{\max}`$ are the lowest and highest `raw_label` of the query.
172
+ - $`l`$ and $`h`$ are `low` and `high` from the `range: [low, high]` setting. The default is `[0, 1]`.
173
+
174
+ A query whose raw labels are all equal gets `low` for every document. Use it when you want to keep the ratios between a query's label gaps. Its labels are fractions, so it needs `ndcg_exp_gain: false`.
175
+
176
+ `PerQueryKMeansLabelTransformer` sorts each query's raw labels into `groups` clusters with one-dimensional k-means, the same way scikit-learn 1.7's [`KBinsDiscretizer(strategy="kmeans")`](https://scikit-learn.org/1.7/modules/generated/sklearn.preprocessing.KBinsDiscretizer.html) does. The lowest group gets 0 plus `offset`. `groups` defaults to `5` and `offset` to `0`. Equal raw labels get equal labels, and a query can get fewer than `groups` grades. Use it when you want whole-number grades, or when you want to try `ndcg_exp_gain: true`.
177
+
178
+ ```yaml
179
+ label_transformer:
180
+ class: "Ltr::DatasetAggregation::PerQueryKMeansLabelTransformer"
181
+ groups: 5
182
+ offset: 0
183
+ ```
184
+
185
+ ## Write your own
186
+
187
+ A label transformer is a class. The pipeline calls `Transformer.call(aggregated_data, config:)` once, after the label step, with every labelled row. `config` is the config object of the run. The base class keeps both arguments and reads them with the private methods `aggregated_data` and `config`. A subclass that defines `initialize` must take the same two arguments and call `super`. To write one, subclass `Ltr::DatasetAggregation::LabelTransformer` and define the private method `transform(aggregated_data)`.
188
+
189
+ `aggregated_data` is an `Ltr::Data::RowStore` with one row per query and document. Its `:raw_label` column holds the raw labels. `transform` writes a `:label` column and returns the `RowStore`. This example sets each label to $`\ln(1 + \text{raw\_label})`$:
190
+
191
+ ```ruby
192
+ class MyApp::Ltr::MyLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
193
+ private
194
+
195
+ def transform(aggregated_data)
196
+ raw_labels = pluck_column(aggregated_data, :raw_label)
197
+ set_labels(aggregated_data, raw_labels.map { |raw_label| Math.log(1 + raw_label) })
198
+ end
199
+ end
200
+ ```
201
+
202
+ `pluck_column(data, key)` returns one column as an array. `set_labels(data, labels)` writes the `:label` column and returns the `RowStore`, so it can be the last line of `transform`.
203
+
204
+ Name the class in config:
205
+
206
+ ```yaml
207
+ label_transformer:
208
+ class: "MyApp::Ltr::MyLabelTransformer"
209
+ ```
210
+
211
+ Before `transform` runs, the base class raises `ArgumentError` if `aggregated_data` is not a `RowStore`, is empty, or has no `:raw_label` column. With `cascade_cutoff: false`, the gem appends the negatives with a label of 0 after your class runs. So treat 0 as the lowest label.
212
+
213
+ ### Write a per-query transformer
214
+
215
+ To fit each query on its own, subclass `Ltr::DatasetAggregation::PerQueryLabelTransformer` instead. It groups the rows by `:qid` and calls the private method `query_labels(values)` once per query. `values` holds the query's raw labels as floats. `query_labels` returns one label per value, in the same order. The base class writes the `:label` column. It raises `ArgumentError` if the `RowStore` has no `:qid` column.
216
+
217
+ This example subtracts the query's lowest raw label from each raw label, then raises the result to the power `power`:
218
+
219
+ ```ruby
220
+ class MyApp::Ltr::MyPerQueryLabelTransformer < Ltr::DatasetAggregation::PerQueryLabelTransformer
221
+ def self.settings_from(label_transformer)
222
+ { power: setting(label_transformer, "power", 1, "a number above 0") { |value| value.is_a?(Numeric) && value > 0 } }
223
+ end
224
+
225
+ private
226
+
227
+ def query_labels(values)
228
+ lowest = values.min
229
+ values.map { |value| (value - lowest)**settings[:power] }
230
+ end
231
+ end
232
+ ```
233
+
234
+ `self.settings_from(label_transformer)` is optional. It gets the `label_transformer` section of the config as a hash and returns your settings. The default returns `{}`. `query_labels` reads the result from `settings`. The private class method `setting(label_transformer, key, default, requirement)` reads one key. It raises `Ltr::ConfigurationError` when the block returns false. `ConfigValidator` also calls `settings_from` when the config loads, so a bad value fails before the dataset is built.
235
+
236
+ ```yaml
237
+ label_transformer:
238
+ class: "MyApp::Ltr::MyPerQueryLabelTransformer"
239
+ power: 2
240
+ ```
241
+
242
+ A class outside the `Ltr::DatasetAggregation::` namespace can add any key under `label_transformer`. The config load gives no unknown-key warning for these keys.