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,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads the feature lists and hyperparameters from SSM parameters.
4
+
5
+ class Ltr::Ssm::Loader
6
+ extend Ltr::Callable
7
+
8
+ HTTP_READ_TIMEOUT_SECONDS = 0.5
9
+
10
+ def initialize(config, load_all_features: false, load_feature_store_features: false, load_hyperparameters: false)
11
+ @ssm_config = config.ssm
12
+ @requested = { all_features: load_all_features, feature_store_features: load_feature_store_features, hyperparameters: load_hyperparameters }
13
+ end
14
+
15
+ # Returns a hash with only the values that were asked for: `:all_features`, `:feature_store_features` and `:hyperparameters`.
16
+ # The values are parsed JSON, so hyperparameter keys are strings.
17
+ # Raises `ArgumentError` when the path for a requested value is not configured.
18
+ # It does not check `ssm.enabled`. AWS errors such as `Aws::SSM::Errors::ParameterNotFound` pass through.
19
+ def call
20
+ validate_config!
21
+ create_ssm_client
22
+
23
+ requested_parameters.to_h { |parameter| [parameter, load_parameter_from_ssm(parameter)] }
24
+ end
25
+
26
+ private
27
+
28
+ attr_reader :ssm_config, :ssm_client, :requested
29
+
30
+ def requested_parameters
31
+ Ltr::Ssm::ParameterPaths::KEYS.keys.select { |parameter| requested[parameter] }
32
+ end
33
+
34
+ def param_path(parameter)
35
+ ssm_config&.dig(Ltr::Ssm::ParameterPaths::KEYS.fetch(parameter))
36
+ end
37
+
38
+ def validate_config!
39
+ requested_parameters.each do |parameter|
40
+ raise ArgumentError, "SSM #{parameter} path not configured" if param_path(parameter).blank?
41
+ end
42
+ end
43
+
44
+ def create_ssm_client
45
+ Ltr::OptionalDependency.require!("aws-sdk-ssm", feature: "SSM parameters")
46
+ @ssm_client = Aws::SSM::Client.new(http_read_timeout: HTTP_READ_TIMEOUT_SECONDS)
47
+ end
48
+
49
+ def load_parameter_from_ssm(parameter)
50
+ parameter_path = param_path(parameter)
51
+ logger.info("Loading optimized #{parameter} from SSM: #{parameter_path}")
52
+ response = ssm_client.get_parameter(name: parameter_path)
53
+ value = JSON.parse(response.parameter.value)
54
+ logger.info("Successfully loaded #{parameter} from SSM")
55
+ value
56
+ end
57
+
58
+ def logger
59
+ Ltr.config.logger
60
+ end
61
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ltr::Ssm::ParameterPaths
4
+ KEYS = {
5
+ all_features: "all_features_param_path",
6
+ feature_store_features: "feature_store_features_param_path",
7
+ hyperparameters: "hyperparameters_param_path",
8
+ }.freeze
9
+
10
+ # Only the list `[]` is valid for `feature_store_features`, and it means no stored features.
11
+ EMPTY_LIST_ALLOWED = %i[feature_store_features].freeze
12
+
13
+ # Returns true when `value` is blank, unless it is `[]` for a key in `EMPTY_LIST_ALLOWED`.
14
+ def self.missing_value?(parameter, value)
15
+ return false if value == [] && EMPTY_LIST_ALLOWED.include?(parameter)
16
+
17
+ value.blank?
18
+ end
19
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Saves the feature lists and hyperparameters to SSM parameters.
4
+
5
+ class Ltr::Ssm::Saver
6
+ extend Ltr::Callable
7
+
8
+ MAX_VALUE_BYTES = 8192
9
+
10
+ def initialize(config)
11
+ @config = config
12
+ end
13
+
14
+ # Writes `all_features`, `feature_store_features` and `hyperparameters` to their SSM parameters as JSON, replacing old values.
15
+ # It uses the Intelligent-Tiering tier, so a value over 4 KB is stored as an Advanced parameter.
16
+ # Raises `ArgumentError` when a value is missing (see `ParameterPaths.missing_value?`), when a path is blank, or when a JSON value is over `MAX_VALUE_BYTES`.
17
+ # The size check runs before the first write, so an oversize value stores none of the three parameters.
18
+ def call
19
+ validate_config!
20
+ validate_value_sizes!
21
+ create_ssm_client
22
+ values.each { |parameter, value| save_parameter(parameter, value) }
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :config, :ssm_client
28
+
29
+ def values
30
+ {
31
+ all_features: config.all_features,
32
+ feature_store_features: config.feature_store_features,
33
+ hyperparameters: config.hyperparameters,
34
+ }
35
+ end
36
+
37
+ def param_path(parameter)
38
+ config.ssm.dig(Ltr::Ssm::ParameterPaths::KEYS.fetch(parameter))
39
+ end
40
+
41
+ def validate_config!
42
+ values.each do |parameter, value|
43
+ raise ArgumentError, "#{parameter} cannot be empty" if Ltr::Ssm::ParameterPaths.missing_value?(parameter, value)
44
+ end
45
+ Ltr::Ssm::ParameterPaths::KEYS.each_key do |parameter|
46
+ raise ArgumentError, "SSM #{parameter} path not configured" if param_path(parameter).blank?
47
+ end
48
+ end
49
+
50
+ def validate_value_sizes!
51
+ values.each do |parameter, value|
52
+ bytesize = value.to_json.bytesize
53
+ next if bytesize <= MAX_VALUE_BYTES
54
+
55
+ raise ArgumentError, "SSM #{parameter} is #{bytesize} bytes. The limit is #{MAX_VALUE_BYTES}"
56
+ end
57
+ end
58
+
59
+ def create_ssm_client
60
+ Ltr::OptionalDependency.require!("aws-sdk-ssm", feature: "SSM parameters")
61
+ @ssm_client = Aws::SSM::Client.new(http_read_timeout: Ltr::Ssm::Loader::HTTP_READ_TIMEOUT_SECONDS)
62
+ end
63
+
64
+ def save_parameter(parameter, value)
65
+ ssm_client.put_parameter(
66
+ name: param_path(parameter),
67
+ value: value.to_json,
68
+ type: "String",
69
+ tier: "Intelligent-Tiering",
70
+ overwrite: true,
71
+ description: "Optimized #{parameter} for LTR model"
72
+ )
73
+
74
+ Ltr.config.logger.info("Successfully saved optimized #{parameter} to SSM: #{param_path(parameter)}")
75
+ end
76
+ end
@@ -0,0 +1,13 @@
1
+ # `lib/ltr/support`
2
+
3
+ Small cross-cutting helpers used throughout the `Ltr::` namespace. These provide the `OptionalDependency` loader for gems only some features need, the `Callable` mixin that gives services their `.call(...)` entry point, the `PipelineResult` value object that pipelines return, the `PipelineTask` runner behind the rake tasks, and the gem version constant.
4
+
5
+ ## Files
6
+
7
+ | File | Purpose |
8
+ |---|---|
9
+ | `callable.rb` | Mixin that lets a service be invoked as `Service.call(...)` instead of `Service.new(...).call`. |
10
+ | `optional_dependency.rb` | `OptionalDependency.require!` loads an optional gem when its feature runs. It raises `MissingDependencyError` naming the gem to add to the Gemfile. |
11
+ | `pipeline_task.rb` | Runs one pipeline for the `ltr:*` rake tasks: builds the config from the task arguments and `LTR_CONFIG` (one path is the whole config; `LTR_CONFIG` plus one argument is base + override; at least one is required), calls the pipeline, and logs a summary of its result. |
12
+ | `pipeline_result.rb` | Immutable value object returned by pipelines, carrying arbitrary result attributes. |
13
+ | `version.rb` | Defines the gem version constant `Ltr::VERSION`. |
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adds a class level call method that builds the object and calls it.
4
+
5
+ module Ltr::Callable
6
+ # Builds an instance with the given arguments, then calls it with the block.
7
+ def call(*, **, &)
8
+ new(*, **).call(&)
9
+ end
10
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Requires a gem that only some features need.
4
+
5
+ module Ltr::OptionalDependency
6
+ GEMS = {
7
+ "aws-sdk-s3" => { require_path: "aws-sdk-s3", limits: ["~> 1"] },
8
+ "aws-sdk-sagemaker" => { require_path: "aws-sdk-sagemaker", limits: ["~> 1"] },
9
+ "aws-sdk-sagemakerruntime" => { require_path: "aws-sdk-sagemakerruntime", limits: ["~> 1"] },
10
+ "aws-sdk-ssm" => { require_path: "aws-sdk-ssm", limits: ["~> 1"] },
11
+ "opensearch-ruby" => { require_path: "opensearch", limits: [">= 4.0.0.pre.beta.5", "< 5.a"] },
12
+ "sqlite3" => { require_path: "sqlite3", limits: ["~> 2.0"] },
13
+ }.freeze
14
+
15
+ # Activates the gem within its version limits, then requires it.
16
+ # Raises `Ltr::MissingDependencyError` if the gem is not installed or is outside its version limits.
17
+ # The message holds the Gemfile line to add and the original `LoadError` message.
18
+ def self.require!(gem_name, feature: nil)
19
+ entry = GEMS.fetch(gem_name)
20
+ gem(gem_name, *entry.fetch(:limits))
21
+ require entry.fetch(:require_path)
22
+ rescue LoadError => error
23
+ purpose = feature ? " for #{feature}" : ""
24
+ raise Ltr::MissingDependencyError, "The `#{gem_name}` gem is required#{purpose}. Add `#{gemfile_line(gem_name)}` to your Gemfile. (#{error.message})"
25
+ end
26
+
27
+ # Returns the Gemfile line that adds the gem within its version limits.
28
+ def self.gemfile_line(gem_name)
29
+ ["gem #{gem_name.inspect}", *GEMS.fetch(gem_name).fetch(:limits).map(&:inspect)].join(", ")
30
+ end
31
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Holds the outputs of a finished pipeline run.
4
+
5
+ class Ltr::PipelineResult
6
+ # The frozen hash of outputs.
7
+ attr_reader :attributes
8
+
9
+ def initialize(**attributes)
10
+ @attributes = attributes.freeze
11
+ end
12
+
13
+ # Returns one output of the run by key.
14
+ def [](key)
15
+ attributes[key]
16
+ end
17
+
18
+ # Returns a mutable copy of the output hash.
19
+ def to_h
20
+ attributes.dup
21
+ end
22
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Runs the aggregate, optimize or train pipeline by name with the config paths.
4
+
5
+ class Ltr::PipelineTask
6
+ extend Ltr::Callable
7
+
8
+ # The environment variable that holds the base config path.
9
+ CONFIG_ENV_VAR = "LTR_CONFIG"
10
+
11
+ # The pipeline class to run for each task name.
12
+ PIPELINES = {
13
+ aggregate: Ltr::DatasetAggregation::DatasetPipeline,
14
+ optimize: Ltr::Optimize::OptimizePipeline,
15
+ train: Ltr::Train::ModellingPipeline,
16
+ }.freeze
17
+
18
+ # `name` is `aggregate`, `optimize` or `train`. A blank path counts as not given.
19
+ # Unless both paths are given, the `LTR_CONFIG` path is put first as the base config.
20
+ # So when `LTR_CONFIG` is set, a single path is the override. When it is not set, a single path is the base.
21
+ def initialize(name, base_config_path: nil, override_config_path: nil)
22
+ @name = name.to_sym
23
+ paths = [base_config_path.presence, override_config_path.presence].compact
24
+ paths.unshift(ENV[CONFIG_ENV_VAR].presence) if paths.size < 2
25
+ @base_config_path, @override_config_path = paths.compact
26
+ end
27
+
28
+ # Runs the named pipeline with a `ConfigLoader` built from the config paths, and logs a summary of its result.
29
+ # Raises ArgumentError when the pipeline name is unknown or no config path is set.
30
+ # Returns the `Ltr::PipelineResult` of the pipeline.
31
+ def call
32
+ pipeline = PIPELINES.fetch(name) do
33
+ raise ArgumentError, "Unknown pipeline task '#{name}'. Available: #{PIPELINES.keys.join(", ")}"
34
+ end
35
+ if base_config_path.nil?
36
+ raise ArgumentError, "ltr:#{name} needs a config path. Usage: rake \"ltr:#{name}[base_config,override_config]\" " \
37
+ "or set #{CONFIG_ENV_VAR} (as the base; a single argument is then the override)"
38
+ end
39
+
40
+ log("base config: #{base_config_path}, override config: #{override_config_path || "none"}")
41
+ result = pipeline.call(build_config)
42
+ summary(result).each { |line| log(line) }
43
+ result
44
+ end
45
+
46
+ private
47
+
48
+ attr_reader :name, :base_config_path, :override_config_path
49
+
50
+ def log(message)
51
+ Ltr.config.logger.info("ltr:#{name} #{message}")
52
+ end
53
+
54
+ def build_config
55
+ Ltr::ConfigLoader.new(base_config_path: base_config_path, override_config_path: override_config_path)
56
+ end
57
+
58
+ def summary(result)
59
+ case name
60
+ in :aggregate
61
+ ["wrote #{result[:rows]} rows to #{result[:dataset_path]}"]
62
+ in :optimize
63
+ [
64
+ "search_time_features: #{result[:features][:search_time_features].inspect}",
65
+ "feature_store_features: #{result[:features][:feature_store_features].inspect}",
66
+ "hyperparameters: #{result[:hyperparameters].inspect}",
67
+ ]
68
+ in :train
69
+ [
70
+ "metrics: #{result[:metrics].inspect}",
71
+ "sagemaker deploy: #{describe_gate(result[:deployment])}",
72
+ "local deploy: #{describe_gate(result[:local_deployment])}",
73
+ ]
74
+ end
75
+ end
76
+
77
+ def describe_gate(gate)
78
+ details = gate.except(:deployed, :reason, :endpoint).map { |key, value| "#{key}=#{value}" }
79
+ ["deployed=#{gate[:deployed]}", "reason=#{gate[:reason]}", *details].join(", ")
80
+ end
81
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Defines the gem version.
4
+
5
+ module Ltr
6
+ VERSION = "0.1.0"
7
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Defines the rake tasks that run the aggregate, optimize and train pipelines.
4
+
5
+ namespace :ltr do
6
+ task :load_environment do
7
+ Rake::Task[:environment].invoke if Rake::Task.task_defined?(:environment)
8
+ end
9
+
10
+ desc "Run the LTR dataset aggregation pipeline"
11
+ task :aggregate, [:base_config, :override_config] => :load_environment do |_task, args|
12
+ Ltr::PipelineTask.call(:aggregate, base_config_path: args[:base_config], override_config_path: args[:override_config])
13
+ end
14
+
15
+ desc "Run the LTR feature and hyperparameter optimization pipeline"
16
+ task :optimize, [:base_config, :override_config] => :load_environment do |_task, args|
17
+ Ltr::PipelineTask.call(:optimize, base_config_path: args[:base_config], override_config_path: args[:override_config])
18
+ end
19
+
20
+ desc "Run the LTR training pipeline and deploy when the gates pass"
21
+ task :train, [:base_config, :override_config] => :load_environment do |_task, args|
22
+ Ltr::PipelineTask.call(:train, base_config_path: args[:base_config], override_config_path: args[:override_config])
23
+ end
24
+ end
@@ -0,0 +1,19 @@
1
+ # `lib/ltr/train`
2
+
3
+ The training pipeline for the `ltr` gem: it trains an XGBoost learning-to-rank model from the modelling dataset, evaluates it against the configured ranking metrics, and deploys it when eligible. Everything here lives in the `Ltr::Train::` namespace and is orchestrated by `ModellingPipeline.call(config)`.
4
+
5
+ The dataset carries three splits. Which split each stage reads is set in config. The [Data splits](../../../docs/data-splits.md) guide explains how queries are split and which split each stage reads.
6
+
7
+ ## Files
8
+
9
+ | File | Purpose |
10
+ |---|---|
11
+ | `modelling_pipeline.rb` | `ModellingPipeline.call(config)` entry point that loads the dataset, trains and evaluates the model, and deploys it to SageMaker (and/or locally) when above the configured threshold. |
12
+ | `deploy_metric.rb` | Reads `deploy.metric`, `deploy.minimum_metric_value` and the score for both deploys. Raises when one is missing or not numeric. |
13
+ | `deploy_gate.rb` | Checks `deploy.enabled`, the deploy metric and `deploy.minimum_metric_value`, deploys to SageMaker when the score passes. |
14
+ | `optimization_split_report.rb` | Evaluates the booster on the optimization split too and logs the gap to the reported split. |
15
+ | `xgb_trainer.rb` | Trains an XGBoost learning-to-rank model, sourcing features and hyperparameters from SSM when enabled and otherwise from the config. When `early_stopping_rounds` is set and the best round is before the last round, it trains a second time for `best_iteration + 1` rounds with early stopping off. |
16
+ | `xgb_evaluator.rb` | Evaluates a trained booster on the configured evaluation split, computing the configured ranking metrics per query group. |
17
+ | `eval_logger.rb` | XGBoost callback that logs the per-round eval lines (`verbose_eval`) to `Ltr.config.logger`, not to stdout. |
18
+ | `evaluation_cache.rb` | Caches one sorted split so repeated feature/hyperparameter trials skip re-sorting rows and rebuilding prediction inputs. |
19
+ | `utils.rb` | Shared training helpers, chiefly filtering requested features down to the columns actually present in the dataset. |
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Deploys the model only when the configured metric meets the minimum value.
4
+
5
+ class Ltr::Train::DeployGate
6
+ extend Ltr::Callable
7
+
8
+ def initialize(config, booster, metrics)
9
+ @config = config
10
+ @booster = booster
11
+ @metrics = metrics
12
+ end
13
+
14
+ # Returns a hash with `deployed` and a `reason`.
15
+ # With `deploy.enabled` false it skips with `:disabled` and checks no other setting.
16
+ # It deploys to SageMaker when the `deploy.metric` score is at least `deploy.minimum_metric_value`. The reason is `:threshold_met` and the hash adds `endpoint`.
17
+ # Below the minimum it skips with `:below_threshold` and adds `metric`, `score` and `threshold`.
18
+ # Raises `StandardError` when `deploy.enabled` is not a boolean, or the minimum or metric is invalid or missing.
19
+ def call
20
+ inputs = validate_inputs!
21
+ logger.debug { "Deployment inputs: #{inputs.inspect}" }
22
+
23
+ return skip_deploy_disabled if inputs[:enabled] == false
24
+
25
+ if inputs[:met]
26
+ deploy(inputs)
27
+ else
28
+ skip_deploy_below_threshold(inputs)
29
+ end
30
+ end
31
+
32
+ private
33
+
34
+ attr_reader :config, :booster, :metrics
35
+
36
+ def validate_inputs!
37
+ logger.info("Validating deployment inputs...")
38
+ enabled = config.deploy["enabled"]
39
+ raise StandardError, "deploy.enabled must be true or false (got #{enabled.inspect})" unless [true, false].include?(enabled)
40
+
41
+ if enabled == false
42
+ logger.info("Deployment is disabled in configuration")
43
+ return { enabled: false }
44
+ end
45
+
46
+ deploy_metric = Ltr::Train::DeployMetric.call(config, metrics)
47
+
48
+ logger.info(
49
+ "Deployment validation completed. Metric: #{deploy_metric[:metric_name]}, Score: #{deploy_metric[:score]}, Threshold: #{deploy_metric[:threshold]}"
50
+ )
51
+ { enabled: true }.merge(deploy_metric)
52
+ end
53
+
54
+ def skip_deploy_disabled
55
+ logger.info { "Deployment disabled by config (deploy.enabled=false). Skipping." }
56
+ logger.debug { "Result: deployed=false, metric=nil, threshold=nil, score=nil, reason=disabled" }
57
+ { deployed: false, reason: :disabled }
58
+ end
59
+
60
+ def deploy(inputs)
61
+ logger.info { "#{inputs[:metric_name]}=#{inputs[:score]} >= #{inputs[:threshold]} → deploying" }
62
+ info = Ltr::Deploy::SagemakerDeployer.call(config: config, booster: booster)
63
+ logger.info { "Deployment info: #{info.inspect}" }
64
+ logger.debug { "Result: deployed=true, metric=#{inputs[:metric_name]}, threshold=#{inputs[:threshold]}, score=#{inputs[:score]}" }
65
+ { deployed: true, reason: :threshold_met, endpoint: info }
66
+ end
67
+
68
+ def skip_deploy_below_threshold(inputs)
69
+ logger.info { "#{inputs[:metric_name]}=#{inputs[:score]} < #{inputs[:threshold]} → not deploying" }
70
+ logger.debug { "Result: deployed=false, metric=#{inputs[:metric_name]}, threshold=#{inputs[:threshold]}, score=#{inputs[:score]}" }
71
+ Ltr::Train::DeployMetric.below_threshold_result(inputs)
72
+ end
73
+
74
+ def logger
75
+ Ltr.config.logger
76
+ end
77
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reads the `deploy.metric` score and the `deploy.minimum_metric_value` threshold that both deploys compare.
4
+
5
+ class Ltr::Train::DeployMetric
6
+ extend Ltr::Callable
7
+
8
+ # Returns the result both deploys give when the score is below the minimum.
9
+ def self.below_threshold_result(deploy_metric)
10
+ {
11
+ deployed: false,
12
+ reason: :below_threshold,
13
+ metric: deploy_metric[:metric_name],
14
+ score: deploy_metric[:score],
15
+ threshold: deploy_metric[:threshold],
16
+ }
17
+ end
18
+
19
+ def initialize(config, metrics)
20
+ @config = config
21
+ @metrics = metrics
22
+ end
23
+
24
+ # Returns a hash with `metric_name`, `threshold`, `score` and `met` (true when the score is at least the threshold).
25
+ # Raises `StandardError` when the minimum is not numeric, the metric is missing or unknown, or its score is nil.
26
+ def call
27
+ threshold = parse_threshold!
28
+ metric_name = deploy_metric_name!
29
+ score = metric_score!(metric_name)
30
+ { metric_name: metric_name, threshold: threshold, score: score, met: score >= threshold }
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :config, :metrics
36
+
37
+ def parse_threshold!
38
+ threshold_raw = config.deploy["minimum_metric_value"]
39
+ Float(threshold_raw)
40
+ rescue ArgumentError, TypeError
41
+ raise StandardError, "deploy.minimum_metric_value must be a numeric value (got #{threshold_raw.inspect})"
42
+ end
43
+
44
+ def deploy_metric_name!
45
+ metric_name = Ltr::Metrics::MetricScores.normalize_name(config.deploy["metric"])
46
+ return metric_name unless metric_name.blank?
47
+
48
+ available = metrics.keys.map(&:to_s).sort
49
+ raise StandardError, "deploy.metric is required. Available metrics: #{available.join(", ")}"
50
+ end
51
+
52
+ def metric_score!(metric_name)
53
+ metrics_by_name = metrics.transform_keys(&:to_s)
54
+ unless metrics_by_name.key?(metric_name)
55
+ raise StandardError, "Deploy metric '#{metric_name}' not found. Available: #{metrics_by_name.keys.sort.join(", ")}"
56
+ end
57
+
58
+ score = metrics_by_name[metric_name]
59
+ raise StandardError, "Evaluator returned nil for metric '#{metric_name}'." if score.nil?
60
+
61
+ score
62
+ end
63
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ # `XGBoost::EvaluationMonitor` builds the eval line and decides which rounds to show, then prints it with a bare `puts`.
4
+ # This subclass swaps that `puts` for the logger, so the line format and the period rule stay the gem's own.
5
+ class Ltr::Train::EvalLogger < XGBoost::EvaluationMonitor
6
+ # `period` is the configured `verbose_eval`. `true` means every round.
7
+ def initialize(period)
8
+ super(period: (period == true) ? 1 : period)
9
+ end
10
+
11
+ private
12
+
13
+ def puts(message)
14
+ Ltr.config.logger.info(message.chomp)
15
+ end
16
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Scores a model on one split with per-query ranking metrics and caches the split data.
4
+
5
+ class Ltr::Train::EvaluationCache
6
+ # Builds a cache that scores one metric on one split.
7
+ def self.for_metric(df, config:, metric:, split:, split_cache: nil)
8
+ new(df, split: split, config: config, metrics_list: [metric], split_cache: split_cache)
9
+ end
10
+
11
+ # `metrics_list` defaults to `evaluation.metrics` in the config.
12
+ # `evaluation.min_relevance_grade` wins when set. Otherwise `evaluation.min_relevance_percentile` is turned into a grade from this split's labels.
13
+ # Raises `ArgumentError` when there are no metrics, no grade or percentile, or no rows in the split.
14
+ def initialize(df, split:, config: nil, metrics_list: nil, split_cache: nil)
15
+ evaluation = config.evaluation if config&.respond_to?(:evaluation)
16
+ @metrics_list = metrics_list || evaluation&.[]("metrics")
17
+ raise ArgumentError, "metrics_list is required" if @metrics_list.nil?
18
+
19
+ @split = split
20
+ @df_split = (split_cache || Ltr::Data::SplitCache.new(df)).sorted(split)
21
+ raise ArgumentError, "Split '#{split}' has no rows to evaluate" if @df_split.empty?
22
+
23
+ @qids = @df_split[:qid].to_a
24
+ @y_true = @df_split[:label].to_a
25
+
26
+ @min_relevance_grade = resolve_min_relevance(
27
+ evaluation&.[]("min_relevance_grade"),
28
+ evaluation&.[]("min_relevance_percentile")
29
+ )
30
+ end
31
+
32
+ # Predicts with the model and averages the per-query metrics over all queries. Every query counts the same.
33
+ # Returns a hash of metric spec to value, rounded to 4 places.
34
+ # It reuses the DMatrix when called again with the same `features`.
35
+ def evaluate(model, features)
36
+ preds = Ltr::Train::XgbTrainer.predict(model, dmatrix_for(features))
37
+
38
+ grouped = Ltr::Data::Dataframe.group_by_qid(@qids, preds, @y_true)
39
+ exp_gain = ndcg_exp_gain(model)
40
+ per_query_metrics = grouped.map do |pred, label|
41
+ Ltr::Metrics::MetricScores.call(
42
+ pred,
43
+ label,
44
+ @metrics_list,
45
+ min_relevance_grade: @min_relevance_grade,
46
+ ndcg_exp_gain: exp_gain
47
+ )
48
+ end
49
+
50
+ aggregate_metrics(per_query_metrics)
51
+ end
52
+
53
+ # Returns the value of one metric from `evaluate`.
54
+ # Raises `KeyError` when `metric_name` is not one of the cache's metrics.
55
+ def evaluate_metric(model, features, metric_name)
56
+ evaluate(model, features).fetch(Ltr::Metrics::MetricScores.normalize_name(metric_name))
57
+ end
58
+
59
+ private
60
+
61
+ def ndcg_exp_gain(model)
62
+ JSON.parse(model.save_config).dig("learner", "objective", "lambdarank_param", "ndcg_exp_gain") != "0"
63
+ end
64
+
65
+ def resolve_min_relevance(grade, percentile)
66
+ return grade unless grade.nil?
67
+
68
+ if percentile.nil?
69
+ raise ArgumentError, "min_relevance_grade or min_relevance_percentile is required"
70
+ end
71
+
72
+ threshold = Ltr::Metrics::Metrics.relevance_threshold(@y_true, percentile)
73
+ relevant_share = @y_true.count { |label| label >= threshold }.fdiv(@y_true.length)
74
+ logger.info(
75
+ "Resolved min_relevance_percentile #{percentile} to a label threshold of #{threshold} " \
76
+ "(#{(relevant_share * 100).round(2)}% of #{@y_true.length} #{@split} documents relevant)"
77
+ )
78
+
79
+ threshold
80
+ end
81
+
82
+ def dmatrix_for(features)
83
+ return @dmatrix if @dmatrix_features == features
84
+
85
+ @dmatrix_features = features.dup
86
+ @dmatrix = XGBoost::DMatrix.new(@df_split[features])
87
+ end
88
+
89
+ def aggregate_metrics(per_query_metric_scores)
90
+ metric_sums = per_query_metric_scores.each_with_object(Hash.new(0.0)) do |per_query_metrics, metric_accumulator|
91
+ per_query_metrics.each { |metric_name, metric_value| metric_accumulator[metric_name] += metric_value }
92
+ end
93
+
94
+ num_queries = per_query_metric_scores.size
95
+ metric_sums.transform_values { |sum| sum.fdiv(num_queries).round(4) }
96
+ end
97
+
98
+ def logger
99
+ Ltr.config.logger
100
+ end
101
+ end