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,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Adds derived features such as rank and relative score for each query.
4
+
5
+ class Ltr::Features::FeatureEngineering
6
+ # These constants and the rank math must match deploy/artifacts/code/inference.py.
7
+ AVAILABLE_METHODS = %w[rank relative_score].freeze
8
+ BM25_FEATURE_PREFIX = "bm25_"
9
+ FEATURE_ENGINEERING_EXCLUDED = %w[bm25_fields_matched].freeze
10
+ ADDITIONAL_ENGINEERED_FEATURES = %w[relevancy].freeze
11
+
12
+ class << self
13
+ # Raises ArgumentError when `methods` names a method other than `rank` or `relative_score`. Blank `methods` pass.
14
+ def validate_methods!(methods)
15
+ return if methods.blank?
16
+
17
+ unknown_methods = methods - AVAILABLE_METHODS
18
+ return if unknown_methods.empty?
19
+
20
+ raise ArgumentError,
21
+ "Unknown feature engineering method: #{unknown_methods.join(", ")}. " \
22
+ "Available methods: #{AVAILABLE_METHODS.join(", ")}"
23
+ end
24
+
25
+ # Returns the names of the features that `methods` would add, such as `bm25_title_rank`.
26
+ # Only `feature_names` that pass `engineerable?` get derived names.
27
+ # Returns an empty array when there are no methods.
28
+ def derived_feature_names(feature_names, methods)
29
+ return [] if methods.blank?
30
+
31
+ engineerable = feature_names.select { |feature| engineerable?(feature) }
32
+ methods.flat_map { |method| engineerable.map { |feature| "#{feature}_#{method}" } }
33
+ end
34
+
35
+ # True for a name that starts with `bm25_` (except `bm25_fields_matched`) and for `relevancy`.
36
+ def engineerable?(feature)
37
+ name = feature.to_s
38
+ return false if FEATURE_ENGINEERING_EXCLUDED.include?(name)
39
+
40
+ name.start_with?(BM25_FEATURE_PREFIX) || ADDITIONAL_ENGINEERED_FEATURES.include?(name)
41
+ end
42
+
43
+ # Adds the configured derived columns to each query's rows in place and returns the same data.
44
+ # Only columns that pass `engineerable?` get derived columns. Rows are grouped by `:qid`.
45
+ # A value that is nil or NaN is a missing score. Its derived values are NaN and it does not change the other rows. When methods are configured, `aggregated_data` must be a `Ltr::Data::RowStore`.
46
+ def engineer_features(aggregated_data, config)
47
+ methods = config.feature_engineering
48
+ return aggregated_data if methods.blank?
49
+
50
+ raise ArgumentError, "Aggregated data must be a RowStore" unless aggregated_data.is_a?(Ltr::Data::RowStore)
51
+
52
+ engineerable_features = aggregated_data.keys.select { |feature| engineerable?(feature) }
53
+ return aggregated_data if engineerable_features.empty?
54
+
55
+ engineer_by_qid(aggregated_data, engineerable_features, methods)
56
+
57
+ aggregated_data
58
+ end
59
+
60
+ # Adds the derived fields that `feature_names` asks for to each inference item in place and returns the items.
61
+ # An item without a `fields` list gets no new fields, and its score is missing.
62
+ # A base field an item lacks, or holds as nil, is a missing score.
63
+ # A missing score gets NaN rank and relative_score and does not change the other items. A real 0.0 keeps rank -1 and relative_score 0.0.
64
+ # An infinite score or one past the float32 range is clamped to plus or minus `Float32Range::FLOAT32_MAX` before the rank and relative score are computed.
65
+ def engineer_features_for_items(items, feature_names)
66
+ return items if items.blank?
67
+
68
+ engineering_map = detect_engineering_from_feature_names(feature_names)
69
+ return items if engineering_map.empty?
70
+
71
+ field_lookups = build_field_lookups(items)
72
+
73
+ engineering_map.each do |base_feature, methods|
74
+ scores = extract_scores(field_lookups, base_feature)
75
+ append_engineered_features(items, base_feature, methods, scores)
76
+ end
77
+
78
+ items
79
+ end
80
+
81
+ # Returns a hash of base feature name to the methods that `feature_names` asks for, such as `{ "bm25_title" => ["rank"] }`.
82
+ def detect_engineering_from_feature_names(feature_names)
83
+ engineering_map = {}
84
+
85
+ feature_names.each do |name|
86
+ name_str = name.to_s
87
+
88
+ AVAILABLE_METHODS.each do |method|
89
+ suffix = "_#{method}"
90
+ next unless name_str.end_with?(suffix)
91
+
92
+ base_name = name_str.chomp(suffix)
93
+ next unless engineerable?(base_name)
94
+
95
+ (engineering_map[base_name] ||= []) << method
96
+ end
97
+ end
98
+
99
+ engineering_map
100
+ end
101
+
102
+ private
103
+
104
+ def engineer_by_qid(row_store, engineerable_features, methods)
105
+ row_indices_by_qid = Hash.new { |groups, qid| groups[qid] = [] }
106
+ row_store.length.times { |index| row_indices_by_qid[row_store.row_at(index)[:qid]] << index }
107
+
108
+ row_indices_by_qid.each_value do |row_indices|
109
+ rows = row_indices.map { |index| row_store.row_at(index) }
110
+ apply_engineering_methods(rows, engineerable_features, methods)
111
+ rows.zip(row_indices) { |row, index| row_store.merge_row(index, row) }
112
+ end
113
+ end
114
+
115
+ def apply_engineering_methods(query_docs, engineerable_features, methods)
116
+ engineerable_features.each do |feature_name|
117
+ scores = query_docs.map { |doc| doc[feature_name]&.to_f }
118
+
119
+ methods.each do |method|
120
+ derived_name = :"#{feature_name}_#{method}"
121
+ derived_values = compute_method(method, scores)
122
+
123
+ query_docs.each_with_index do |doc, idx|
124
+ doc[derived_name] = derived_values[idx]
125
+ end
126
+ end
127
+ end
128
+ end
129
+
130
+ def compute_method(method, scores)
131
+ case method
132
+ when "rank"
133
+ compute_rank(scores)
134
+ when "relative_score"
135
+ compute_relative_score(scores)
136
+ end
137
+ end
138
+
139
+ # Ties share the lowest rank (1, 2, 2, 4). Scores that are zero or negative get -1. A missing score gets NaN.
140
+ def compute_rank(scores)
141
+ descending = scores.select { |score| score&.positive? }.sort.reverse
142
+
143
+ rank_by_score = {}
144
+ descending.each_with_index { |score, index| rank_by_score[score] ||= index + 1 }
145
+
146
+ scores.map do |score|
147
+ next Float::NAN if missing_score?(score)
148
+
149
+ score.positive? ? rank_by_score[score] : -1
150
+ end
151
+ end
152
+
153
+ # The largest present score is the divisor. A missing score gets NaN.
154
+ def compute_relative_score(scores)
155
+ max_score = scores.reject { |score| missing_score?(score) }.max || 0.0
156
+
157
+ scores.map do |score|
158
+ next Float::NAN if missing_score?(score)
159
+
160
+ (max_score <= 0.0) ? 0.0 : (score / max_score).round(3)
161
+ end
162
+ end
163
+
164
+ def missing_score?(score)
165
+ score.nil? || score.nan?
166
+ end
167
+
168
+ def build_field_lookups(items)
169
+ items.map do |item|
170
+ fields = item["fields"] || []
171
+ fields.to_h { |f| [f["name"], f["value"]] }
172
+ end
173
+ end
174
+
175
+ def extract_scores(field_lookups, feature_name)
176
+ field_lookups.map do |lookup|
177
+ value = lookup[feature_name]
178
+ Ltr::Features::Float32Range.clamp(Float(value)) unless value.nil?
179
+ end
180
+ end
181
+
182
+ def append_engineered_features(items, base_feature, methods, scores)
183
+ methods.each do |method|
184
+ new_feature_name = "#{base_feature}_#{method}"
185
+ new_feature_values = compute_method(method, scores)
186
+
187
+ items.each_with_index do |item, idx|
188
+ fields = item["fields"] || []
189
+ fields << { "name" => new_feature_name, "value" => new_feature_values[idx] }
190
+ end
191
+ end
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Applies the configured transforms, such as log1p, sqrt and z-score, to feature columns.
4
+
5
+ class Ltr::Features::FeatureTransformer
6
+ extend Ltr::Callable
7
+
8
+ # The steps `call` applied, in order, as `TransformSteps` hashes.
9
+ attr_reader :steps
10
+
11
+ def initialize(aggregated_data, config:)
12
+ @aggregated_data = aggregated_data
13
+ @config = config
14
+ @steps = []
15
+ end
16
+
17
+ # Applies each configured transform to its features in place and returns the same data.
18
+ # Only numeric values change. `log1p` and `sqrt` also leave negative values as they are.
19
+ # A `z_score` mean and std skip NaN values. A column with no value other than NaN gets no step, so it stays NaN.
20
+ # It skips features that are not in `all_features`, with a warning.
21
+ # Raises `ArgumentError` for an unknown transform, but only when the transform lists a feature that is in `all_features`.
22
+ # Raises `ArgumentError` when any transform is configured and the data is not a `RowStore`.
23
+ def call
24
+ transformations = @config.feature_transformations
25
+ return @aggregated_data if transformations.blank?
26
+
27
+ raise ArgumentError, "Aggregated data must be a RowStore" unless aggregated_data.is_a?(Ltr::Data::RowStore)
28
+
29
+ known_features = config.all_features.map(&:to_sym).to_set
30
+
31
+ transformations.each do |transform_name, feature_names|
32
+ known, unknown = feature_names.partition { |name| known_features.include?(name.to_sym) }
33
+ unknown.each { |name| logger.warn("Feature '#{name}' listed in feature_transformations is not in all_features, skipping") }
34
+ next if known.empty?
35
+
36
+ apply_transformation(transform_name, known.map(&:to_sym))
37
+
38
+ logger.info("Applied '#{transform_name}' transformation to #{feature_names.length} features: #{feature_names.join(", ")}")
39
+ end
40
+
41
+ @aggregated_data
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :aggregated_data, :config
47
+
48
+ def apply_transformation(transform_name, feature_syms)
49
+ new_steps = build_steps(transform_name, feature_syms)
50
+ new_steps.each { |step| apply_step(step) }
51
+ @steps.concat(new_steps)
52
+ end
53
+
54
+ def build_steps(transform_name, feature_syms)
55
+ case transform_name
56
+ when "log1p", "sqrt"
57
+ feature_syms.select { |feat| column?(feat) }.map { |feat| { "feature" => feat.to_s, "transform" => transform_name } }
58
+ when "z_score"
59
+ compute_feature_stats(feature_syms).map do |feat, (mean, std)|
60
+ { "feature" => feat.to_s, "transform" => transform_name, "mean" => mean, "std" => std }
61
+ end
62
+ else
63
+ raise ArgumentError, "Unknown feature transformation: #{transform_name}."
64
+ end
65
+ end
66
+
67
+ def column?(feat)
68
+ aggregated_data.keys.include?(feat)
69
+ end
70
+
71
+ def apply_step(step)
72
+ aggregated_data.update_column(step["feature"].to_sym) do |value, _index|
73
+ value.is_a?(Numeric) ? Ltr::Features::TransformSteps.apply_step(step, value) : value
74
+ end
75
+ end
76
+
77
+ def compute_feature_stats(feature_syms)
78
+ feature_syms.each_with_object({}) do |feat, stats|
79
+ # NaN is a missing value. One NaN in the mean would make the step's stats NaN, which `JSON.generate` cannot write.
80
+ values = aggregated_data.pluck(feat).select { |value| value.is_a?(Numeric) && !(value.respond_to?(:nan?) && value.nan?) }
81
+ next if values.empty?
82
+
83
+ mean = values.sum.to_f / values.length
84
+ variance = values.sum { |v| (v - mean)**2 } / values.length
85
+ stats[feat] = [mean, Math.sqrt(variance)]
86
+ end
87
+ end
88
+
89
+ def logger
90
+ Ltr.config.logger
91
+ end
92
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Limits a number to the float32 range, which is the range of the XGBoost matrix.
4
+ # This must match `FLOAT32_MAX` and `_clamp_to_float32` in deploy/artifacts/code/inference.py.
5
+ # `float32_max` in spec/fixtures/serving_rows.json checks that both constants have the same value.
6
+
7
+ module Ltr::Features::Float32Range
8
+ FLOAT32_MAX = 3.4028234663852886e38
9
+
10
+ module_function
11
+
12
+ # Returns `value` limited to plus or minus `FLOAT32_MAX`. An infinity becomes the matching limit.
13
+ # `nil` and `NaN` come back as they are, because XGBoost reads them as missing.
14
+ def clamp(value)
15
+ return value unless value.is_a?(Numeric)
16
+ return value if value.is_a?(Float) && value.nan?
17
+
18
+ value.clamp(-FLOAT32_MAX, FLOAT32_MAX).to_f
19
+ end
20
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Applies saved feature transform steps to one value.
4
+ # A step is a hash with string keys: `feature`, `transform`, and `mean` and `std` for `z_score`.
5
+
6
+ module Ltr::Features::TransformSteps
7
+ module_function
8
+
9
+ # Runs every step for `feature` on `value`, in the order the steps were saved.
10
+ # Only numeric values change. A value of another type comes back as it is.
11
+ def apply(steps, feature, value)
12
+ steps.reduce(value) do |current, step|
13
+ (step["feature"] == feature) ? apply_step(step, current) : current
14
+ end
15
+ end
16
+
17
+ # `log1p` and `sqrt` leave negative values as they are. `z_score` gives 0.0 for a present value when
18
+ # `std` is 0. A `NaN` stays `NaN`, so a missing value is never turned into 0.0.
19
+ # Raises `ArgumentError` for an unknown transform.
20
+ def apply_step(step, value)
21
+ return value unless value.is_a?(Numeric)
22
+
23
+ case step["transform"]
24
+ when "log1p" then (value >= 0) ? Math.log(value + 1) : value
25
+ when "sqrt" then (value >= 0) ? Math.sqrt(value) : value
26
+ when "z_score"
27
+ return value if value.is_a?(Float) && value.nan?
28
+
29
+ step["std"].zero? ? 0.0 : (value - step["mean"]) / step["std"]
30
+ else
31
+ raise ArgumentError, "Unknown feature transformation: #{step["transform"]}."
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Saves and loads what serving needs from training and deploy: the feature transform steps, the one-hot column names and the feature store.
4
+ # The dataset file is one JSON file next to the modelling dataset with the steps and the names. It can also hold the fallback totals for documents with no train rows. The model file holds them as XGBoost attributes, and a local deploy can add the feature store.
5
+
6
+ module Ltr::Features::TransformStore
7
+ DATASET_SUFFIX = ".serving.json"
8
+ MODEL_ATTRIBUTE = :feature_transforms
9
+ ONE_HOT_COLUMNS_ATTRIBUTE = :one_hot_columns
10
+ FEATURE_STORE_ATTRIBUTE = :feature_store
11
+ FALLBACK_FEATURE_TOTALS_KEY = :fallback_feature_totals
12
+
13
+ class << self
14
+ # Writes the steps and the one-hot column names next to the modelling dataset, locally or in S3. It replaces an old file.
15
+ # The fallback totals (doc id to feature name to value) get their own key, and only when there are any.
16
+ def write_dataset(config, steps, one_hot_columns, fallback_feature_totals = {})
17
+ content = { MODEL_ATTRIBUTE => steps, ONE_HOT_COLUMNS_ATTRIBUTE => one_hot_columns }
18
+ content[FALLBACK_FEATURE_TOTALS_KEY] = fallback_feature_totals if fallback_feature_totals.present?
19
+ write_json(dataset_path(config), content)
20
+ end
21
+
22
+ # Reads the file saved next to the modelling dataset.
23
+ # Raises `Ltr::ConfigurationError` if S3 returns `NoSuchKey` or the local file is missing.
24
+ # S3 can return `AccessDenied` for a missing key without `s3:ListBucket`. That error passes through.
25
+ def read_dataset(config)
26
+ path = dataset_path(config)
27
+ json = read_file(path)
28
+ return JSON.parse(json) if json
29
+
30
+ raise Ltr::ConfigurationError, "#{path} was not found. Run ltr:aggregate again."
31
+ end
32
+
33
+ def delete_dataset(config)
34
+ delete_file(dataset_path(config))
35
+ end
36
+
37
+ # Stores the steps in the booster, so `save_model` writes them into the model file. An empty list replaces old steps.
38
+ def write_model_steps(booster, steps)
39
+ booster.set_attr(MODEL_ATTRIBUTE => JSON.generate(steps))
40
+ end
41
+
42
+ # Returns the steps stored in the booster, or an empty list for a model saved without them.
43
+ def read_model_steps(booster)
44
+ JSON.parse(booster.attr(MODEL_ATTRIBUTE) || "[]")
45
+ end
46
+
47
+ # Stores the one-hot column names in the booster, so `save_model` writes them into the model file. An empty list replaces old names.
48
+ def write_model_one_hot_columns(booster, names)
49
+ booster.set_attr(ONE_HOT_COLUMNS_ATTRIBUTE => JSON.generate(names))
50
+ end
51
+
52
+ # Returns the names stored in the booster, or an empty list for a model saved without them.
53
+ def read_model_one_hot_columns(booster)
54
+ JSON.parse(booster.attr(ONE_HOT_COLUMNS_ATTRIBUTE) || "[]")
55
+ end
56
+
57
+ # Stores the feature store (feature name to doc id to value) in the booster as compact JSON. A `nil` store deletes the attribute.
58
+ def write_model_feature_store(booster, store)
59
+ booster.set_attr(FEATURE_STORE_ATTRIBUTE => store && JSON.generate(store))
60
+ end
61
+
62
+ # Returns the feature store stored in the booster, or an empty hash for a model saved without one.
63
+ def read_model_feature_store(booster)
64
+ JSON.parse(booster.attr(FEATURE_STORE_ATTRIBUTE) || "{}")
65
+ end
66
+
67
+ # Stores the steps and the one-hot column names that the dataset was built with in the booster.
68
+ # Pass the hash `read_dataset` returned as `dataset` to skip reading the file again.
69
+ def write_model_attributes(booster, config, dataset = read_dataset(config))
70
+ steps, one_hot_columns = dataset.fetch_values(MODEL_ATTRIBUTE.to_s, ONE_HOT_COLUMNS_ATTRIBUTE.to_s)
71
+ write_model_steps(booster, steps)
72
+ write_model_one_hot_columns(booster, one_hot_columns)
73
+ end
74
+
75
+ private
76
+
77
+ def dataset_path(config)
78
+ config.modelling_dataset_path.delete_suffix(".csv") + DATASET_SUFFIX
79
+ end
80
+
81
+ def write_json(path, value)
82
+ json = JSON.generate(value)
83
+
84
+ if path.start_with?("s3://")
85
+ bucket, key = s3_location(path)
86
+ Ltr.config.s3_client.put_object(bucket: bucket, key: key, body: json)
87
+ else
88
+ FileUtils.mkdir_p(File.dirname(path))
89
+ File.write(path, json)
90
+ end
91
+ end
92
+
93
+ def read_file(path)
94
+ path.start_with?("s3://") ? read_s3(path) : read_local(path)
95
+ end
96
+
97
+ def delete_file(path)
98
+ if path.start_with?("s3://")
99
+ bucket, key = s3_location(path)
100
+ Ltr.config.s3_client.delete_object(bucket: bucket, key: key)
101
+ elsif File.exist?(path)
102
+ File.delete(path)
103
+ end
104
+ end
105
+
106
+ def read_s3(path)
107
+ bucket, key = s3_location(path)
108
+ Ltr.config.s3_client.get_object(bucket: bucket, key: key).body.read
109
+ rescue => error
110
+ raise unless defined?(Aws::S3::Errors::NoSuchKey) && error.is_a?(Aws::S3::Errors::NoSuchKey)
111
+
112
+ nil
113
+ end
114
+
115
+ def read_local(path)
116
+ File.exist?(path) ? File.read(path) : nil
117
+ end
118
+
119
+ def s3_location(path)
120
+ path.delete_prefix("s3://").split("/", 2)
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,11 @@
1
+ # `lib/ltr/inference`
2
+
3
+ Runtime reranking within the `Ltr::Inference` namespace. A dispatcher selects the backend based on config, routing reranking requests to either an in-process local XGBoost model or a deployed SageMaker endpoint.
4
+
5
+ ## Files
6
+
7
+ | File | Purpose |
8
+ |---|---|
9
+ | `base.rb` | Entry point dispatcher that routes to the local reranker when `deploy.local` is enabled, otherwise to the SageMaker client. |
10
+ | `local_reranker.rb` | Reranks items in-process using a locally persisted XGBoost model, cached per path behind a mutex, with the steps, one-hot column names and feature store saved in the model file. It follows the same serving rules as `inference.py`, including clamping an infinite or too large value to the float32 range. |
11
+ | `sagemaker_client.rb` | Reranks items by invoking a deployed SageMaker endpoint with the serialized payload and parsing the response. `config` may be `nil` when a custom endpoint is passed; the client then uses the default 0.5s open and read timeouts. |
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Sends an inference request to the local or SageMaker backend.
4
+
5
+ class Ltr::Inference::Base
6
+ extend Ltr::Callable
7
+
8
+ LOCAL_BACKEND = "local"
9
+ SAGEMAKER_BACKEND = "sagemaker"
10
+
11
+ # `options` may hold `:custom_model_path` for the local backend or `:custom_model_endpoint` for SageMaker.
12
+ def initialize(payload, config, backend_type = nil, **options)
13
+ @payload = payload
14
+ @config = config
15
+ @backend_type = backend_type
16
+ @options = options
17
+ end
18
+
19
+ # Sends the payload to the chosen backend and returns its response.
20
+ # Without a backend type it uses local when `deploy.local` is `true` and SageMaker if not.
21
+ # Raises `ArgumentError` for any other backend type.
22
+ def call
23
+ case backend_type
24
+ when LOCAL_BACKEND
25
+ call_local_backend
26
+ when SAGEMAKER_BACKEND
27
+ call_sagemaker_backend
28
+ else
29
+ raise ArgumentError, "Unknown backend type: #{backend_type}. Must be '#{LOCAL_BACKEND}' or '#{SAGEMAKER_BACKEND}'"
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :payload, :config, :options
36
+
37
+ def backend_type
38
+ return @backend_type if @backend_type
39
+
40
+ config.local_deploy_enabled? ? LOCAL_BACKEND : SAGEMAKER_BACKEND
41
+ end
42
+
43
+ def call_local_backend
44
+ custom_model_path = options[:custom_model_path]
45
+ Ltr::Inference::LocalReranker.call(payload, config, custom_model_path)
46
+ end
47
+
48
+ def call_sagemaker_backend
49
+ custom_model_endpoint = options[:custom_model_endpoint]
50
+ Ltr::Inference::SagemakerClient.call(payload, config, custom_model_endpoint)
51
+ end
52
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reranks items with a locally saved XGBoost model.
4
+
5
+ class Ltr::Inference::LocalReranker
6
+ extend Ltr::Callable
7
+
8
+ ModelAssets = Struct.new(:model, :feature_transforms, :one_hot_columns, :feature_store)
9
+
10
+ class << self
11
+ # Clears the cached models.
12
+ def reset!
13
+ models_mutex.synchronize { models.clear }
14
+ end
15
+
16
+ # Returns the cached `ModelAssets` for `path`. It loads them on first use and keeps them until `reset!`.
17
+ def model_fn(path)
18
+ models_mutex.synchronize do
19
+ models[path] ||= begin
20
+ booster = XGBoost::Booster.new(model_file: path)
21
+ raise Ltr::ConfigurationError, "#{path} has no feature names. Train it again." if booster.feature_names.blank?
22
+
23
+ ModelAssets.new(
24
+ booster,
25
+ Ltr::Features::TransformStore.read_model_steps(booster),
26
+ Ltr::Features::TransformStore.read_model_one_hot_columns(booster).to_set,
27
+ Ltr::Features::TransformStore.read_model_feature_store(booster)
28
+ )
29
+ end
30
+ end
31
+ end
32
+
33
+ # Predictions share the lock because one cached booster serves every thread.
34
+ def predict(model, dmatrix)
35
+ models_mutex.synchronize { model.predict(dmatrix) }
36
+ end
37
+
38
+ private
39
+
40
+ def models
41
+ @models ||= {}
42
+ end
43
+
44
+ def models_mutex
45
+ @models_mutex ||= Mutex.new
46
+ end
47
+ end
48
+
49
+ def initialize(items, config, custom_model_path = nil)
50
+ @items = items
51
+ @config = config
52
+ @custom_model_path = custom_model_path
53
+ end
54
+
55
+ # Scores the items with the local model and returns a hash with `"items"` and `"took_seconds"`.
56
+ # `"items"` holds `{ "item", "score" }` entries, best first. Equal scores keep the request order. An empty request returns empty `"items"`.
57
+ # It builds the rank features first. Then it runs each request value through the transform steps stored in the model file.
58
+ # A feature the request leaves out or sends as `nil` or `NaN` is read from the model's feature store by item id as a string. A stored value is not transformed again.
59
+ # A one-hot column that the model file lists and neither the request nor the store has counts as a raw 0.
60
+ # Any other missing value stays `nil`.
61
+ # An infinite value or one past the float32 range is clamped to plus or minus `Ltr::Features::Float32Range::FLOAT32_MAX`, both when it is read and after the transform steps, and is still scored.
62
+ # A numeric string in a field the model uses becomes a float. Text in a field the model does not use is ignored.
63
+ # `"took_seconds"` holds the run time after the model is loaded.
64
+ # Raises `ArgumentError` for items that are not an array, for a non-numeric string in a field the model uses, and for a boolean in any field.
65
+ # Raises `Ltr::ConfigurationError` when there is no custom model path and no `deploy.local` with `deploy.local_path`, and when the model file has no feature names.
66
+ def call
67
+ checked_items = input_fn
68
+ validate_local_deploy!
69
+ predict_fn(checked_items, self.class.model_fn(model_path))
70
+ end
71
+
72
+ private
73
+
74
+ attr_reader :items, :config, :custom_model_path
75
+
76
+ def input_fn
77
+ raise ArgumentError, "Items must be an Array" unless items.is_a?(Array)
78
+
79
+ items.map do |item|
80
+ item = item.transform_keys(&:to_s)
81
+ (item["fields"] || []).map! { |field| field.transform_keys(&:to_s) }.each do |field|
82
+ raise ArgumentError, "Field #{field["name"]} of item #{item["id"]} is a boolean. Send a number." if [true, false].include?(field["value"])
83
+ end
84
+ item
85
+ end
86
+ end
87
+
88
+ def validate_local_deploy!
89
+ return if custom_model_path.present?
90
+ return if config.local_deploy_enabled? && config.local_deploy_path.present?
91
+
92
+ raise Ltr::ConfigurationError,
93
+ "Local inference requires deploy.local=true and deploy.local_path, or an explicit custom model path"
94
+ end
95
+
96
+ def predict_fn(items, assets)
97
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
98
+ return output_fn([], [], started) if items.empty?
99
+
100
+ names = assets.model.feature_names
101
+ Ltr::Features::FeatureEngineering.engineer_features_for_items(items, names)
102
+ rows, ids = to_feature_matrix(items, names, assets)
103
+ scores = self.class.predict(assets.model, XGBoost::DMatrix.new(rows))
104
+ output_fn(ids, scores, started)
105
+ end
106
+
107
+ def to_feature_matrix(items, names, assets)
108
+ rows = items.map do |item|
109
+ field_dict = build_field_dictionary(item)
110
+ names.map { |name| feature_value(name, field_dict[name], item["id"].to_s, assets) }
111
+ end
112
+
113
+ [rows, items.map { |item| item["id"] }]
114
+ end
115
+
116
+ def feature_value(name, value, item_id, assets)
117
+ steps = assets.feature_transforms
118
+ value = Ltr::Features::TransformSteps.apply(steps, name, request_number(value))
119
+ value = assets.feature_store.dig(name, item_id) if value.nil?
120
+ value = Ltr::Features::TransformSteps.apply(steps, name, 0.0) if value.nil? && assets.one_hot_columns.include?(name)
121
+ Ltr::Features::Float32Range.clamp(value)
122
+ end
123
+
124
+ def request_number(value)
125
+ return nil if value.nil?
126
+
127
+ number = Float(value)
128
+ number.nan? ? nil : Ltr::Features::Float32Range.clamp(number)
129
+ end
130
+
131
+ def build_field_dictionary(item)
132
+ (item["fields"] || []).to_h { |field| [field["name"], field["value"]] }
133
+ end
134
+
135
+ def output_fn(ids, scores, started)
136
+ scored_items = ids.zip(scores).map { |id, score| { "item" => id.to_s, "score" => score.to_f } }
137
+
138
+ {
139
+ "items" => scored_items.sort_by.with_index { |item, index| [-item["score"], index] },
140
+ "took_seconds" => Process.clock_gettime(Process::CLOCK_MONOTONIC) - started,
141
+ }
142
+ end
143
+
144
+ def model_path
145
+ custom_model_path || config.local_deploy_path
146
+ end
147
+ end