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,16 @@
1
+ # `lib/ltr/dataset_aggregation/dataset_builder/steps`
2
+
3
+ The ordered pipeline step classes invoked by `Ltr::DatasetAggregation::DatasetBuilder`, each taking the shared `Context` and transforming the dataset a stage further — from joining raw UBI events through aggregation, labelling, filtering, and the train/val/test split. Everything here lives in the `Ltr::DatasetAggregation::DatasetBuilder::` namespace.
4
+
5
+ ## Files
6
+
7
+ | File | Purpose |
8
+ |---|---|
9
+ | `ubi_joiner.rb` | Cleans and normalises UBI queries/events, then joins each event to its parent query. |
10
+ | `query_aggregator.rb` | Expands each query into per-document feature rows keyed by a query-group id, capturing scores, position, and action counts. Applies a per-session cascade examination: docs at or above the deepest position with a cascade action (a numerator or denominator in `conversion_rate_targets`, other than `impression`) are credited one `impression_count`; docs below that cutoff are unexamined and dropped pre-aggregation, or kept with `impression_count` 0 when `dataset_builder.cascade_cutoff` is false. |
11
+ | `user_query_aggregator.rb` | Collapses duplicate query/document rows, summing `_count` features and keeping the scores of the most recent session, preferring one that examined the doc. |
12
+ | `negative_downsampler.rb` | `ruby` engine only, when `negative_downsample_ratio` is set: keeps at most `ceil(ratio × positives)` zero-impression negatives per query group, the ones with the lowest hash rank. The rank hashes the top-level `seed`, the group key and the doc id, through `NegativeRank`. |
13
+ | `behavioural_feature_builder.rb` | Aggregates per-document behavioural counts across train-split queries and derives configured conversion-ratio features. Leaves the val and test totals of documents with no train rows in `context.fallback_feature_totals`. |
14
+ | `label_creator.rb` | Computes each row's `:raw_label` as a weighted sum of Beta-Binomial smoothed conversion rates (per `conversion_rate_targets`). |
15
+ | `dataset_filters.rb` | Removes queries below `min_documents_per_query` and renumbers the kept `qid`s from 1 with no gaps. |
16
+ | `split_assigner.rb` | Assigns train/val/test splits at the query level from `dataset_builder.split_ratios`. Returns a `Ltr::Data::RowStore` with a `split` column. Runs before `behavioural_feature_builder.rb`, which reads the split. |
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Sums the action counts for each document across the train-split queries and writes the totals to every row of that document.
5
+ class BehaviouralFeatureBuilder
6
+ def initialize(context)
7
+ @context = context
8
+ end
9
+
10
+ # Replaces the `*_count` columns of each row with the train-split totals for its document.
11
+ # Adds each `conversion_features` rate when its columns exist, and sets it for a document only when the denominator total is above 0.
12
+ # A document with no train rows gets nil for each `*_count` and each conversion feature.
13
+ # Its totals over its val and test rows go to `context.fallback_feature_totals` for the feature store. Documents with train rows get no entry there.
14
+ # The rows need a `split` column. Returns the same row store.
15
+ def call(aggregated_data)
16
+ count_features = aggregated_data.keys.select { |key| key.to_s.end_with?("_count") }
17
+ conversion_features = usable_conversion_features(count_features)
18
+ doc_ids = aggregated_data.pluck(context.doc_id_field.to_sym)
19
+ totals_by_doc, held_out_totals_by_doc = sum_counts_by_doc(aggregated_data, doc_ids, count_features)
20
+ totals_by_doc.each_value { |totals| add_conversion_features!(totals, conversion_features) }
21
+ context.fallback_feature_totals = fallback_totals_by_doc(held_out_totals_by_doc, conversion_features, totals_by_doc.keys)
22
+ merge_behavioural_features(aggregated_data, doc_ids, totals_by_doc, count_features, conversion_features.map { |feature| feature["name"].to_sym })
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :context
28
+
29
+ def usable_conversion_features(count_features)
30
+ (context.config.dataset_builder["conversion_features"] || []).select do |feature_config|
31
+ %w[denominator numerator].all? do |role|
32
+ next true if count_features.include?(feature_config[role].to_sym)
33
+
34
+ context.logger.warn("conversion_features: #{role} '#{feature_config[role]}' not found in features for '#{feature_config["name"]}'")
35
+ false
36
+ end
37
+ end
38
+ end
39
+
40
+ def sum_counts_by_doc(aggregated_data, doc_ids, count_features)
41
+ splits = aggregated_data.pluck(:split)
42
+ counts = count_features.index_with { |feature| aggregated_data.pluck(feature) }
43
+ train_totals = {}
44
+ held_out_totals = {}
45
+ doc_ids.each_index do |index|
46
+ target = (splits[index] == Ltr::Data::Splits::TRAIN) ? train_totals : held_out_totals
47
+ totals = target[doc_ids[index]] ||= count_features.index_with(0)
48
+ count_features.each { |feature| totals[feature] += counts[feature][index] || 0 }
49
+ end
50
+ [train_totals, held_out_totals]
51
+ end
52
+
53
+ def fallback_totals_by_doc(held_out_totals_by_doc, conversion_features, train_doc_ids)
54
+ fallback_totals = held_out_totals_by_doc.except(*train_doc_ids)
55
+ fallback_totals.each_value { |totals| add_conversion_features!(totals, conversion_features) }
56
+ fallback_totals.transform_values { |totals| totals.transform_keys(&:to_s) }
57
+ end
58
+
59
+ def add_conversion_features!(totals, conversion_features)
60
+ conversion_features.each do |feature_config|
61
+ denominator = totals[feature_config["denominator"].to_sym]
62
+ next unless denominator > 0
63
+
64
+ totals[feature_config["name"].to_sym] = totals[feature_config["numerator"].to_sym].to_f / denominator
65
+ end
66
+ end
67
+
68
+ def merge_behavioural_features(aggregated_data, doc_ids, totals_by_doc, count_features, conversion_feature_names)
69
+ no_train_totals = (count_features + conversion_feature_names).index_with(nil).freeze
70
+ features_by_doc = totals_by_doc.transform_values { |totals| no_train_totals.merge(totals) }
71
+ doc_ids.each_with_index do |doc_id, index|
72
+ aggregated_data.merge_row(index, features_by_doc.fetch(doc_id, no_train_totals))
73
+ end
74
+ aggregated_data
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Drops queries that have fewer documents than the configured minimum.
5
+ class DatasetFilters
6
+ def initialize(context)
7
+ @context = context
8
+ end
9
+
10
+ # Returns a new row store without the queries that have fewer rows than `min_documents_per_query`.
11
+ # The kept queries keep their relative order and take `qid`s from 1 with no gaps.
12
+ def filter_queries_below_min_documents(aggregated_data)
13
+ groups = aggregated_data.group_by { |row| row[:qid] }
14
+ kept_groups = groups.select { |_qid, rows| rows.length >= context.min_documents_per_query }
15
+ new_qid_by_qid = kept_groups.keys.sort.each.with_index(1).to_h
16
+
17
+ kept = Ltr::Data::RowStore.new
18
+ kept_groups.each_value { |rows| kept.concat(rows) }
19
+ kept.update_column(:qid) { |qid| new_qid_by_qid.fetch(qid) }
20
+
21
+ context.logger.info("Filtered queries below min_documents_per_query (#{context.min_documents_per_query}): #{aggregated_data.length} -> #{kept.length}")
22
+ kept
23
+ end
24
+
25
+ private
26
+
27
+ attr_reader :context
28
+ end
29
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Creates the raw label for each row from smoothed conversion rates.
5
+ class LabelCreator
6
+ DEFAULT_DENOMINATOR = :impression_count
7
+
8
+ def initialize(context)
9
+ @context = context
10
+ end
11
+
12
+ # Returns the rows with a `:raw_label` column, which is the weighted sum of the smoothed rate of each rate target.
13
+ # A numerator or denominator column that is missing is added with 0 and a warning.
14
+ # Raises `ArgumentError` if a numerator is bigger than its denominator, unless the rate sets `allow_invariant_violation`.
15
+ # In that case it logs a warning instead.
16
+ def call(aggregated_data)
17
+ return aggregated_data if aggregated_data.empty?
18
+
19
+ rate_targets = context.conversion_rate_targets
20
+ backfill_missing_columns!(aggregated_data, rate_targets)
21
+
22
+ rate_columns = rate_targets.to_h { |rate| [rate, pluck_rate_columns(aggregated_data, rate)] }
23
+ check_numerator_within_denominator!(rate_targets, rate_columns, aggregated_data)
24
+
25
+ priors = rate_targets.to_h { |rate| [rate, compute_prior(rate_columns[rate], rate)] }
26
+ raw_labels = (0...aggregated_data.length).map do |index|
27
+ rate_targets.sum { |rate| rate["weight"].to_f * smoothed_rate(rate_columns[rate], index, priors[rate]) }
28
+ end
29
+
30
+ aggregated_data.set_column(:raw_label, raw_labels)
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :context
36
+
37
+ def backfill_missing_columns!(aggregated_data, rate_targets)
38
+ rate_targets.each do |rate|
39
+ [numerator_key(rate), denominator_key(rate)].each do |column|
40
+ next if aggregated_data.keys.include?(column)
41
+
42
+ context.logger.warn(Ltr::DatasetAggregation::CascadeActions.missing_column_warning(rate["name"], column))
43
+ aggregated_data.add_column(column, default: 0)
44
+ end
45
+ end
46
+ end
47
+
48
+ def pluck_rate_columns(aggregated_data, rate)
49
+ [aggregated_data.pluck(numerator_key(rate)), aggregated_data.pluck(denominator_key(rate))]
50
+ end
51
+
52
+ def check_numerator_within_denominator!(rate_targets, rate_columns, aggregated_data)
53
+ rate_targets.each do |rate|
54
+ allow_violation = rate["allow_invariant_violation"]
55
+ indices = violating_indices(rate_columns[rate], stop_after_first: !allow_violation)
56
+ next if indices.empty?
57
+
58
+ if allow_violation
59
+ warn_violations(rate, indices, aggregated_data)
60
+ else
61
+ raise_violation!(rate, indices.first, rate_columns[rate], aggregated_data)
62
+ end
63
+ end
64
+ end
65
+
66
+ def violating_indices(columns, stop_after_first:)
67
+ numerators, denominators = columns
68
+
69
+ (0...numerators.length).each_with_object([]) do |index, indices|
70
+ next unless numerators[index].to_f > denominators[index].to_f
71
+
72
+ indices << index
73
+ break indices if stop_after_first
74
+ end
75
+ end
76
+
77
+ def raise_violation!(rate, index, columns, aggregated_data)
78
+ numerators, denominators = columns
79
+ raise ArgumentError,
80
+ "conversion_rate_targets['#{rate["name"]}']: numerator (#{numerator_key(rate)}=#{numerators[index]}) " \
81
+ "exceeds denominator (#{denominator_key(rate)}=#{denominators[index]}) for " \
82
+ "#{cell_description(aggregated_data, index)}. Set allow_invariant_violation: true on this rate to " \
83
+ "permit this and log a warning instead."
84
+ end
85
+
86
+ def warn_violations(rate, indices, aggregated_data)
87
+ examples = indices.first(2).map { |index| cell_description(aggregated_data, index) }.join(", ")
88
+ context.logger.warn(
89
+ "conversion_rate_targets['#{rate["name"]}']: #{indices.length} row(s) violate numerator <= denominator " \
90
+ "(e.g. #{examples}) -- allow_invariant_violation is true, proceeding"
91
+ )
92
+ end
93
+
94
+ def cell_description(aggregated_data, index)
95
+ row = aggregated_data.row_at(index)
96
+ "qid=#{row[:qid]} #{context.doc_id_field}=#{row[context.doc_id_field.to_sym]}"
97
+ end
98
+
99
+ # Beta prior centred on the overall conversion rate. `nu` is how many pseudo-observations the prior is worth.
100
+ def compute_prior(columns, rate)
101
+ numerators, denominators = columns
102
+ numerator_sum = numerators.sum(&:to_f)
103
+ denominator_sum = denominators.sum(&:to_f)
104
+ mu = denominator_sum.zero? ? 0.0 : numerator_sum / denominator_sum
105
+ nu = rate["nu"].to_f
106
+
107
+ { mu: mu, alpha: mu * nu, beta: (1 - mu) * nu }
108
+ end
109
+
110
+ def smoothed_rate(columns, index, prior)
111
+ numerators, denominators = columns
112
+ numerator_value = numerators[index].to_f
113
+ denominator_value = denominators[index].to_f
114
+ (numerator_value + prior[:alpha]) / (denominator_value + prior[:alpha] + prior[:beta])
115
+ end
116
+
117
+ def numerator_key(rate)
118
+ rate["numerator"].to_s.to_sym
119
+ end
120
+
121
+ def denominator_key(rate)
122
+ (rate["denominator"] || DEFAULT_DENOMINATOR).to_s.to_sym
123
+ end
124
+ end
125
+ end
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Drops rows with no impressions so each query keeps a capped number of negatives.
5
+ class NegativeDownsampler
6
+ def initialize(context)
7
+ @context = context
8
+ end
9
+
10
+ # Keeps at most `ceil(positive rows * negative_downsample_ratio)` rows with no impressions in each query.
11
+ # The rows to drop are picked by a hash rank, so the `ruby` and `sqlite` engines drop the same rows.
12
+ # A query with no positive rows loses all its rows with no impressions.
13
+ # Returns the kept rows in their old order.
14
+ def call(aggregated_data)
15
+ positives, negatives = positive_counts_and_negative_indices(aggregated_data)
16
+ dropped = indices_to_drop(aggregated_data, positives, negatives)
17
+
18
+ negative_count = negatives.sum { |_qid, indices| indices.length }
19
+ context.logger.info("Downsampled negatives (ratio #{context.negative_downsample_ratio}): " \
20
+ "#{negative_count} -> #{negative_count - dropped.size}")
21
+ aggregated_data.select_indices((0...aggregated_data.length).reject { |index| dropped.include?(index) })
22
+ end
23
+
24
+ private
25
+
26
+ attr_reader :context
27
+
28
+ def positive_counts_and_negative_indices(aggregated_data)
29
+ qids = aggregated_data.pluck(:qid)
30
+ impressions = aggregated_data.pluck(:impression_count)
31
+ positives = Hash.new(0)
32
+ negatives = Hash.new { |hash, qid| hash[qid] = [] }
33
+ qids.each_with_index do |qid, index|
34
+ impressions[index].to_i.zero? ? negatives[qid] << index : positives[qid] += 1
35
+ end
36
+ [positives, negatives]
37
+ end
38
+
39
+ def indices_to_drop(aggregated_data, positives, negatives)
40
+ doc_ids = aggregated_data.pluck(context.doc_id_field.to_sym)
41
+ negatives.each_with_object(Set.new) do |(qid, indices), dropped|
42
+ cap = (positives[qid] * context.negative_downsample_ratio).ceil
43
+ ranked = indices.sort_by { |index| [negative_rank(qid, doc_ids[index]), doc_ids[index].to_s] }
44
+ dropped.merge(ranked.drop(cap))
45
+ end
46
+ end
47
+
48
+ def negative_rank(qid, doc_id)
49
+ Ltr::DatasetAggregation::NegativeRank.for(context.random_seed, context.query_keys.fetch(qid), doc_id)
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Turns each query and its events into document rows with action counts and scores.
5
+ class QueryAggregator
6
+ def initialize(context)
7
+ @context = context
8
+ @shadowed_scores = Set.new
9
+ end
10
+
11
+ # Returns a row store with a row for each document at or above the deepest position that has a cascade action.
12
+ # With `cascade_cutoff` off, the documents below it are kept too, with `impression_count` 0.
13
+ # A query with no cascade action adds no rows.
14
+ # Each cascade action has a `<action>_count` column, which is 0 when no event has that action.
15
+ # Queries with the same text and extra qid fields share one `qid`.
16
+ # The `qid` numbers start at 1 and have no gaps. A query that adds no rows takes no number.
17
+ # A score named like a column the gem writes is left out, and one warning names the scores left out.
18
+ def call(queries_with_events)
19
+ qid_by_query_key = {}
20
+ displayed_rows = 0
21
+ unexamined_rows = 0
22
+
23
+ results = Ltr::Data::RowStore.new
24
+ queries_with_events.each do |query_data|
25
+ query_key = build_qid_key(query_data)
26
+ qid = qid_by_query_key.fetch(query_key, qid_by_query_key.size + 1)
27
+ doc_rows, displayed_count = build_features(query_data, qid)
28
+ if doc_rows.any?
29
+ qid_by_query_key[query_key] = qid
30
+ context.query_keys[qid] = query_key
31
+ end
32
+ displayed_rows += displayed_count
33
+ unexamined_rows += doc_rows.count { |row| row[:impression_count].zero? }
34
+ results.concat(doc_rows)
35
+ end
36
+
37
+ warn_absent_cascade_actions(results)
38
+ warn_shadowed_scores
39
+ context.cascade_actions.each { |action| results.update_column(:"#{action}_count") { |count| count || 0 } }
40
+ log_cascade_summary(displayed_rows, results.length - unexamined_rows, unexamined_rows)
41
+ results
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :context, :shadowed_scores
47
+
48
+ def warn_shadowed_scores
49
+ return if shadowed_scores.empty?
50
+
51
+ context.logger.warn(Ltr::DatasetAggregation::CascadeActions.shadowed_scores_warning(shadowed_scores))
52
+ end
53
+
54
+ def warn_absent_cascade_actions(results)
55
+ present_actions = context.cascade_actions.select { |action| results.keys.include?(:"#{action}_count") }
56
+ Ltr::DatasetAggregation::CascadeActions.absent_column_warnings(context.conversion_rate_targets, present_actions)
57
+ .each { |message| context.logger.warn(message) }
58
+ end
59
+
60
+ def build_qid_key(query_data)
61
+ key_parts = [query_data["user_query"]]
62
+ context.additional_qid_fields.each do |field|
63
+ key_parts << Ltr::DatasetAggregation::UbiQueryFields.qid_field_value(
64
+ query_data, field, query_id_field: context.query_id_field
65
+ )
66
+ end
67
+ key_parts
68
+ end
69
+
70
+ def build_features(data, qid)
71
+ events_by_doc = data["events"].group_by { |event| event[context.doc_id_field].to_s }
72
+ display_positions = Ltr::DatasetAggregation::DisplayPositions.for(
73
+ data, hit_ids_field: context.hit_ids_field, query_id_field: context.query_id_field
74
+ )
75
+ capped_counts_by_doc, cutoff_position = compute_cascade_cutoff_and_counts(display_positions, events_by_doc)
76
+ return [[], display_positions.size] if cutoff_position.zero?
77
+
78
+ scores_by_doc = Ltr::DatasetAggregation::UbiQueryFields.scores_by_doc(
79
+ data, query_id_field: context.query_id_field
80
+ ) || {}
81
+ rows = display_positions.filter_map do |doc_id, position|
82
+ examined = position <= cutoff_position
83
+ next if context.cascade_cutoff && !examined
84
+
85
+ build_doc_row(data, qid, doc_id, position, examined, capped_counts_by_doc[doc_id], scores_by_doc[doc_id])
86
+ end
87
+
88
+ [rows, display_positions.size]
89
+ end
90
+
91
+ def compute_cascade_cutoff_and_counts(display_positions, events_by_doc)
92
+ capped_counts_by_doc = {}
93
+ cutoff_position = 0
94
+
95
+ events_by_doc.each do |doc_id, doc_events|
96
+ position = display_positions[doc_id]
97
+ next unless position
98
+
99
+ capped_counts = capped_action_counts(doc_events)
100
+ capped_counts_by_doc[doc_id] = capped_counts
101
+ cutoff_position = position if position > cutoff_position && cascade_action_present?(capped_counts)
102
+ end
103
+
104
+ [capped_counts_by_doc, cutoff_position]
105
+ end
106
+
107
+ # An action repeated on one document still counts once.
108
+ def capped_action_counts(events)
109
+ events.group_by { |event| event["action_name"] }
110
+ .transform_values { 1 }
111
+ end
112
+
113
+ def cascade_action_present?(capped_counts)
114
+ context.cascade_actions.any? { |action| capped_counts[action].to_i > 0 }
115
+ end
116
+
117
+ def build_doc_row(data, qid, doc_id, position, examined, capped_counts, scores)
118
+ doc_features = create_base_doc_features(qid, data["user_query"], data["timestamp"], doc_id)
119
+ doc_features[:original_position] = position
120
+ doc_features[:impression_count] = examined ? 1 : 0
121
+ add_action_counts!(doc_features, capped_counts)
122
+ add_scores!(doc_features, scores)
123
+ doc_features
124
+ end
125
+
126
+ def create_base_doc_features(qid, user_query, timestamp, doc_id)
127
+ {
128
+ :qid => qid,
129
+ :user_query => user_query,
130
+ :timestamp => timestamp,
131
+ context.doc_id_field.to_sym => doc_id,
132
+ :query_length_tokens => Ltr::DatasetAggregation::DerivedFeatures.query_length_tokens(user_query),
133
+ }
134
+ end
135
+
136
+ def add_action_counts!(doc_features, capped_counts)
137
+ return unless capped_counts
138
+
139
+ capped_counts.each do |action_name, count|
140
+ doc_features[:"#{action_name}_count"] = count
141
+ end
142
+ end
143
+
144
+ def add_scores!(doc_features, scores)
145
+ shadowed, kept = scores.partition { |name, _| context.reserved_feature?(name) }
146
+ shadowed_scores.merge(shadowed.map { |name, _| name.to_sym })
147
+ columns = Ltr::DatasetAggregation::DerivedFeatures.score_columns(kept.to_h)
148
+ columns.each do |name, score_value|
149
+ doc_features[name] = score_value
150
+ context.feature_names << name
151
+ end
152
+ end
153
+
154
+ def log_cascade_summary(displayed_rows, examined_rows, unexamined_rows)
155
+ if context.cascade_cutoff
156
+ context.logger.info("Cascade examination: #{displayed_rows} -> #{examined_rows} rows (#{displayed_rows - examined_rows} dropped as unexamined)")
157
+ else
158
+ context.logger.info("Cascade examination: #{displayed_rows} rows, #{examined_rows} examined, " \
159
+ "#{unexamined_rows} kept with zero impressions")
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Assigns each unique query to the train, val or test split.
5
+ class SplitAssigner
6
+ def initialize(context)
7
+ @context = context
8
+ end
9
+
10
+ # Puts all rows with the same `user_query` in one split, sized by `split_ratios`.
11
+ # The queries are shuffled first if `should_shuffle_data` is set.
12
+ # The test split gets the queries that the rounded train and val counts leave.
13
+ # Returns the rows, with a `split` column, as a `Ltr::Data::RowStore`.
14
+ def call(aggregated_data)
15
+ grouped_by_query = aggregated_data.group_by { |doc_result| doc_result[:user_query] }
16
+ context.logger.info("Grouped into #{grouped_by_query.keys.length} unique queries")
17
+
18
+ query_groups = grouped_by_query.keys
19
+ shuffled_queries = context.should_shuffle_data ? shuffle_data(query_groups) : query_groups
20
+ queries_per_split = partition_queries(shuffled_queries)
21
+ log_split_sizes(queries_per_split)
22
+
23
+ combined = Ltr::Data::RowStore.new
24
+ queries_per_split.each { |split, queries| append_split_rows(combined, grouped_by_query, queries, split) }
25
+ grouped_by_query.clear
26
+
27
+ combined
28
+ end
29
+
30
+ private
31
+
32
+ attr_reader :context
33
+
34
+ def shuffle_data(data)
35
+ data.shuffle(random: Random.new(context.random_seed))
36
+ end
37
+
38
+ def partition_queries(shuffled_queries)
39
+ total = shuffled_queries.length
40
+ ratios = context.split_ratios
41
+
42
+ train_end = (total * ratios.fetch(Ltr::Data::Splits::TRAIN)).round
43
+ val_end = train_end + (total * ratios.fetch(Ltr::Data::Splits::VAL)).round
44
+
45
+ {
46
+ Ltr::Data::Splits::TRAIN => shuffled_queries[0...train_end],
47
+ Ltr::Data::Splits::VAL => shuffled_queries[train_end...val_end] || [],
48
+ Ltr::Data::Splits::TEST => shuffled_queries[val_end..] || [],
49
+ }
50
+ end
51
+
52
+ def log_split_sizes(queries_per_split)
53
+ summary = queries_per_split.map { |split, queries| "#{queries.length} #{split}" }.join(", ")
54
+ context.logger.info("Split #{summary} queries")
55
+
56
+ starved = queries_per_split.select do |split, queries|
57
+ queries.empty? && context.split_ratios.fetch(split) > 0
58
+ end
59
+ return if starved.empty?
60
+
61
+ context.logger.warn(
62
+ "Too few queries for the configured split ratios: #{starved.keys.join(", ")} got none. " \
63
+ "Anything configured to read those splits will fall back to " \
64
+ "'#{Ltr::Data::Splits::FALLBACK}' or fail."
65
+ )
66
+ end
67
+
68
+ def append_split_rows(combined, grouped_by_query, queries, split)
69
+ queries.each do |query|
70
+ grouped_by_query[query].each do |row|
71
+ combined.append(row.merge(split: split))
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ class Ltr::DatasetAggregation::DatasetBuilder
4
+ # Cleans the UBI queries and events and joins the events to their queries.
5
+ class UbiJoiner
6
+ def initialize(context)
7
+ @context = context
8
+ end
9
+
10
+ # Drops queries with a blank `user_query`, a blank query ID or no `scores`.
11
+ # Keeps the first query for each query ID. The loader returns queries newest first.
12
+ # Drops a query ID whose first query has no hit IDs.
13
+ # Drops events with no known query ID, no document ID or no action name.
14
+ # Logs how many cascade-action events with a document ID were dropped because their query ID is not among the cleaned queries.
15
+ # Raises `ArgumentError` if no query is left and some were dropped for having no hit IDs, which means `hit_ids_field` is wrong.
16
+ # Raises `ArgumentError` if no cascade-action event has a document ID, which means `doc_id_field` is wrong.
17
+ # Strips and downcases `user_query` in the query hashes it is given.
18
+ # Returns copies of the queries that have events, each with an `events` list.
19
+ def call(queries, events)
20
+ queries = clean_queries(queries)
21
+ valid_query_ids = extract_query_ids_from_queries(queries)
22
+ context.logger.info("Found #{valid_query_ids.length} valid, unique query IDs")
23
+
24
+ events = clean_events(events, valid_query_ids)
25
+ valid_query_ids.clear
26
+ queries_with_events = join_events_to_queries(queries, events)
27
+ queries.clear
28
+ events.clear
29
+ context.logger.info("Queries with events: #{queries_with_events.length}")
30
+ queries_with_events
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :context
36
+
37
+ def clean_queries(queries)
38
+ normalized = queries.map { |query| normalize_query(query) }
39
+ scored = normalized.grep(Hash)
40
+ unique = keep_first_per_query_id(scored)
41
+ cleaned, without_hit_ids = unique.partition { |query| hit_ids?(query) }
42
+ log_query_cleaning(queries.length, cleaned, without_hit_ids, normalized.count(:no_scores))
43
+ cleaned
44
+ end
45
+
46
+ def normalize_query(query)
47
+ user_query = query["user_query"]
48
+ return nil if user_query.nil?
49
+
50
+ normalized_text = user_query.strip.downcase
51
+ return nil if normalized_text.empty? || query[context.query_id_field].blank?
52
+ return :no_scores if Ltr::DatasetAggregation::UbiQueryFields.scores_by_doc(query, query_id_field: context.query_id_field).nil?
53
+
54
+ query["user_query"] = normalized_text
55
+ query
56
+ end
57
+
58
+ def hit_ids?(query)
59
+ Ltr::DatasetAggregation::UbiQueryFields.hit_ids?(query, hit_ids_field: context.hit_ids_field)
60
+ end
61
+
62
+ def log_query_cleaning(original_count, cleaned, without_hit_ids, without_scores)
63
+ context.logger.info("Query cleaning: #{original_count} -> #{cleaned.length} (#{original_count - cleaned.length} removed)")
64
+ context.logger.warn("Skipped #{without_scores} ubi_queries record(s) with no `scores`") if without_scores.positive?
65
+ missing_ids = without_hit_ids.pluck(context.query_id_field)
66
+ Ltr::DatasetAggregation::MissingHitIds.report(
67
+ context.logger, missing_ids.length, missing_ids,
68
+ kept: cleaned.any?, hit_ids_field: context.hit_ids_field
69
+ )
70
+ end
71
+
72
+ def keep_first_per_query_id(queries)
73
+ unique = queries.uniq { |query| query[context.query_id_field].to_s }
74
+ duplicates = queries.length - unique.length
75
+ context.logger.warn("Skipped #{duplicates} ubi_queries record(s) repeating an already-seen query_id; kept the first record for each") if duplicates.positive?
76
+ unique
77
+ end
78
+
79
+ def extract_query_ids_from_queries(queries)
80
+ queries.map { |query| query[context.query_id_field].to_s }.to_set
81
+ end
82
+
83
+ def clean_events(events, valid_query_ids)
84
+ original_count = events.length
85
+ cleaned_events = events.filter do |event|
86
+ event_query_id = event[context.query_id_field]
87
+ event_query_id.present? && valid_query_ids.include?(event_query_id.to_s) &&
88
+ doc_id_present?(event) && event["action_name"].present?
89
+ end
90
+ context.logger.info("Event cleaning: #{original_count} -> #{cleaned_events.length} (#{original_count - cleaned_events.length} removed)")
91
+ report_missing_doc_id(events)
92
+ report_orphan_events(events, valid_query_ids)
93
+ cleaned_events
94
+ end
95
+
96
+ def report_orphan_events(events, valid_query_ids)
97
+ orphans = events.count do |event|
98
+ event_query_id = event[context.query_id_field]
99
+ event_query_id.present? && !valid_query_ids.include?(event_query_id.to_s) &&
100
+ context.cascade_actions.include?(event["action_name"]) &&
101
+ doc_id_present?(event)
102
+ end
103
+ Ltr::DatasetAggregation::DroppedEvents.report_orphan_events(context.logger, orphans)
104
+ end
105
+
106
+ def doc_id_present?(event)
107
+ !Ltr::DatasetAggregation::DroppedEvents.doc_id_missing?(event, context.doc_id_field)
108
+ end
109
+
110
+ def report_missing_doc_id(events)
111
+ cascade_events = events.select { |event| context.cascade_actions.include?(event["action_name"]) }
112
+ without_doc_id = cascade_events.count { |event| Ltr::DatasetAggregation::DroppedEvents.doc_id_missing?(event, context.doc_id_field) }
113
+ Ltr::DatasetAggregation::DroppedEvents.report_missing_doc_id(cascade_events.length, without_doc_id, context.doc_id_field)
114
+ end
115
+
116
+ def join_events_to_queries(queries, events)
117
+ events_by_query = events.group_by { |event| event[context.query_id_field].to_s }
118
+ add_events_to_queries(queries, events_by_query)
119
+ end
120
+
121
+ def add_events_to_queries(queries, events_by_query)
122
+ queries.filter_map do |query|
123
+ associated_events = events_by_query[query[context.query_id_field].to_s] || []
124
+ next if associated_events.empty?
125
+
126
+ doc_events = associated_events.map do |event|
127
+ {
128
+ "action_name" => event["action_name"],
129
+ context.doc_id_field => Ltr::DatasetAggregation::DroppedEvents.doc_id(event, context.doc_id_field)&.to_s,
130
+ }.compact
131
+ end
132
+
133
+ query.merge("events" => doc_events)
134
+ end
135
+ end
136
+ end
137
+ end