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,182 @@
1
+ seed: 1967
2
+ model:
3
+ type: xgboost
4
+ name: ltr-model
5
+ hyperparameters:
6
+ eval_metric: ndcg@12
7
+ lambdarank_unbiased: true
8
+ ndcg_exp_gain: false
9
+ objective: rank:ndcg
10
+ n_estimators: 500
11
+ learning_rate: 0.1
12
+ max_depth: 6
13
+ lambdarank_num_pair_per_sample: 12
14
+ early_stopping_rounds: 20
15
+ verbose_eval: 10
16
+ min_child_weight: 1
17
+ subsample: 0.5
18
+ colsample_bytree: 0.6
19
+
20
+ training:
21
+ nthread: <%= Integer(ENV.fetch("LTR_NTHREAD", 4)) %>
22
+ early_stopping_split: test
23
+ modelling_dataset_path: "tmp/ltr/data/ltr_dataset.csv"
24
+ s3_region: "us-east-1"
25
+
26
+ search_time_features:
27
+ - relevancy
28
+ - bm25_name
29
+ - bm25_description
30
+
31
+ feature_engineering:
32
+ - rank
33
+ - relative_score
34
+
35
+ feature_store:
36
+ include_in_deployment: true
37
+ features:
38
+ - purchase_count
39
+ - add_to_cart_count
40
+ - view_count
41
+
42
+ evaluation:
43
+ split: test
44
+ min_relevance_percentile: 60
45
+ metrics:
46
+ - map@10
47
+ - mrr@10
48
+ - ndcg
49
+ - ndcg@5
50
+ - ndcg@12
51
+ - precision
52
+ - precision@5
53
+ - recall@5
54
+
55
+ optimization:
56
+ split: val
57
+ complexity_penalty: 0.0001
58
+ feature_selection:
59
+ strategy: greedy_backward
60
+ metric_to_optimize: ndcg@12
61
+ min_features: 4
62
+ search_time_features:
63
+ - relevancy
64
+ - bm25_name
65
+ - bm25_description
66
+ - bm25_name_simple
67
+ - bm25_brand
68
+ - bm25_dosage_format
69
+ - bm25_ingredients
70
+ - bm25_condition
71
+ feature_store_features:
72
+ - cart_conversion
73
+ - price
74
+ - purchase_conversion
75
+ - view_count
76
+ - add_to_cart_count
77
+ - purchase_count
78
+
79
+ n_init: 5
80
+ iterations: 50
81
+ bayesian_optimizer:
82
+ candidates_per_iteration: 1000
83
+ noise_variance: 0.1
84
+ kernel_lengthscale: 0.3
85
+ kernel_variance: 1.0
86
+ ei_xi: 0.5
87
+ hyperparameter_search_space:
88
+ colsample_bytree:
89
+ min: 0.5
90
+ max: 0.9
91
+ learning_rate:
92
+ min: 0.1
93
+ max: 0.3
94
+ max_depth:
95
+ min: 3
96
+ max: 10
97
+ min_child_weight:
98
+ min: 1
99
+ max: 10
100
+ subsample:
101
+ min: 0.3
102
+ max: 0.9
103
+
104
+ ubi_data_loader:
105
+ n_events: 10000
106
+ max_days_ago: 30
107
+ batch_size: 10000
108
+ opensearch:
109
+ url: <%= ENV["OPENSEARCH_URL"] %>
110
+ username: <%= ENV["OPENSEARCH_USERNAME"] %>
111
+ password: <%= ENV["OPENSEARCH_PASSWORD"] %>
112
+ index:
113
+ queries: ubi_queries
114
+ events: ubi_events
115
+
116
+ dataset_builder:
117
+ aggregation_engine: ruby
118
+ split_ratios:
119
+ train: 0.7
120
+ val: 0.15
121
+ test: 0.15
122
+ query_id_field: "query_id"
123
+ doc_id_field: "doc_id"
124
+ hit_ids_field: "query_response_hit_ids"
125
+ should_shuffle_data: true
126
+ label_quantiles: 10
127
+ min_documents_per_query: 3
128
+ conversion_features:
129
+ - name: cart_conversion
130
+ numerator: add_to_cart_count
131
+ denominator: view_count
132
+ - name: purchase_conversion
133
+ numerator: purchase_count
134
+ denominator: view_count
135
+ conversion_rate_targets:
136
+ - name: ctr
137
+ numerator: view_count
138
+ weight: 1
139
+ nu: 50
140
+ - name: atcr
141
+ numerator: add_to_cart_count
142
+ weight: 2
143
+ nu: 100
144
+ - name: cvr
145
+ numerator: purchase_count
146
+ weight: 3
147
+ nu: 150
148
+
149
+ dataset_aggregation:
150
+ staging_root:
151
+ sqlite:
152
+ cache_size_mb: 256
153
+ page_size: 8192
154
+
155
+ dataset_enricher:
156
+ # class: "Path::To::DatasetEnricher" # Comment out to disable
157
+
158
+ label_transformer:
159
+ class: "Ltr::DatasetAggregation::SqrtLabelTransformer"
160
+
161
+ deploy:
162
+ enabled: false
163
+ local: false
164
+ local_path: "tmp/ltr/models/ltr_model.ubj"
165
+ sagemaker_bucket: <%= ENV["SAGEMAKER_BUCKET"].to_json %>
166
+ execution_role: <%= ENV["SAGEMAKER_EXECUTION_ROLE"].to_json %>
167
+ instance_type: "ml.m5.large"
168
+ instance_count: 1
169
+ image_uri: null
170
+ metric: ndcg
171
+ minimum_metric_value: 0.5
172
+
173
+ inference:
174
+ sagemaker:
175
+ open_timeout: 0.5
176
+ read_timeout: 0.5
177
+
178
+ ssm:
179
+ enabled: false
180
+ all_features_param_path: "/ltr/optimization/all_features"
181
+ feature_store_features_param_path: "/ltr/optimization/feature_store_features"
182
+ hyperparameters_param_path: "/ltr/optimization/hyperparameters"
@@ -0,0 +1,20 @@
1
+ # `lib/ltr/data`
2
+
3
+ Low-level data primitives shared across the gem's pipelines. These `Ltr::Data` classes read and validate modelling datasets, provide `Rover::DataFrame` helpers for XGBoost ranking, and offer an efficient column-oriented row store used while building datasets before export.
4
+
5
+ ## Subfolders
6
+
7
+ | Folder | Purpose |
8
+ |---|---|
9
+ | `csv/` | How a dataset's columns are typed during the single parsing pass, and why the typing is not a `CSV` converter. |
10
+
11
+ ## Files
12
+
13
+ | File | Purpose |
14
+ |---|---|
15
+ | `csv.rb` | Reads modelling datasets from local disk or S3 (with gzip fallback) and standardizes `"NaN"` strings to `Float::NAN`. |
16
+ | `dataframe.rb` | DataFrame helpers for ranking: builds grouped XGBoost DMatrices, sorts/splits by query id, orders each query group by `original_position` with missing positions last, and groups predictions and labels per query. |
17
+ | `dataset_loader.rb` | Loads a dataset via `Csv`, standardizes NaNs, and validates the required ranking columns (`qid`, `label`, `split`) are present. |
18
+ | `row_store.rb` | Mutable column-oriented row store that accumulates rows during dataset building and exports to a `Rover::DataFrame` on demand. |
19
+ | `split_cache.rb` | Memoizes a split's sorted rows and query-group sizes so a run sorts each split once instead of once per reader. |
20
+ | `splits.rb` | The canonical split names (`train`/`val`/`test`) and the resolution of a configured split role against what a dataset actually carries, falling back to `test` with a warning when the dataset predates `val`; also validates that a `dataset_builder.split_ratios` hash names every split and sums to 1. |
@@ -0,0 +1,9 @@
1
+ # `lib/ltr/data/csv`
2
+
3
+ The column typing behind `Ltr::Data::Csv.read`. `Csv` does the I/O and hands records to `TypedColumns`, which decides each column's type as the file streams past and casts it once at the end.
4
+
5
+ ## Files
6
+
7
+ | File | Purpose |
8
+ |---|---|
9
+ | `typed_columns.rb` | Per-column type state for one pass over a dataset: sniffs from the first rows whether each column is numeric or text (a `text_columns:` column always stays text), appends fields into one Ruby array per column, and casts each to `Numo::Int64`, `Numo::DFloat` or an object column on `to_dataframe`. |
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Builds typed dataframe columns from CSV rows.
4
+ # It picks integer, float or object types from a sample of rows.
5
+
6
+ class Ltr::Data::Csv
7
+ # Collects CSV rows into typed columns.
8
+ # A column is an integer column, a float column or an object column.
9
+ class TypedColumns
10
+ # Plain decimals only. Float() also accepts hex (0x1A) and underscores (1_000), so those stay strings.
11
+ NUMBER = /\A[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][-+]?\d+)?\z/
12
+
13
+ # `sniffed` is the sample of records that sets each column's starting type. With an empty sample every column starts as an integer column.
14
+ # `text_columns` names columns that stay object columns even when every value is a number, such as ids with leading zeros.
15
+ def initialize(header, sniffed, text_columns: [])
16
+ @header = header
17
+ @kind = header.each_with_index.map do |name, index|
18
+ (!text_columns.include?(name) && sniffed.all? { |sniff| numeric_field?(sniff[index]) }) ? :int : :object
19
+ end
20
+ @numeric_indices = @kind.each_index.reject { |index| @kind[index] == :object }
21
+ @object_indices = @kind.each_index.select { |index| @kind[index] == :object }
22
+ @columns = Array.new(header.size) { [] }
23
+ @row = 0
24
+
25
+ sniffed.each { |record| append(record) }
26
+ end
27
+
28
+ # Adds one CSV record to the columns.
29
+ # An integer column becomes a float column when a value is empty, "NaN" or not a whole number.
30
+ # Raises InvalidDatasetError when a numeric column holds a non-numeric value.
31
+ def append(record)
32
+ @row += 1
33
+ @object_indices.each { |index| @columns[index] << record[index] }
34
+
35
+ @numeric_indices.each do |index|
36
+ value = record[index]
37
+
38
+ if missing?(value)
39
+ @kind[index] = :float
40
+ @columns[index] << Float::NAN
41
+ elsif @kind[index] == :int && number?(value) && (whole = Integer(value, 10, exception: false))
42
+ @columns[index] << whole
43
+ else
44
+ @kind[index] = :float
45
+ @columns[index] << float_field!(value, index)
46
+ end
47
+ end
48
+ end
49
+
50
+ # Builds the dataframe from the collected columns.
51
+ # Call it once, because it frees the raw column arrays.
52
+ # An integer column that does not fit in 64 bits becomes a float column.
53
+ def to_dataframe
54
+ data = {}
55
+
56
+ @header.each_with_index do |name, index|
57
+ data[name] = vector(index)
58
+ # Drop the raw array once the vector exists, so both copies are not held at once.
59
+ @columns[index] = nil
60
+ end
61
+
62
+ Rover::DataFrame.new(data)
63
+ end
64
+
65
+ private
66
+
67
+ def vector(index)
68
+ case @kind[index]
69
+ when :object then @columns[index]
70
+ when :int then integer_vector(index)
71
+ when :float then Numo::DFloat.cast(@columns[index])
72
+ end
73
+ end
74
+
75
+ def integer_vector(index)
76
+ Numo::Int64.cast(@columns[index])
77
+ rescue RangeError
78
+ Numo::DFloat.cast(@columns[index])
79
+ end
80
+
81
+ def numeric_field?(value)
82
+ missing?(value) || number?(value)
83
+ end
84
+
85
+ def number?(value)
86
+ value.strip.match?(NUMBER)
87
+ end
88
+
89
+ def missing?(value)
90
+ value.nil? || value.empty? || value == NAN_TOKEN
91
+ end
92
+
93
+ def float_field!(value, index)
94
+ return Float(value) if number?(value)
95
+
96
+ raise Ltr::InvalidDatasetError,
97
+ "Column #{@header[index].inspect} parsed as numeric from its first " \
98
+ "#{TYPE_SNIFF_ROWS} rows but row #{@row} holds #{value.inspect}"
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Reads the modelling dataset from a local or S3 CSV file into a dataframe.
4
+
5
+ class Ltr::Data::Csv
6
+ # The number of rows read first to decide whether each column is numeric or text.
7
+ TYPE_SNIFF_ROWS = 500
8
+
9
+ # The text that marks a missing value in the CSV.
10
+ NAN_TOKEN = "NaN"
11
+
12
+ class << self
13
+ # Reads the modelling dataset CSV into a dataframe.
14
+ # A path that starts with s3:// is read from S3, any other path from disk.
15
+ # It adds .gz to the path and tries that file first, then the plain file.
16
+ # Raises InvalidDatasetError when a local file or the header row is missing, or when a numeric column holds a non-numeric value.
17
+ # `training.modelling_dataset_path` must be set.
18
+ # The `doc_id_field` column always stays text, so ids such as "00123" keep their zeros.
19
+ # A missing S3 object raises Aws::S3::Errors::NoSuchKey when the role can list the bucket. Otherwise the AWS error propagates.
20
+ def read(config)
21
+ dataset_path = config.modelling_dataset_path
22
+ text_columns = [config.doc_id_field]
23
+
24
+ if s3_storage?(dataset_path)
25
+ logger.info("Reading CSV from S3: #{dataset_path}")
26
+ read_from_s3(dataset_path, text_columns)
27
+ else
28
+ logger.info("Reading CSV locally: #{dataset_path}")
29
+ read_locally(dataset_path, text_columns)
30
+ end
31
+ end
32
+
33
+ # Turns the string "NaN" into Float::NAN in the object columns.
34
+ # Changes the dataframe in place and returns it.
35
+ def standardize_nans(df)
36
+ df.keys.each do |column_name|
37
+ column = df[column_name]
38
+ next unless column.to_numo.is_a?(Numo::RObject)
39
+
40
+ column.each_with_index do |value, index|
41
+ column[index] = Float::NAN if nan?(value)
42
+ end
43
+ end
44
+
45
+ df
46
+ end
47
+
48
+ private
49
+
50
+ def s3_storage?(dataset_path)
51
+ dataset_path.start_with?("s3://")
52
+ end
53
+
54
+ def read_from_s3(dataset_path, text_columns)
55
+ s3_client = Ltr.config.s3_client
56
+ s3_path = dataset_path.delete_prefix("s3://")
57
+ s3_bucket, s3_key = s3_path.split("/", 2)
58
+
59
+ fetched_key, body = fetch_s3_object_body(s3_client, s3_bucket, s3_key)
60
+ read_from_stream(body, text_columns, compressed: fetched_key.end_with?(".gz"))
61
+ end
62
+
63
+ def fetch_s3_object_body(s3_client, bucket, key)
64
+ compressed_key = "#{key}.gz"
65
+
66
+ begin
67
+ logger.info("Attempting to fetch compressed file: #{compressed_key}")
68
+ response = s3_client.get_object(bucket: bucket, key: compressed_key)
69
+ [compressed_key, response.body]
70
+ rescue => error
71
+ raise unless defined?(Aws::S3::Errors::NoSuchKey) && error.is_a?(Aws::S3::Errors::NoSuchKey)
72
+
73
+ logger.info("Compressed file not found, falling back to: #{key}")
74
+ response = s3_client.get_object(bucket: bucket, key: key)
75
+ [key, response.body]
76
+ end
77
+ end
78
+
79
+ def read_locally(dataset_path, text_columns)
80
+ compressed_path = "#{dataset_path}.gz"
81
+
82
+ if File.exist?(compressed_path)
83
+ logger.info("Reading compressed file: #{compressed_path}")
84
+ File.open(compressed_path, "rb") { |file| read_from_stream(file, text_columns, compressed: true) }
85
+ elsif File.exist?(dataset_path)
86
+ logger.info("Reading uncompressed file: #{dataset_path}")
87
+ File.open(dataset_path, "rb") { |file| read_from_stream(file, text_columns, compressed: false) }
88
+ else
89
+ raise Ltr::InvalidDatasetError, "Dataset file not found: #{dataset_path}"
90
+ end
91
+ end
92
+
93
+ def read_from_stream(io, text_columns, compressed:)
94
+ if compressed
95
+ logger.info("Decompressing gzip stream...")
96
+ Zlib::GzipReader.wrap(io) { |gzip| parse(gzip, text_columns) }
97
+ else
98
+ parse(io, text_columns)
99
+ end
100
+ end
101
+
102
+ def parse(io, text_columns)
103
+ csv = ::CSV.new(io, skip_blanks: true)
104
+ header = csv.shift
105
+ raise Ltr::InvalidDatasetError, "Dataset has no header row" if header.nil?
106
+
107
+ sniffed = []
108
+ while sniffed.size < TYPE_SNIFF_ROWS && (record = csv.shift)
109
+ sniffed << record
110
+ end
111
+
112
+ columns = TypedColumns.new(header, sniffed, text_columns: text_columns)
113
+ csv.each { |record| columns.append(record) }
114
+
115
+ columns.to_dataframe
116
+ end
117
+
118
+ def nan?(value)
119
+ value == NAN_TOKEN
120
+ end
121
+
122
+ def logger
123
+ Ltr.config.logger
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Provides dataframe helpers that sort rows by query and build XGBoost matrices.
4
+
5
+ # Helpers for dataframes that hold ranking data.
6
+ class Ltr::Data::Dataframe
7
+ REJECTED_FEATURE_NAME_CHARACTERS = /[\[\]<]/
8
+
9
+ class << self
10
+ # Builds an XGBoost matrix from the rows of one split, sorted by query id.
11
+ # Uses the train split by default.
12
+ def dmatrix_from_dataframe(df, features, split: Ltr::Data::Splits::TRAIN)
13
+ dmatrix_from_sorted(sorted_split(df, split), features)
14
+ end
15
+
16
+ # Builds an XGBoost matrix from rows that are already sorted by query id.
17
+ # Pass groups to reuse known group sizes, otherwise they are computed from the qid column.
18
+ # Raises `ArgumentError` naming each feature with `[`, `]` or `<` in its name, because XGBoost rejects it.
19
+ def dmatrix_from_sorted(df_split, features, groups: nil)
20
+ validate_feature_names!(features)
21
+ dsplit = XGBoost::DMatrix.new(df_split[features], label: df_split[:label])
22
+ dsplit.group = groups || group_sizes(df_split[:qid].to_a)
23
+ dsplit
24
+ end
25
+
26
+ # Returns the rows of one split, sorted by the given column (qid by default).
27
+ # Ties sort by `original_position` when the split has it. XGBoost reads each row's index in its group as its position when `lambdarank_unbiased` is true.
28
+ def sorted_split(df, split_value, column: :qid)
29
+ split_df = df[df[:split] == split_value]
30
+ return sort_dataframe(split_df, column) unless split_df.include?(:original_position)
31
+
32
+ sort_dataframe(split_df, column, tie_break: split_df[:original_position].to_a.map { |position| position_key(position) })
33
+ end
34
+
35
+ # Returns the dataframe sorted by one column.
36
+ # Rows with equal values are ordered by `tie_break` when it is given, then keep their original order.
37
+ # `tie_break` holds one comparable key per row.
38
+ # It returns a new dataframe, or the same one when it is empty.
39
+ def sort_dataframe(df, column, tie_break: nil)
40
+ return df if df.empty?
41
+
42
+ values = df[column].to_a
43
+ # The index is part of the sort key because Ruby sort_by is not stable.
44
+ indices = values.each_index.sort_by { |index| [values[index], *tie_break&.at(index), index] }
45
+ columns = df.keys.index_with { |key| indices.map { |index| df[key][index] } }
46
+ Rover::DataFrame.new(columns)
47
+ end
48
+
49
+ # Returns one [preds, labels] pair per query id, in the order the ids first appear.
50
+ # The ids do not need to be sorted. Equal ids are grouped even when they are not next to each other.
51
+ def group_by_qid(qids, preds, labels)
52
+ qids.each_with_index.with_object({}) do |(qid, idx), groups|
53
+ groups[qid] ||= { preds: [], labels: [] }
54
+ groups[qid][:preds] << preds[idx]
55
+ groups[qid][:labels] << labels[idx]
56
+ end.values.map { |g| [g[:preds], g[:labels]] }
57
+ end
58
+
59
+ # Counts the rows in each run of equal query ids.
60
+ # The ids must already be sorted so that equal ids sit next to each other.
61
+ def group_sizes(qids)
62
+ qids.chunk_while { |a, b| a == b }.map(&:size)
63
+ end
64
+
65
+ private
66
+
67
+ def validate_feature_names!(features)
68
+ rejected = features.map(&:to_s).grep(REJECTED_FEATURE_NAME_CHARACTERS)
69
+ return if rejected.empty?
70
+
71
+ raise ArgumentError,
72
+ "XGBoost rejects feature names with [, ] or <. Rename or drop: #{rejected.join(", ")}. " \
73
+ "A name from an enricher text column is `<column>_<value>`, so drop the column or bucket its values."
74
+ end
75
+
76
+ def position_key(position)
77
+ (position.respond_to?(:nan?) && position.nan?) ? [1, 0] : [0, position]
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads the modelling dataset and checks that it has the required columns.
4
+
5
+ # Loads and checks the modelling dataset.
6
+ class Ltr::Data::DatasetLoader
7
+ REQUIRED_COLUMNS = [:qid, :label, :split].freeze
8
+
9
+ class << self
10
+ # Reads the dataset CSV with `Csv.read`, standardizes its NaN values and checks the required columns.
11
+ # Raises what `Csv.read` raises, and InvalidDatasetError when a required column is missing.
12
+ # Returns the dataset as a `Rover::DataFrame`.
13
+ def load(config)
14
+ df = Ltr::Data::Csv.read(config)
15
+ df = Ltr::Data::Csv.standardize_nans(df)
16
+ validate!(df)
17
+ df
18
+ end
19
+
20
+ # Raises InvalidDatasetError that names the missing columns when the dataframe lacks `qid`, `label` or `split`.
21
+ def validate!(df)
22
+ missing_columns = REQUIRED_COLUMNS.reject { |column| df.include?(column) }
23
+ return if missing_columns.empty?
24
+
25
+ raise Ltr::InvalidDatasetError,
26
+ "Missing required columns: #{missing_columns.join(", ")}. Required: #{REQUIRED_COLUMNS.join(", ")}"
27
+ end
28
+ end
29
+ end