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,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Finds the display position of each document in a query result.
4
+
5
+ module Ltr::DatasetAggregation::DisplayPositions
6
+ class << self
7
+ # Returns a hash of document ID to display position, starting at 1.
8
+ # Only documents that are in the hit IDs and have a non-empty score hash are included.
9
+ # Raises `Ltr::InvalidDatasetError` if `query_attributes` or its `scores` is present and not a hash.
10
+ def for(query, hit_ids_field:, query_id_field:)
11
+ hit_ids = query[hit_ids_field]
12
+
13
+ # Positions start at 1. A document listed twice keeps its first position.
14
+ positions = hit_ids.each_with_index.with_object({}) do |(doc_id, index), acc|
15
+ acc[doc_id.to_s] ||= index + 1
16
+ end
17
+
18
+ scores_by_doc = Ltr::DatasetAggregation::UbiQueryFields.scores_by_doc(query, query_id_field: query_id_field) || {}
19
+ scores_by_doc.each_with_object({}) do |(doc_id, scores), result|
20
+ position = positions[doc_id.to_s]
21
+ result[doc_id] = position if position && scores.is_a?(Hash) && !scores.empty?
22
+ end
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ltr::DatasetAggregation::DroppedEvents
4
+ class << self
5
+ # Returns the event's `event_attributes.<doc_id_field>` value, or nil when it is blank.
6
+ def doc_id(event, doc_id_field)
7
+ event.dig("event_attributes", doc_id_field).presence
8
+ end
9
+
10
+ # Returns true when the event has no `event_attributes.<doc_id_field>` value.
11
+ def doc_id_missing?(event, doc_id_field)
12
+ doc_id(event, doc_id_field).nil?
13
+ end
14
+
15
+ # Logs how many events were dropped because their query is not in the query set, for example when a custom query filter removed the query. Logs nothing for zero.
16
+ def report_orphan_events(logger, count)
17
+ logger.info("Dropped #{count} event(s) whose query is not in the query set") if count.positive?
18
+ end
19
+
20
+ # Raises `ArgumentError` when `total` events came in and all of them lack the document ID, which means `doc_id_field` is wrong.
21
+ def report_missing_doc_id(total, without_doc_id, doc_id_field)
22
+ return if total.zero? || without_doc_id < total
23
+
24
+ raise ArgumentError,
25
+ "None of the #{total} events has `event_attributes.#{doc_id_field}`. " \
26
+ "If your events store the document id under another field, set `dataset_builder.doc_id_field`."
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,18 @@
1
+ # `lib/ltr/dataset_aggregation/labels`
2
+
3
+ Label transformers that `Ltr::DatasetAggregation::DatasetFinalizer` uses to turn each row's `:raw_label` into the `:label` the model trains on. The `label_transformer` config entry picks the class. Every class here is in the `Ltr::DatasetAggregation::` namespace.
4
+
5
+ [Label transformers](../../../../docs/label-transformers.md) and [Labels from behavior](../../../../docs/labels-from-behavior.md) explain the labels.
6
+
7
+ ## Files
8
+
9
+ | File | Purpose |
10
+ |---|---|
11
+ | `label_transformer.rb` | Base class that checks for a non-empty `Ltr::Data::RowStore` with a `:raw_label` column. It provides helpers to read raw labels and write final labels. `.resolve` looks up the configured transformer class and uses `IdentityLabelTransformer` for a blank name. |
12
+ | `per_query_label_transformer.rb` | Base class for transformers fitted separately on each `:qid` group: requires `:qid`, groups the rows, and calls `query_labels(values)` once per query. Subclasses validate their settings in `settings_from(label_transformer)`, which `ConfigValidator` also calls at config load. |
13
+ | `identity_label_transformer.rb` | Passes raw labels through to `:label` unchanged. |
14
+ | `log_plus_one_label_transformer.rb` | Applies `log(1 + x)` to raw labels to compress heavy-tailed distributions. |
15
+ | `sqrt_label_transformer.rb` | Applies a square root to raw labels to dampen very large values (the default transformer). |
16
+ | `quantile_label_transformer.rb` | Maps positive raw labels into configured quantile buckets, producing a bounded ordinal scale. `label_quantiles_from(dataset_builder)` reads `label_quantiles` and raises `Ltr::ConfigurationError` below 3. `ConfigValidator` also calls it at config load. |
17
+ | `per_query_min_max_label_transformer.rb` | Rescales each query's raw labels to `range` (`[low, high]`, default `[0, 1]`), like scikit-learn's `MinMaxScaler(feature_range=...)`. |
18
+ | `per_query_k_means_label_transformer.rb` | Bins each query's raw labels into `groups` ordinal labels with a 1D k-means fitted per `:qid`, mirroring scikit-learn's `KBinsDiscretizer(strategy="kmeans")`. |
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Uses the raw label as the final label with no change.
4
+
5
+ class Ltr::DatasetAggregation::IdentityLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
6
+ private
7
+
8
+ def transform(aggregated_data)
9
+ set_labels(aggregated_data, pluck_column(aggregated_data, :raw_label))
10
+ end
11
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Base class for label transformers. It checks the data and sets the final label on each row.
4
+
5
+ class Ltr::DatasetAggregation::LabelTransformer
6
+ extend Ltr::Callable
7
+
8
+ IDENTITY_CLASS_NAME = "Ltr::DatasetAggregation::IdentityLabelTransformer"
9
+
10
+ # Returns the class for the `label_transformer.class` name. A blank name gives `IdentityLabelTransformer`.
11
+ # Raises `Ltr::ConfigurationError` if the name does not resolve.
12
+ def self.resolve(class_name)
13
+ class_name = IDENTITY_CLASS_NAME if class_name.blank?
14
+ class_name.safe_constantize ||
15
+ raise(Ltr::ConfigurationError, "Invalid label_transformer.class '#{class_name}': the class could not be found")
16
+ end
17
+
18
+ def initialize(aggregated_data, config:)
19
+ @aggregated_data = aggregated_data
20
+ @config = config
21
+ end
22
+
23
+ # Checks that the data is a non-empty `Ltr::Data::RowStore` with a `raw_label` column, then calls `transform`.
24
+ # Raises `ArgumentError` if a check fails.
25
+ # Subclasses define `transform`, which sets the final `label` and returns the data.
26
+ def call
27
+ validate!
28
+ transform(aggregated_data)
29
+ end
30
+
31
+ private
32
+
33
+ attr_reader :aggregated_data, :config
34
+
35
+ def validate!
36
+ raise ArgumentError, "Aggregated data must be a RowStore" unless aggregated_data.is_a?(Ltr::Data::RowStore)
37
+ raise ArgumentError, "Aggregated data cannot be empty" if aggregated_data.empty?
38
+ raise ArgumentError, "RowStore must have a :raw_label column" unless aggregated_data.keys.include?(:raw_label)
39
+ end
40
+
41
+ def transform(aggregated_data)
42
+ raise NotImplementedError, "Subclasses must implement the transform method"
43
+ end
44
+
45
+ def pluck_column(data, key)
46
+ data.pluck(key)
47
+ end
48
+
49
+ def set_labels(data, labels)
50
+ data.set_column(:label, labels)
51
+ data
52
+ end
53
+
54
+ def zero_labels(data)
55
+ set_labels(data, Array.new(data.length, 0))
56
+ end
57
+
58
+ def logger
59
+ Ltr.config.logger
60
+ end
61
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Sets each label to the natural log of the raw label plus one.
4
+
5
+ class Ltr::DatasetAggregation::LogPlusOneLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
6
+ private
7
+
8
+ def transform(aggregated_data)
9
+ labels = pluck_column(aggregated_data, :raw_label).map { |raw_label| apply_log_plus_one(raw_label) }
10
+ set_labels(aggregated_data, labels)
11
+ end
12
+
13
+ def apply_log_plus_one(raw_label)
14
+ return raw_label if raw_label.negative?
15
+
16
+ Math.log(raw_label + 1)
17
+ end
18
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Turns the raw labels in each query into graded levels with k-means clustering.
4
+
5
+ class Ltr::DatasetAggregation::PerQueryKMeansLabelTransformer < Ltr::DatasetAggregation::PerQueryLabelTransformer
6
+ DEFAULT_GROUPS = 5
7
+ DEFAULT_OFFSET = 0
8
+ MAX_ITERATIONS = 300
9
+ RELATIVE_TOLERANCE = 1e-4
10
+ MIN_BIN_WIDTH = 1e-8
11
+ PAIRWISE_BLOCK_SIZE = 128
12
+
13
+ # Returns `{ groups:, offset: }` from the `label_transformer` settings hash, or the defaults of 5 and 0.
14
+ # Raises `Ltr::ConfigurationError` unless `groups` is an integer of at least 2 and `offset` is an integer of at least 0.
15
+ def self.settings_from(label_transformer)
16
+ {
17
+ groups: setting(label_transformer, "groups", DEFAULT_GROUPS, "an integer of at least 2") { |value| value.is_a?(Integer) && value >= 2 },
18
+ offset: setting(label_transformer, "offset", DEFAULT_OFFSET, "a non-negative integer") { |value| value.is_a?(Integer) && value >= 0 },
19
+ }
20
+ end
21
+
22
+ private
23
+
24
+ def query_labels(values)
25
+ bins(values).map { |bin| bin + offset }
26
+ end
27
+
28
+ def offset
29
+ settings[:offset]
30
+ end
31
+
32
+ def bins(values)
33
+ distinct = values.uniq.sort
34
+ if distinct.length <= groups
35
+ ranks = distinct.each_with_index.to_h
36
+ return values.map { |value| ranks[value] }
37
+ end
38
+
39
+ inner_edges = bin_edges(values, distinct.first, distinct.last)[1...-1]
40
+ values.map { |value| inner_edges.bsearch_index { |edge| edge > value } || inner_edges.length }
41
+ end
42
+
43
+ def groups
44
+ settings[:groups]
45
+ end
46
+
47
+ def bin_edges(values, min, max)
48
+ centers = k_means_centers(values, min, max).sort
49
+ edges = [min, *midpoints(centers), max]
50
+ edges.each_with_index.select { |edge, index| index.zero? || edge - edges[index - 1] > MIN_BIN_WIDTH }.map(&:first)
51
+ end
52
+
53
+ def k_means_centers(values, min, max)
54
+ mean = pairwise_sum(values) / values.length
55
+ centred = values.map { |value| value - mean }
56
+ tolerance = RELATIVE_TOLERANCE * (pairwise_sum(centred.map { |value| value * value }) / centred.length)
57
+ centers = initial_centers(min, max).map { |center| center - mean }
58
+ previous_assignments = nil
59
+
60
+ MAX_ITERATIONS.times do
61
+ assignments = assign(centred, centers)
62
+ updated = update_centers(centred, assignments, centers)
63
+ shift = pairwise_sum(centers.zip(updated).map { |old, new| (new - old)**2 })
64
+ centers = updated
65
+ break if assignments == previous_assignments || shift <= tolerance
66
+
67
+ previous_assignments = assignments
68
+ end
69
+
70
+ centers.map { |center| center + mean }
71
+ end
72
+
73
+ # Copies numpy's pairwise summation so the labels match sklearn's KBinsDiscretizer bit for bit.
74
+ def pairwise_sum(values, from = 0, count = values.length)
75
+ if count < 8
76
+ values[from, count].inject(-0.0, :+)
77
+ elsif count <= PAIRWISE_BLOCK_SIZE
78
+ partials = values[from, 8]
79
+ unrolled = count - count % 8
80
+ (8...unrolled).step(8) { |start| 8.times { |lane| partials[lane] += values[from + start + lane] } }
81
+ total = ((partials[0] + partials[1]) + (partials[2] + partials[3])) + ((partials[4] + partials[5]) + (partials[6] + partials[7]))
82
+ values[from + unrolled, count - unrolled].inject(total, :+)
83
+ else
84
+ half = count / 2
85
+ half -= half % 8
86
+ pairwise_sum(values, from, half) + pairwise_sum(values, from + half, count - half)
87
+ end
88
+ end
89
+
90
+ def initial_centers(min, max)
91
+ step = (max - min) / groups
92
+ edges = (0..groups).map { |index| index * step + min }
93
+ edges[-1] = max
94
+ midpoints(edges)
95
+ end
96
+
97
+ def midpoints(values)
98
+ values.each_cons(2).map { |low, high| (low + high) * 0.5 }
99
+ end
100
+
101
+ # Squared distance minus the value's own square, which is the same for every center.
102
+ def assign(values, centers)
103
+ values.map do |value|
104
+ centers.each_index.min_by { |index| [centers[index] * centers[index] - 2 * value * centers[index], index] }
105
+ end
106
+ end
107
+
108
+ def update_centers(values, assignments, centers)
109
+ sums = Array.new(centers.length, 0.0)
110
+ counts = Array.new(centers.length, 0)
111
+ values.each_with_index do |value, index|
112
+ sums[assignments[index]] += value
113
+ counts[assignments[index]] += 1
114
+ end
115
+
116
+ reseed_empty_clusters!(values, assignments, centers, sums, counts)
117
+ average_centers(sums, counts)
118
+ end
119
+
120
+ # Each empty cluster takes the value that sits farthest from its current center.
121
+ def reseed_empty_clusters!(values, assignments, centers, sums, counts)
122
+ empty = counts.each_index.select { |cluster| counts[cluster].zero? }
123
+ return if empty.empty?
124
+
125
+ farthest = values.each_index.max_by(empty.length) { |index| [(values[index] - centers[assignments[index]])**2, index] }
126
+ empty.zip(farthest).each do |cluster, index|
127
+ sums[assignments[index]] -= values[index]
128
+ counts[assignments[index]] -= 1
129
+ sums[cluster] = values[index]
130
+ counts[cluster] = 1
131
+ end
132
+ end
133
+
134
+ def average_centers(sums, counts)
135
+ heaviest = counts.each_index.max_by { |cluster| [counts[cluster], -cluster] }
136
+ sums.each_index do |cluster|
137
+ sums[cluster] = counts[cluster].positive? ? sums[cluster] / counts[cluster] : sums[heaviest]
138
+ end
139
+ sums
140
+ end
141
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Base class for label transformers that work on one query at a time.
4
+
5
+ class Ltr::DatasetAggregation::PerQueryLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
6
+ # Returns an empty hash.
7
+ # Subclasses override it to read their settings from the `label_transformer` settings hash and raise `Ltr::ConfigurationError` on a bad value.
8
+ def self.settings_from(label_transformer)
9
+ {}
10
+ end
11
+
12
+ def self.setting(label_transformer, key, default, requirement)
13
+ value = label_transformer.fetch(key, default)
14
+ return value if yield(value)
15
+
16
+ raise Ltr::ConfigurationError, "label_transformer.#{key} must be #{requirement} (got #{value.inspect})"
17
+ end
18
+ private_class_method :setting
19
+
20
+ private
21
+
22
+ attr_reader :settings
23
+
24
+ def validate!
25
+ super
26
+ raise ArgumentError, "Aggregated data must have a :qid column" unless qid_present?
27
+
28
+ @settings = self.class.settings_from(config.label_transformer_settings)
29
+ end
30
+
31
+ def qid_present?
32
+ aggregated_data.keys.include?(:qid)
33
+ end
34
+
35
+ def transform(aggregated_data)
36
+ raw_labels = pluck_column(aggregated_data, :raw_label)
37
+ qids = pluck_column(aggregated_data, :qid)
38
+ labels = Array.new(raw_labels.length)
39
+
40
+ raw_labels.each_index.group_by { |index| qids[index] }.each_value do |indices|
41
+ query_labels(raw_labels.values_at(*indices).map(&:to_f)).each_with_index do |label, position|
42
+ labels[indices[position]] = label
43
+ end
44
+ end
45
+
46
+ set_labels(aggregated_data, labels)
47
+ end
48
+
49
+ def query_labels(values)
50
+ raise NotImplementedError, "Subclasses must implement the query_labels method"
51
+ end
52
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Scales the raw labels in each query to a configured range.
4
+
5
+ class Ltr::DatasetAggregation::PerQueryMinMaxLabelTransformer < Ltr::DatasetAggregation::PerQueryLabelTransformer
6
+ DEFAULT_RANGE = [0, 1].freeze
7
+
8
+ # Returns `{ range: [low, high] }` from the `label_transformer` settings hash, or `[0, 1]`.
9
+ # Raises `Ltr::ConfigurationError` unless the range is two numbers with `0 <= low < high`.
10
+ def self.settings_from(label_transformer)
11
+ {
12
+ range: setting(label_transformer, "range", DEFAULT_RANGE, "[low, high] with 0 <= low < high") do |value|
13
+ value.is_a?(Array) && value.length == 2 && value.all?(Numeric) && value[0] >= 0 && value[0] < value[1]
14
+ end,
15
+ }
16
+ end
17
+
18
+ private
19
+
20
+ def query_labels(values)
21
+ low, high = settings[:range]
22
+ min, max = values.minmax
23
+ return Array.new(values.length, low.to_f) if max == min
24
+
25
+ values.map { |value| low + (high - low) * (value - min) / (max - min) }
26
+ end
27
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Turns the raw labels into graded levels with quantile thresholds of the positive labels.
4
+
5
+ class Ltr::DatasetAggregation::QuantileLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
6
+ DEFAULT_LABEL_QUANTILES = 10
7
+ SAMPLES_PER_THRESHOLD = 10
8
+
9
+ MIN_LABEL_QUANTILES = 3
10
+
11
+ # Returns the `label_quantiles` setting from the `dataset_builder` settings hash, or the default when it is missing.
12
+ # Raises `Ltr::ConfigurationError` when it is not an integer of at least 3.
13
+ def self.label_quantiles_from(dataset_builder)
14
+ value = dataset_builder["label_quantiles"]
15
+ return DEFAULT_LABEL_QUANTILES if value.nil?
16
+ return value if value.is_a?(Integer) && value >= MIN_LABEL_QUANTILES
17
+
18
+ raise Ltr::ConfigurationError,
19
+ "dataset_builder.label_quantiles must be an integer of at least #{MIN_LABEL_QUANTILES} (got #{value.inspect})"
20
+ end
21
+
22
+ private
23
+
24
+ def transform(aggregated_data)
25
+ positive_label_values = get_positive_label_values(aggregated_data)
26
+ if positive_label_values.empty?
27
+ zero_labels(aggregated_data)
28
+ return aggregated_data
29
+ end
30
+
31
+ quantile_thresholds = get_quantile_thresholds(positive_label_values)
32
+ logger.info("Quantile thresholds: #{quantile_thresholds}")
33
+
34
+ apply_quantile_mapping(aggregated_data, quantile_thresholds)
35
+ end
36
+
37
+ def get_positive_label_values(data_with_labels)
38
+ pluck_column(data_with_labels, :raw_label).select { |raw_label| raw_label.to_f > 0 }.sort
39
+ end
40
+
41
+ def get_quantile_thresholds(positive_label_values)
42
+ target_quantiles = label_quantiles - 1
43
+ max_unique_values = positive_label_values.uniq.length
44
+ return positive_label_values.uniq.sort if target_quantiles >= max_unique_values
45
+
46
+ sample_size = [target_quantiles * SAMPLES_PER_THRESHOLD, positive_label_values.length].min
47
+
48
+ thresholds = (0...sample_size).map do |i|
49
+ percentile = i * (100.0 / sample_size)
50
+ index = ((percentile / 100.0) * positive_label_values.length).round
51
+ positive_label_values[index]
52
+ end.uniq
53
+
54
+ step = (thresholds.length - 1).to_f / (target_quantiles - 1)
55
+ (0...target_quantiles).map { |i| thresholds[(i * step).round] }
56
+ end
57
+
58
+ def label_quantiles
59
+ @label_quantiles ||= self.class.label_quantiles_from(config.dataset_builder)
60
+ end
61
+
62
+ def apply_quantile_mapping(data_with_labels, quantile_thresholds)
63
+ labels = pluck_column(data_with_labels, :raw_label).map do |raw_label|
64
+ if raw_label.to_f <= 0
65
+ 0
66
+ else
67
+ quantile_thresholds.count { |threshold| raw_label >= threshold }
68
+ end
69
+ end
70
+
71
+ set_labels(data_with_labels, labels)
72
+ end
73
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Sets each label to the square root of the raw label.
4
+
5
+ class Ltr::DatasetAggregation::SqrtLabelTransformer < Ltr::DatasetAggregation::LabelTransformer
6
+ private
7
+
8
+ def transform(aggregated_data)
9
+ labels = pluck_column(aggregated_data, :raw_label).map { |raw_label| apply_sqrt(raw_label) }
10
+ set_labels(aggregated_data, labels)
11
+ end
12
+
13
+ def apply_sqrt(raw_label)
14
+ return raw_label if raw_label.negative?
15
+
16
+ Math.sqrt(raw_label)
17
+ end
18
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reports the query records skipped for having no hit IDs.
4
+
5
+ module Ltr::DatasetAggregation::MissingHitIds
6
+ SAMPLE_SIZE = 10
7
+
8
+ class << self
9
+ # Logs one warning with `count` and the first `SAMPLE_SIZE` of `query_ids` when `count` is positive.
10
+ # Raises `ArgumentError` after the warning if `kept` is false, which means `hit_ids_field` is wrong.
11
+ def report(logger, count, query_ids, kept:, hit_ids_field:)
12
+ return if count.zero?
13
+
14
+ logger.warn("Skipped #{count} ubi_queries record(s) with no #{hit_ids_field} (first: #{query_ids.first(SAMPLE_SIZE).join(", ")})")
15
+ return if kept
16
+
17
+ raise ArgumentError, "No ubi_queries record has #{hit_ids_field}. Check dataset_builder.hit_ids_field."
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Ranks a negative row by a hash of the seed, the query group and the doc ID.
4
+ # Both aggregation engines call it, so they keep the same negatives for the same seed.
5
+
6
+ module Ltr::DatasetAggregation::NegativeRank
7
+ class << self
8
+ # Returns a signed 64-bit integer. The negatives with the lowest ranks are kept first.
9
+ # `key_parts` are the group's values in a fixed order. Each one is compared as text, and nil stays nil.
10
+ def for(seed, key_parts, doc_id)
11
+ payload = JSON.generate([Integer(seed), *key_parts.map { |value| value&.to_s }, doc_id.to_s])
12
+ Digest::SHA256.digest(payload).unpack1("q>")
13
+ end
14
+ end
15
+ end