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.
- checksums.yaml +7 -0
- data/ARCHITECTURE.md +92 -0
- data/CHANGELOG.md +5 -0
- data/LICENSE +21 -0
- data/README.md +186 -0
- data/docs/AGENTS.md +67 -0
- data/docs/aggregation-engines.md +80 -0
- data/docs/config.md +516 -0
- data/docs/data-contracts.md +94 -0
- data/docs/data-splits.md +34 -0
- data/docs/dataset-builder-steps.md +13 -0
- data/docs/dataset-csv.md +73 -0
- data/docs/dataset-enrichers.md +62 -0
- data/docs/errors.md +33 -0
- data/docs/feature-selection.md +108 -0
- data/docs/features.md +202 -0
- data/docs/glossary.md +56 -0
- data/docs/host-integration.md +128 -0
- data/docs/host-run-pipelines.md +48 -0
- data/docs/index.md +50 -0
- data/docs/inference.md +164 -0
- data/docs/label-transformers.md +242 -0
- data/docs/labels-from-behavior.md +94 -0
- data/docs/learning-to-rank.md +119 -0
- data/docs/metrics.md +166 -0
- data/docs/model-files.md +73 -0
- data/docs/optimization.md +72 -0
- data/docs/public-api.md +67 -0
- data/docs/rake-tasks.md +82 -0
- data/docs/relevance-grades.md +80 -0
- data/docs/run-locally.md +584 -0
- data/docs/run-on-aws.md +647 -0
- data/docs/training-objective.md +110 -0
- data/docs/ubi-documents.md +75 -0
- data/docs/ubi-logging.md +125 -0
- data/lib/ltr/README.md +28 -0
- data/lib/ltr/configuration/README.md +12 -0
- data/lib/ltr/configuration/config_loader.rb +326 -0
- data/lib/ltr/configuration/config_validator.rb +476 -0
- data/lib/ltr/configuration/configuration.rb +84 -0
- data/lib/ltr/configuration/example_config.yml +182 -0
- data/lib/ltr/data/README.md +20 -0
- data/lib/ltr/data/csv/README.md +9 -0
- data/lib/ltr/data/csv/typed_columns.rb +101 -0
- data/lib/ltr/data/csv.rb +126 -0
- data/lib/ltr/data/dataframe.rb +80 -0
- data/lib/ltr/data/dataset_loader.rb +29 -0
- data/lib/ltr/data/row_store.rb +188 -0
- data/lib/ltr/data/split_cache.rb +30 -0
- data/lib/ltr/data/splits.rb +86 -0
- data/lib/ltr/dataset_aggregation/README.md +32 -0
- data/lib/ltr/dataset_aggregation/aggregated_sqlite_loader.rb +64 -0
- data/lib/ltr/dataset_aggregation/cascade_actions.rb +58 -0
- data/lib/ltr/dataset_aggregation/column_name.rb +47 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/README.md +15 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/context.rb +159 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/README.md +16 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/behavioural_feature_builder.rb +77 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/dataset_filters.rb +29 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/label_creator.rb +125 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/negative_downsampler.rb +52 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/query_aggregator.rb +163 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/split_assigner.rb +76 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/ubi_joiner.rb +137 -0
- data/lib/ltr/dataset_aggregation/dataset_builder/steps/user_query_aggregator.rb +68 -0
- data/lib/ltr/dataset_aggregation/dataset_builder.rb +82 -0
- data/lib/ltr/dataset_aggregation/dataset_enricher.rb +168 -0
- data/lib/ltr/dataset_aggregation/dataset_finalizer.rb +116 -0
- data/lib/ltr/dataset_aggregation/dataset_pipeline.rb +113 -0
- data/lib/ltr/dataset_aggregation/dataset_saver.rb +79 -0
- data/lib/ltr/dataset_aggregation/derived_features.rb +45 -0
- data/lib/ltr/dataset_aggregation/display_positions.rb +25 -0
- data/lib/ltr/dataset_aggregation/dropped_events.rb +29 -0
- data/lib/ltr/dataset_aggregation/labels/README.md +18 -0
- data/lib/ltr/dataset_aggregation/labels/identity_label_transformer.rb +11 -0
- data/lib/ltr/dataset_aggregation/labels/label_transformer.rb +61 -0
- data/lib/ltr/dataset_aggregation/labels/log_plus_one_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_k_means_label_transformer.rb +141 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_label_transformer.rb +52 -0
- data/lib/ltr/dataset_aggregation/labels/per_query_min_max_label_transformer.rb +27 -0
- data/lib/ltr/dataset_aggregation/labels/quantile_label_transformer.rb +73 -0
- data/lib/ltr/dataset_aggregation/labels/sqrt_label_transformer.rb +18 -0
- data/lib/ltr/dataset_aggregation/missing_hit_ids.rb +20 -0
- data/lib/ltr/dataset_aggregation/negative_rank.rb +15 -0
- data/lib/ltr/dataset_aggregation/sql/aggregate.sqlite.sql.erb +209 -0
- data/lib/ltr/dataset_aggregation/sqlite_aggregator.rb +167 -0
- data/lib/ltr/dataset_aggregation/sqlite_event_stager.rb +79 -0
- data/lib/ltr/dataset_aggregation/sqlite_query_stager.rb +148 -0
- data/lib/ltr/dataset_aggregation/sqlite_staging.rb +180 -0
- data/lib/ltr/dataset_aggregation/sqlite_ubi_data_loader.rb +91 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader.rb +138 -0
- data/lib/ltr/dataset_aggregation/ubi_data_loader_base.rb +147 -0
- data/lib/ltr/dataset_aggregation/ubi_query_fields.rb +54 -0
- data/lib/ltr/deploy/README.md +21 -0
- data/lib/ltr/deploy/artifacts/code/inference.py +371 -0
- data/lib/ltr/deploy/artifacts/code/requirements.txt +1 -0
- data/lib/ltr/deploy/feature_extractor.rb +94 -0
- data/lib/ltr/deploy/feature_store_deployer.rb +88 -0
- data/lib/ltr/deploy/local_deployer.rb +61 -0
- data/lib/ltr/deploy/model_packager.rb +90 -0
- data/lib/ltr/deploy/sagemaker_deployer.rb +85 -0
- data/lib/ltr/deploy/sagemaker_endpoint.rb +199 -0
- data/lib/ltr/deploy/ssm_feature_source.rb +35 -0
- data/lib/ltr/errors/README.md +16 -0
- data/lib/ltr/errors/configuration_error.rb +5 -0
- data/lib/ltr/errors/deploy_error.rb +5 -0
- data/lib/ltr/errors/error.rb +5 -0
- data/lib/ltr/errors/invalid_dataset_error.rb +5 -0
- data/lib/ltr/errors/missing_dependency_error.rb +5 -0
- data/lib/ltr/errors/sqlite_error.rb +14 -0
- data/lib/ltr/features/README.md +19 -0
- data/lib/ltr/features/encoders/README.md +10 -0
- data/lib/ltr/features/encoders/enriched_column_encoder.rb +77 -0
- data/lib/ltr/features/encoders/feature_encoder.rb +61 -0
- data/lib/ltr/features/feature_engineering.rb +194 -0
- data/lib/ltr/features/feature_transformer.rb +92 -0
- data/lib/ltr/features/float32_range.rb +20 -0
- data/lib/ltr/features/transform_steps.rb +34 -0
- data/lib/ltr/features/transform_store.rb +123 -0
- data/lib/ltr/inference/README.md +11 -0
- data/lib/ltr/inference/base.rb +52 -0
- data/lib/ltr/inference/local_reranker.rb +147 -0
- data/lib/ltr/inference/sagemaker_client.rb +62 -0
- data/lib/ltr/metrics/README.md +12 -0
- data/lib/ltr/metrics/metric_scores.rb +67 -0
- data/lib/ltr/metrics/metrics.rb +139 -0
- data/lib/ltr/optimize/README.md +25 -0
- data/lib/ltr/optimize/bayesian_optimizer.rb +212 -0
- data/lib/ltr/optimize/candidate_selector.rb +97 -0
- data/lib/ltr/optimize/cholesky_decomposition.rb +81 -0
- data/lib/ltr/optimize/expected_improvement.rb +33 -0
- data/lib/ltr/optimize/feature_selection/README.md +15 -0
- data/lib/ltr/optimize/feature_selection/greedy_backward.rb +38 -0
- data/lib/ltr/optimize/feature_selection/importance_ranked.rb +23 -0
- data/lib/ltr/optimize/feature_selection/rfe.rb +22 -0
- data/lib/ltr/optimize/feature_selection/strategy.rb +112 -0
- data/lib/ltr/optimize/feature_selection/trial.rb +39 -0
- data/lib/ltr/optimize/gaussian_process.rb +125 -0
- data/lib/ltr/optimize/optimization_dataset.rb +16 -0
- data/lib/ltr/optimize/optimize_features.rb +129 -0
- data/lib/ltr/optimize/optimize_hyperparameters.rb +165 -0
- data/lib/ltr/optimize/optimize_pipeline.rb +105 -0
- data/lib/ltr/optimize/search_space.rb +165 -0
- data/lib/ltr/optimize/update_config.rb +196 -0
- data/lib/ltr/ssm/README.md +11 -0
- data/lib/ltr/ssm/loader.rb +61 -0
- data/lib/ltr/ssm/parameter_paths.rb +19 -0
- data/lib/ltr/ssm/saver.rb +76 -0
- data/lib/ltr/support/README.md +13 -0
- data/lib/ltr/support/callable.rb +10 -0
- data/lib/ltr/support/optional_dependency.rb +31 -0
- data/lib/ltr/support/pipeline_result.rb +22 -0
- data/lib/ltr/support/pipeline_task.rb +81 -0
- data/lib/ltr/support/version.rb +7 -0
- data/lib/ltr/tasks/ltr.rake +24 -0
- data/lib/ltr/train/README.md +19 -0
- data/lib/ltr/train/deploy_gate.rb +77 -0
- data/lib/ltr/train/deploy_metric.rb +63 -0
- data/lib/ltr/train/eval_logger.rb +16 -0
- data/lib/ltr/train/evaluation_cache.rb +101 -0
- data/lib/ltr/train/modelling_pipeline.rb +82 -0
- data/lib/ltr/train/optimization_split_report.rb +54 -0
- data/lib/ltr/train/utils.rb +35 -0
- data/lib/ltr/train/xgb_evaluator.rb +96 -0
- data/lib/ltr/train/xgb_trainer.rb +154 -0
- data/lib/ltr/ubi.rb +86 -0
- data/lib/ltr.rb +61 -0
- data/scripts/seed_ubi.rb +75 -0
- metadata +346 -0
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Stores dataset rows by column and keeps all columns the same length.
|
|
4
|
+
|
|
5
|
+
# Row store that keeps one array per column.
|
|
6
|
+
class Ltr::Data::RowStore
|
|
7
|
+
# Builds a store from an array of row hashes.
|
|
8
|
+
def self.from_rows(rows)
|
|
9
|
+
store = new
|
|
10
|
+
rows.each { |row| store.append(row) }
|
|
11
|
+
store
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Builds an empty store.
|
|
15
|
+
def initialize
|
|
16
|
+
@columns = {}
|
|
17
|
+
@row_count = 0
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Adds one row hash and returns the store.
|
|
21
|
+
# Keys become symbols.
|
|
22
|
+
# Columns the row does not mention are filled with nil.
|
|
23
|
+
# A key that is new pads the earlier rows with nil.
|
|
24
|
+
def append(row)
|
|
25
|
+
row.each do |key, value|
|
|
26
|
+
column = column_for(key)
|
|
27
|
+
pad_column!(column) if column.length < @row_count
|
|
28
|
+
column << value
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
@row_count += 1
|
|
32
|
+
pad_all_columns!
|
|
33
|
+
self
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Returns the number of rows.
|
|
37
|
+
def length
|
|
38
|
+
@row_count
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# True when the store has no rows.
|
|
42
|
+
def empty?
|
|
43
|
+
@row_count.zero?
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Removes all rows and columns. It returns 0, not the store.
|
|
47
|
+
def clear
|
|
48
|
+
@columns.clear
|
|
49
|
+
@row_count = 0
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Returns the column names as symbols.
|
|
53
|
+
def keys
|
|
54
|
+
@columns.keys
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Returns the first row as a hash, or nil when the store is empty.
|
|
58
|
+
def first
|
|
59
|
+
return nil if empty?
|
|
60
|
+
|
|
61
|
+
row_at(0)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Returns all values of one column.
|
|
65
|
+
# An unknown column is created empty and returns an empty array, not nils.
|
|
66
|
+
def pluck(key)
|
|
67
|
+
column_for(key).first(@row_count)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Returns the row at the index as a hash of column name to value.
|
|
71
|
+
# An index past the last row gives a hash of nils.
|
|
72
|
+
def row_at(index)
|
|
73
|
+
@columns.transform_values { |values| values[index] }
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Yields each row as a hash.
|
|
77
|
+
# Without a block it returns an enumerator.
|
|
78
|
+
def each
|
|
79
|
+
return enum_for(:each) unless block_given?
|
|
80
|
+
|
|
81
|
+
(0...@row_count).each { |index| yield(row_at(index)) }
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# Replaces or adds a column with a copy of `values` and returns the store.
|
|
85
|
+
# Raises ArgumentError unless `values` has one entry per row.
|
|
86
|
+
def set_column(key, values)
|
|
87
|
+
raise ArgumentError, "Column length mismatch" if values.length != @row_count
|
|
88
|
+
|
|
89
|
+
@columns[key.to_sym] = values.dup
|
|
90
|
+
self
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# Replaces each value of a column with the block result and returns the store.
|
|
94
|
+
# The block gets the value and the row index.
|
|
95
|
+
# An unknown column is created, and the block gets nil for each row.
|
|
96
|
+
def update_column(key)
|
|
97
|
+
column = column_for(key)
|
|
98
|
+
pad_column!(column) if column.length < @row_count
|
|
99
|
+
|
|
100
|
+
(0...@row_count).each do |index|
|
|
101
|
+
column[index] = yield(column[index], index)
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
self
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Sets the given values on the row at the index and returns the store.
|
|
108
|
+
# Columns are created and padded with nil when needed.
|
|
109
|
+
# The index is not checked against the row count, so pass the index of an existing row.
|
|
110
|
+
def merge_row(index, features)
|
|
111
|
+
features.each do |key, value|
|
|
112
|
+
column = column_for(key)
|
|
113
|
+
pad_column!(column) if column.length <= index
|
|
114
|
+
column[index] = value
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
self
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Removes a column and returns the store.
|
|
121
|
+
def delete_column(key)
|
|
122
|
+
@columns.delete(key.to_sym)
|
|
123
|
+
self
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# Adds a column filled with the default value when it does not exist, and returns the store.
|
|
127
|
+
# A column that is too short is padded with the default.
|
|
128
|
+
def add_column(key, default: nil)
|
|
129
|
+
column = column_for(key)
|
|
130
|
+
pad_column!(column, fill: default) if column.length < @row_count
|
|
131
|
+
self
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
# Groups the rows by the block result and returns a hash of one store per key.
|
|
135
|
+
# Without a block it returns an enumerator.
|
|
136
|
+
def group_by
|
|
137
|
+
return enum_for(:group_by) unless block_given?
|
|
138
|
+
|
|
139
|
+
groups = {}
|
|
140
|
+
(0...@row_count).each do |index|
|
|
141
|
+
row = row_at(index)
|
|
142
|
+
key = yield(row)
|
|
143
|
+
(groups[key] ||= Ltr::Data::RowStore.new).append(row)
|
|
144
|
+
end
|
|
145
|
+
groups
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# Returns a new store with the rows at the given indices, in that order.
|
|
149
|
+
def select_indices(indices)
|
|
150
|
+
selected = Ltr::Data::RowStore.new
|
|
151
|
+
indices.each { |index| selected.append(row_at(index)) }
|
|
152
|
+
selected
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# Appends every row of another store and returns this store.
|
|
156
|
+
def concat(other)
|
|
157
|
+
other.each { |row| append(row) }
|
|
158
|
+
self
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
# Returns the rows as an array of hashes.
|
|
162
|
+
def to_a
|
|
163
|
+
(0...@row_count).map { |index| row_at(index) }
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
# Returns the columns as a Rover dataframe.
|
|
167
|
+
def to_dataframe
|
|
168
|
+
Rover::DataFrame.new(@columns.transform_values { |values| values.first(@row_count) })
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
private
|
|
172
|
+
|
|
173
|
+
def column_for(key)
|
|
174
|
+
@columns[key.to_sym] ||= []
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def pad_column!(column, fill: nil)
|
|
178
|
+
while column.length < @row_count
|
|
179
|
+
column << fill
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def pad_all_columns!
|
|
184
|
+
@columns.each_value do |column|
|
|
185
|
+
pad_column!(column) if column.length < @row_count
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
end
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Caches the sorted rows and query group sizes of each dataset split.
|
|
4
|
+
|
|
5
|
+
class Ltr::Data::SplitCache
|
|
6
|
+
# Takes the full dataset, with a `split` column.
|
|
7
|
+
def initialize(df)
|
|
8
|
+
@df = df
|
|
9
|
+
@sorted = {}
|
|
10
|
+
@groups = {}
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# Returns the rows of the split sorted by query id.
|
|
14
|
+
# The result is cached per split.
|
|
15
|
+
def sorted(split)
|
|
16
|
+
@sorted[split] ||= Ltr::Data::Dataframe.sorted_split(@df, split)
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Returns an array with the row count of each query id of the split, in sorted query id order.
|
|
20
|
+
# The result is cached per split.
|
|
21
|
+
def groups(split)
|
|
22
|
+
@groups[split] ||= Ltr::Data::Dataframe.group_sizes(sorted(split)[:qid].to_a)
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Builds an XGBoost matrix for the split with the given features.
|
|
26
|
+
# It reuses the cached sorted rows and group sizes. The matrix itself is built again on each call.
|
|
27
|
+
def dmatrix(split, features)
|
|
28
|
+
Ltr::Data::Dataframe.dmatrix_from_sorted(sorted(split), features, groups: groups(split))
|
|
29
|
+
end
|
|
30
|
+
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Names the train, val and test splits and resolves which split to use for each role.
|
|
4
|
+
|
|
5
|
+
# Names of the dataset splits and the rules to pick a split for each job.
|
|
6
|
+
class Ltr::Data::Splits
|
|
7
|
+
TRAIN = "train"
|
|
8
|
+
VAL = "val"
|
|
9
|
+
TEST = "test"
|
|
10
|
+
NAMES = [TRAIN, VAL, TEST].freeze
|
|
11
|
+
# The split that stands in for a role when the dataset has no rows for its configured split.
|
|
12
|
+
FALLBACK = TEST
|
|
13
|
+
|
|
14
|
+
EARLY_STOPPING_ROLE = "early stopping"
|
|
15
|
+
OPTIMIZATION_ROLE = "the optimization objective"
|
|
16
|
+
EVALUATION_ROLE = "evaluation"
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
# Returns the split names that appear in the dataframe.
|
|
20
|
+
def names_in(df)
|
|
21
|
+
df[:split].uniq.to_a
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Returns the split used for early stopping. See `resolve`.
|
|
25
|
+
def early_stopping_in(df, config)
|
|
26
|
+
resolve(df, config.early_stopping_split, role: EARLY_STOPPING_ROLE)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Returns the split used for the optimization objective. See `resolve`.
|
|
30
|
+
def optimization_in(df, config)
|
|
31
|
+
resolve(df, config.optimization_split, role: OPTIMIZATION_ROLE)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Returns the split used for evaluation. See `resolve`.
|
|
35
|
+
def evaluation_in(df, config)
|
|
36
|
+
resolve(df, config.evaluation_split, role: EVALUATION_ROLE)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Returns the configured split when the dataframe has rows for it.
|
|
40
|
+
# Otherwise it logs a warning and returns the test split.
|
|
41
|
+
# Raises InvalidDatasetError when the dataframe has no test rows either.
|
|
42
|
+
# The role is only used in the warning and error text.
|
|
43
|
+
def resolve(df, configured, role:)
|
|
44
|
+
available = names_in(df)
|
|
45
|
+
return configured if available.include?(configured)
|
|
46
|
+
|
|
47
|
+
unless available.include?(FALLBACK)
|
|
48
|
+
raise Ltr::InvalidDatasetError,
|
|
49
|
+
"Dataset has no '#{configured}' rows for #{role} and no '#{FALLBACK}' rows " \
|
|
50
|
+
"to fall back to (splits present: #{available.sort.join(", ")})"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
logger.warn(
|
|
54
|
+
"Dataset has no '#{configured}' rows, so #{role} falls back to the '#{FALLBACK}' " \
|
|
55
|
+
"split — it is shared with whatever else reads '#{FALLBACK}'. Rebuild the dataset " \
|
|
56
|
+
"with dataset_builder.split_ratios to separate them."
|
|
57
|
+
)
|
|
58
|
+
FALLBACK
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Raises ArgumentError unless `ratios` is a hash that names exactly train, val and test.
|
|
62
|
+
# Each ratio must be a number from 0 to 1, the ratios must sum to 1, and train must be above 0.
|
|
63
|
+
def validate_ratios!(ratios)
|
|
64
|
+
raise ArgumentError, "must be a hash" unless ratios.is_a?(Hash)
|
|
65
|
+
|
|
66
|
+
unless ratios.keys.map(&:to_s).sort == NAMES.sort
|
|
67
|
+
raise ArgumentError, "must name exactly #{NAMES.join(", ")} (got #{ratios.keys.sort.join(", ")})"
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
invalid = ratios.reject { |_split, ratio| ratio.is_a?(Numeric) && ratio.between?(0, 1) }
|
|
71
|
+
raise ArgumentError, "must each be numeric and between 0 and 1 (got #{invalid.inspect})" if invalid.any?
|
|
72
|
+
|
|
73
|
+
total = ratios.values.sum
|
|
74
|
+
raise ArgumentError, "must sum to 1 (got #{total})" unless (total - 1).abs < 1e-9
|
|
75
|
+
|
|
76
|
+
train_ratio = ratios.find { |split, _ratio| split.to_s == TRAIN }.last
|
|
77
|
+
raise ArgumentError, "must give #{TRAIN} a ratio greater than 0" unless train_ratio > 0
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
private
|
|
81
|
+
|
|
82
|
+
def logger
|
|
83
|
+
Ltr.config.logger
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# `lib/ltr/dataset_aggregation`
|
|
2
|
+
|
|
3
|
+
The dataset aggregation pipeline loads User Behavior Insights (UBI) queries and events. It builds a labelled training dataset and can add host-app features. It saves the CSV and its [`.serving.json` file](../../../docs/model-files.md#dataset-serving-file). `Ltr::DatasetAggregation::DatasetPipeline.call(config)` is the entry point. Set `dataset_builder.aggregation_engine` to `ruby` or `sqlite` to choose an engine.
|
|
4
|
+
|
|
5
|
+
| Path | Purpose |
|
|
6
|
+
|---|---|
|
|
7
|
+
| `dataset_builder/` | The step-by-step dataset builder — its shared `Context` value object and the ordered pipeline `steps/` that turn UBI data into a labelled `Rover::DataFrame`. |
|
|
8
|
+
| `labels/` | Label transformers that map raw weighted labels onto the final `:label` scale used for training. |
|
|
9
|
+
| `sql/` | The SQL the `sqlite` aggregation engine renders and executes. Not Ruby; not autoloaded. |
|
|
10
|
+
| `dataset_pipeline.rb` | Pipeline entry point that orchestrates loading, building, enriching, and saving the dataset and returns an `Ltr::PipelineResult`. Picks the aggregation engine. |
|
|
11
|
+
| `ubi_data_loader_base.rb` | The OpenSearch access both loaders share: client, retrying, the `search_after` sort and cursor, date-range/batch-size defaulting, custom filters, and the cascade-action filter on events, which makes `n_events` count the same events in both. |
|
|
12
|
+
| `ubi_data_loader.rb` | Loads UBI queries and the cascade-action events from OpenSearch in retrying, date-filtered batches (`ruby` engine). |
|
|
13
|
+
| `dataset_builder.rb` | Orchestrates the ordered build steps that turn raw UBI data into a labelled train/test `Rover::DataFrame` (`ruby` engine). |
|
|
14
|
+
| `dataset_finalizer.rb` | The tail both engines share: labelling, filtering, feature encoding/transformation and the train/val/test split. |
|
|
15
|
+
| `cascade_actions.rb` | Derives the cascade action set and its `*_count` column list from `conversion_rate_targets`. Excludes the default denominator (`impression_count`), which examination assigns rather than any event carrying; orders the columns as `QueryAggregator` emits them. Also builds the warning for UBI scores that share a name with a gem-written column. |
|
|
16
|
+
| `negative_rank.rb` | `NegativeRank.for` hashes the seed, a query group's key and a doc id into the rank that picks which negatives to keep under `negative_downsample_ratio`. The `ruby` engine calls it, and the `sqlite` engine registers it as `ltr_negative_rank`. |
|
|
17
|
+
| `display_positions.rb` | Maps each scored doc to its 1-based position in the query's hit ids field, the order the page showed. Both engines use it. They call `UbiQueryFields.hit_ids?` first and skip a record without hit ids. |
|
|
18
|
+
| `missing_hit_ids.rb` | `report`, the one place that warns with the count and first 10 query IDs of the records skipped for having no hit IDs, and raises `ArgumentError` when no record was kept. Both engines call it. |
|
|
19
|
+
| `dropped_events.rb` | `doc_id` reads an event's doc id and treats a blank value as missing. `doc_id_missing?` uses it. `report_missing_doc_id` raises `ArgumentError` when every cascade-action event lacks it. `report_orphan_events` logs how many events were dropped because their query is not in the query set. Both engines call them. |
|
|
20
|
+
| `derived_features.rb` | `query_length_tokens`, `scalar_scores` (the scores that are a number, text or a boolean, where `true` becomes 1 and `false` becomes 0, which drops `nil`, hashes and arrays), and `bm25_fields_matched` — distinct bm25 field families with a positive score, the family being the first underscore-delimited segment after the prefix, so `bm25_name_exact` and `bm25_name_stemmed` count once between them. Computed identically by both engines. |
|
|
21
|
+
| `sqlite_staging.rb` | The `sqlite` engine's scratch database: run directory, connection, pragmas, staging schema, failure diagnostics, cleanup. |
|
|
22
|
+
| `sqlite_ubi_data_loader.rb` | Streams UBI events and queries from OpenSearch straight into the staging database. |
|
|
23
|
+
| `sqlite_event_stager.rb` | Pages cascade-action events into `staged_events` and collects their `query_id`s. |
|
|
24
|
+
| `sqlite_query_stager.rb` | Pages the queries for those ids into `staged_queries`, guarding against repeated `query_id`s. |
|
|
25
|
+
| `ubi_query_fields.rb` | `scores_by_doc`, the one read of a query's `scores` hash, and `qid_field_value`, which returns an additional qid field as text for the qid key. It reads the value through `extract_field_value`, the one lookup of that field. Both engines call `scores_by_doc` and `qid_field_value`. |
|
|
26
|
+
| `sqlite_aggregator.rb` | Renders and executes `sql/aggregate.sqlite.sql.erb` statement by statement. |
|
|
27
|
+
| `aggregated_sqlite_loader.rb` | Streams the aggregate out of the staging database into an `Ltr::Data::RowStore`. |
|
|
28
|
+
| `column_name.rb` | Checks config-derived column names (`ConfigValidator#validate_aggregation!` calls it) and quotes columns and path literals. |
|
|
29
|
+
| `dataset_enricher.rb` | Base class for host-app subclasses that left-join features onto the dataset by `dataset_builder.doc_id_field`. Keeps text columns as strings for the pipeline to one-hot encode. |
|
|
30
|
+
| `dataset_saver.rb` | Persists the finished dataset as gzipped CSV, locally or to S3, based on the configured path. |
|
|
31
|
+
|
|
32
|
+
[Aggregation engines](../../../docs/aggregation-engines.md) explains how to choose an engine.
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Reads the aggregated rows from the SQLite staging database into a row store.
|
|
4
|
+
|
|
5
|
+
class Ltr::DatasetAggregation::AggregatedSqliteLoader
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(staging, read_sql, context)
|
|
9
|
+
@staging = staging
|
|
10
|
+
@read_sql = read_sql
|
|
11
|
+
@context = context
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Runs the read SQL and returns the aggregated rows in a `Ltr::Data::RowStore`.
|
|
15
|
+
# A score named like a column the gem writes is left out.
|
|
16
|
+
# Raises `KeyError` if the read SQL has no column for one of the action counts.
|
|
17
|
+
def call
|
|
18
|
+
store = Ltr::Data::RowStore.new
|
|
19
|
+
statement = staging.db.prepare(read_sql)
|
|
20
|
+
|
|
21
|
+
begin
|
|
22
|
+
statement.execute.each { |row| store.append(build_row(row)) }
|
|
23
|
+
ensure
|
|
24
|
+
statement.close
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
logger.info("Loaded #{store.length} aggregated rows with #{store.keys.length} columns")
|
|
28
|
+
store
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
attr_reader :staging, :read_sql, :context
|
|
34
|
+
|
|
35
|
+
def build_row(row)
|
|
36
|
+
user_query = row["user_query"]
|
|
37
|
+
scores = parse_scores(row["scores_json"])
|
|
38
|
+
|
|
39
|
+
result = {
|
|
40
|
+
:qid => row["qid"],
|
|
41
|
+
:user_query => user_query,
|
|
42
|
+
context.doc_id_field.to_sym => row["doc_id"],
|
|
43
|
+
:query_length_tokens => Ltr::DatasetAggregation::DerivedFeatures.query_length_tokens(user_query),
|
|
44
|
+
:original_position => row["original_position"],
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
context.count_columns.each { |column| result[column] = row.fetch(column.to_s) }
|
|
48
|
+
kept = scores.reject { |name, _| context.reserved_feature?(name) }
|
|
49
|
+
result.merge(Ltr::DatasetAggregation::DerivedFeatures.score_columns(kept))
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def parse_scores(scores_json)
|
|
53
|
+
return {} if scores_json.blank?
|
|
54
|
+
|
|
55
|
+
parsed = JSON.parse(scores_json)
|
|
56
|
+
return {} unless parsed.is_a?(Hash)
|
|
57
|
+
|
|
58
|
+
parsed
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def logger
|
|
62
|
+
Ltr.config.logger
|
|
63
|
+
end
|
|
64
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Finds which action count columns the conversion rate targets need.
|
|
4
|
+
|
|
5
|
+
module Ltr::DatasetAggregation::CascadeActions
|
|
6
|
+
class << self
|
|
7
|
+
# Returns the action names (without `_count`) used by the numerators and denominators of the rate targets.
|
|
8
|
+
# The impression action is left out.
|
|
9
|
+
def for(rate_targets)
|
|
10
|
+
columns = rate_targets.flat_map { |rate| [rate["numerator"], rate["denominator"]] }.compact
|
|
11
|
+
columns.map { |column| strip_count_suffix(column) }.uniq - [default_action]
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
# Returns the default count column followed by one `<action>_count` column per action.
|
|
15
|
+
def count_columns(actions)
|
|
16
|
+
[default_denominator] + actions.map { |action| :"#{action}_count" }
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
# Returns `"impression"`, the action behind the default `impression_count` column.
|
|
20
|
+
def default_action
|
|
21
|
+
strip_count_suffix(default_denominator)
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# Returns one warning per numerator or denominator column whose action is not in `present_actions`.
|
|
25
|
+
# The impression action is never reported.
|
|
26
|
+
def absent_column_warnings(rate_targets, present_actions)
|
|
27
|
+
rate_targets.flat_map do |rate|
|
|
28
|
+
[rate["numerator"], rate["denominator"]].compact.filter_map do |column|
|
|
29
|
+
action = strip_count_suffix(column)
|
|
30
|
+
next if action == default_action || present_actions.include?(action)
|
|
31
|
+
|
|
32
|
+
missing_column_warning(rate["name"], column)
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Returns the warning for a rate target column the dataset does not have.
|
|
38
|
+
def missing_column_warning(rate_name, column)
|
|
39
|
+
"conversion_rate_targets['#{rate_name}']: column '#{column}' not found, defaulting to 0"
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Returns the warning for UBI scores that the gem left out because their names are columns it writes itself.
|
|
43
|
+
def shadowed_scores_warning(names)
|
|
44
|
+
"UBI scores named #{names.map(&:to_s).sort.join(", ")} share a name with a column the gem writes itself. " \
|
|
45
|
+
"The gem keeps its own value and leaves each score out. Rename a score to use it as a feature. Do not end the new name in _count."
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
def default_denominator
|
|
51
|
+
Ltr::DatasetAggregation::DatasetBuilder::LabelCreator::DEFAULT_DENOMINATOR
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def strip_count_suffix(column)
|
|
55
|
+
column.to_s.delete_suffix("_count")
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Checks that a name is safe to use as a SQL column and quotes SQL columns and literals.
|
|
4
|
+
|
|
5
|
+
module Ltr::DatasetAggregation::ColumnName
|
|
6
|
+
SAFE = /\A[a-z_][a-z0-9_]*\z/
|
|
7
|
+
|
|
8
|
+
# Columns the staging tables and the aggregation SQL already use.
|
|
9
|
+
# `rn` and `positives` share a SELECT with the qid key columns.
|
|
10
|
+
# `events` is not a column. A qid field of that name is read from the event list on `ruby` and from the raw query on `sqlite`.
|
|
11
|
+
RESERVED = %w[
|
|
12
|
+
query_id user_query timestamp doc_id original_position scores_json
|
|
13
|
+
source_position first_source_position impression_count qid rowid rn positives events
|
|
14
|
+
].freeze
|
|
15
|
+
|
|
16
|
+
class << self
|
|
17
|
+
# Returns the name as a string if it is lowercase letters, digits and underscores, and does not start with a digit.
|
|
18
|
+
# Raises `Ltr::ConfigurationError` if it is not, or if it is a reserved column.
|
|
19
|
+
# A SQL keyword passes, because `quote_column` quotes every config-derived column in the SQL.
|
|
20
|
+
# `kind` names the setting in the error message.
|
|
21
|
+
def validate!(name, kind)
|
|
22
|
+
identifier = name.to_s
|
|
23
|
+
|
|
24
|
+
unless SAFE.match?(identifier)
|
|
25
|
+
raise Ltr::ConfigurationError,
|
|
26
|
+
"#{kind} '#{identifier}' is not a usable column name (expected #{SAFE.inspect})"
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
if RESERVED.include?(identifier)
|
|
30
|
+
raise Ltr::ConfigurationError,
|
|
31
|
+
"#{kind} '#{identifier}' collides with a reserved column (#{RESERVED.join(", ")})"
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
identifier
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Returns the name as a double-quoted SQL identifier, with each double quote doubled.
|
|
38
|
+
def quote_column(name)
|
|
39
|
+
"\"#{name.to_s.gsub('"', '""')}\""
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Returns the value as a single-quoted SQL string, with each single quote doubled.
|
|
43
|
+
def quote_literal(value)
|
|
44
|
+
"'#{value.to_s.gsub("'", "''")}'"
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
end
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# `lib/ltr/dataset_aggregation/dataset_builder`
|
|
2
|
+
|
|
3
|
+
The internals of `Ltr::DatasetAggregation::DatasetBuilder`: the shared `Context` value object that carries configuration and mutable state between build steps, and the ordered `steps/` that transform raw UBI data into a labelled train/test dataset. Everything here lives in the `Ltr::DatasetAggregation::DatasetBuilder::` namespace.
|
|
4
|
+
|
|
5
|
+
## Subfolders
|
|
6
|
+
|
|
7
|
+
| Folder | Purpose |
|
|
8
|
+
|---|---|
|
|
9
|
+
| `steps/` | The ordered pipeline step classes that clean, aggregate, label, filter, and split the data. |
|
|
10
|
+
|
|
11
|
+
## Files
|
|
12
|
+
|
|
13
|
+
| File | Purpose |
|
|
14
|
+
|---|---|
|
|
15
|
+
| `context.rb` | Value object holding configuration (id fields, split ratio, seed, etc.) and mutable state such as accumulated feature names, shared across every build step. |
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
class Ltr::DatasetAggregation::DatasetBuilder
|
|
4
|
+
# Holds the settings and shared helpers that the dataset builder steps read.
|
|
5
|
+
class Context
|
|
6
|
+
DEFAULT_SPLIT_RATIOS = {
|
|
7
|
+
Ltr::Data::Splits::TRAIN => 0.7,
|
|
8
|
+
Ltr::Data::Splits::VAL => 0.15,
|
|
9
|
+
Ltr::Data::Splits::TEST => 0.15,
|
|
10
|
+
}.freeze
|
|
11
|
+
DEFAULT_MIN_DOCUMENTS_PER_QUERY = 3
|
|
12
|
+
GEM_OWNED_COLUMNS = [:qid, :user_query, :timestamp, :original_position, :query_length_tokens, :bm25_fields_matched].freeze
|
|
13
|
+
|
|
14
|
+
# Builds a context from the config.
|
|
15
|
+
# A non-nil argument wins over the config.
|
|
16
|
+
# Missing settings use the defaults.
|
|
17
|
+
def self.build(config, query_id_field: nil, doc_id_field: nil,
|
|
18
|
+
should_shuffle_data: nil, debug_mode: nil)
|
|
19
|
+
dataset_builder = config.dataset_builder
|
|
20
|
+
conversion_rate_targets = dataset_builder["conversion_rate_targets"] || []
|
|
21
|
+
|
|
22
|
+
new(
|
|
23
|
+
config,
|
|
24
|
+
query_id_field: query_id_field || config.query_id_field,
|
|
25
|
+
doc_id_field: doc_id_field || config.doc_id_field,
|
|
26
|
+
hit_ids_field: config.hit_ids_field,
|
|
27
|
+
split_ratios: resolve_split_ratios(dataset_builder),
|
|
28
|
+
should_shuffle_data: should_shuffle_data.nil? ? (dataset_builder.dig("should_shuffle_data") != false) : should_shuffle_data,
|
|
29
|
+
random_seed: config.seed,
|
|
30
|
+
additional_qid_fields: dataset_builder["additional_qid_fields"] || [],
|
|
31
|
+
conversion_rate_targets: conversion_rate_targets,
|
|
32
|
+
cascade_actions: Ltr::DatasetAggregation::CascadeActions.for(conversion_rate_targets),
|
|
33
|
+
min_documents_per_query: dataset_builder["min_documents_per_query"] || DEFAULT_MIN_DOCUMENTS_PER_QUERY,
|
|
34
|
+
cascade_cutoff: dataset_builder.dig("cascade_cutoff") != false,
|
|
35
|
+
negative_downsample_ratio: dataset_builder.dig("negative_downsample_ratio"),
|
|
36
|
+
debug_mode: debug_mode.nil? ? config.debug_mode? : debug_mode
|
|
37
|
+
)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Returns the `split_ratios` from the config if it is set, or the defaults.
|
|
41
|
+
def self.resolve_split_ratios(dataset_builder)
|
|
42
|
+
configured = dataset_builder.dig("split_ratios")
|
|
43
|
+
configured ? split_ratios_from_config(configured) : DEFAULT_SPLIT_RATIOS
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Returns the configured split ratios with string keys.
|
|
47
|
+
# Raises `ArgumentError` if they fail `Ltr::Data::Splits.validate_ratios!`.
|
|
48
|
+
def self.split_ratios_from_config(configured)
|
|
49
|
+
ratios = configured.transform_keys(&:to_s)
|
|
50
|
+
Ltr::Data::Splits.validate_ratios!(ratios)
|
|
51
|
+
ratios
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The config that the context was built from.
|
|
55
|
+
attr_reader :config
|
|
56
|
+
|
|
57
|
+
# The name of the query ID field in UBI records. Defaults to `"query_id"`.
|
|
58
|
+
attr_reader :query_id_field
|
|
59
|
+
|
|
60
|
+
# The name of the document ID field in UBI event attributes. Defaults to `"doc_id"`.
|
|
61
|
+
attr_reader :doc_id_field
|
|
62
|
+
|
|
63
|
+
# The name of the field in a UBI query record that lists the hit document IDs.
|
|
64
|
+
attr_reader :hit_ids_field
|
|
65
|
+
|
|
66
|
+
# Hash of `"train"`, `"val"` and `"test"` to the share of unique queries in that split.
|
|
67
|
+
attr_reader :split_ratios
|
|
68
|
+
|
|
69
|
+
# Whether `SplitAssigner` shuffles the queries before it splits them. True unless set to false.
|
|
70
|
+
attr_reader :should_shuffle_data
|
|
71
|
+
|
|
72
|
+
# The top-level `seed`. It seeds the query shuffle and the negative downsampling. Defaults to 1967.
|
|
73
|
+
attr_reader :random_seed
|
|
74
|
+
|
|
75
|
+
# The query fields, besides `user_query`, that make two queries different. Empty by default.
|
|
76
|
+
attr_reader :additional_qid_fields
|
|
77
|
+
|
|
78
|
+
# The action names from the conversion rate targets, without the impression action.
|
|
79
|
+
attr_reader :cascade_actions
|
|
80
|
+
|
|
81
|
+
# The `conversion_rate_targets` list from the config, or an empty list.
|
|
82
|
+
attr_reader :conversion_rate_targets
|
|
83
|
+
|
|
84
|
+
# Queries with fewer rows than this are dropped by `DatasetFilters`. Defaults to 3.
|
|
85
|
+
attr_reader :min_documents_per_query
|
|
86
|
+
|
|
87
|
+
# Whether to drop documents ranked below the last one with a cascade action. True unless set to false.
|
|
88
|
+
attr_reader :cascade_cutoff
|
|
89
|
+
|
|
90
|
+
# Sets how many rows with no impressions each query keeps.
|
|
91
|
+
# The cap is the query's rows with impressions times this number, rounded up.
|
|
92
|
+
# Nil keeps every row.
|
|
93
|
+
attr_reader :negative_downsample_ratio
|
|
94
|
+
|
|
95
|
+
# Whether `DatasetFinalizer` skips the behavioural features. A dataset built this way is not fit for training.
|
|
96
|
+
attr_reader :debug_mode
|
|
97
|
+
|
|
98
|
+
# The names of the feature columns. Starts with `:original_position`, `:query_length_tokens` and `:bm25_fields_matched`.
|
|
99
|
+
# `QueryAggregator` adds each feature name it sees.
|
|
100
|
+
attr_accessor :feature_names
|
|
101
|
+
|
|
102
|
+
# The group key of each `qid`: `user_query` and the `additional_qid_fields` values. `QueryAggregator` sets it.
|
|
103
|
+
attr_reader :query_keys
|
|
104
|
+
|
|
105
|
+
# The feature transform steps `DatasetFinalizer` applied. Empty until the finalizer runs.
|
|
106
|
+
attr_accessor :feature_transform_steps
|
|
107
|
+
|
|
108
|
+
# Doc id to feature name to value, for each doc with no train rows.
|
|
109
|
+
# `BehaviouralFeatureBuilder` sums these over the val and test rows and `DatasetFinalizer` transforms them. Empty until then, and in `debug_mode`.
|
|
110
|
+
attr_accessor :fallback_feature_totals
|
|
111
|
+
|
|
112
|
+
# The names of the one-hot columns `FeatureEncoder` made. Empty until the encoder runs.
|
|
113
|
+
attr_reader :one_hot_columns
|
|
114
|
+
|
|
115
|
+
def initialize(config, query_id_field:, doc_id_field:, hit_ids_field:, split_ratios:, should_shuffle_data:,
|
|
116
|
+
random_seed:, additional_qid_fields:, cascade_actions:,
|
|
117
|
+
conversion_rate_targets:, min_documents_per_query:, cascade_cutoff: true, negative_downsample_ratio: nil, debug_mode: false)
|
|
118
|
+
@config = config
|
|
119
|
+
@query_id_field = query_id_field
|
|
120
|
+
@doc_id_field = doc_id_field
|
|
121
|
+
@hit_ids_field = hit_ids_field
|
|
122
|
+
@split_ratios = split_ratios
|
|
123
|
+
@should_shuffle_data = should_shuffle_data
|
|
124
|
+
@random_seed = random_seed
|
|
125
|
+
@additional_qid_fields = additional_qid_fields
|
|
126
|
+
@cascade_actions = cascade_actions
|
|
127
|
+
@conversion_rate_targets = conversion_rate_targets
|
|
128
|
+
@min_documents_per_query = min_documents_per_query
|
|
129
|
+
@cascade_cutoff = cascade_cutoff
|
|
130
|
+
@negative_downsample_ratio = negative_downsample_ratio
|
|
131
|
+
@debug_mode = debug_mode
|
|
132
|
+
@feature_names = Set.new([:original_position, :query_length_tokens, :bm25_fields_matched])
|
|
133
|
+
@feature_transform_steps = []
|
|
134
|
+
@fallback_feature_totals = {}
|
|
135
|
+
@one_hot_columns = []
|
|
136
|
+
@query_keys = {}
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# Returns `impression_count` and the `<action>_count` column of each cascade action.
|
|
140
|
+
def count_columns
|
|
141
|
+
@count_columns ||= Ltr::DatasetAggregation::CascadeActions.count_columns(cascade_actions)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# Returns the set of column names the gem writes into a document row, which a UBI score may not use.
|
|
145
|
+
def reserved_feature_names
|
|
146
|
+
@reserved_feature_names ||= (count_columns + GEM_OWNED_COLUMNS + [doc_id_field.to_sym]).to_set
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Returns true if a UBI score with this name would shadow a column the gem writes.
|
|
150
|
+
def reserved_feature?(name)
|
|
151
|
+
reserved_feature_names.include?(name.to_sym)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# Returns the logger from the gem config.
|
|
155
|
+
def logger
|
|
156
|
+
Ltr.config.logger
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|