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,82 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Runs training, evaluation and deployment from the config.
|
|
4
|
+
|
|
5
|
+
class Ltr::Train::ModellingPipeline
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config)
|
|
9
|
+
@config = config
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Loads the dataset, trains and evaluates the model, then runs the deploy gate and the local deploy.
|
|
13
|
+
# Both deploys use the same `deploy.minimum_metric_value`, but each checks it on its own.
|
|
14
|
+
# Returns a `Ltr::PipelineResult` with the metrics, the optimization split metrics and both deploy results.
|
|
15
|
+
def call
|
|
16
|
+
logger.info("Starting modelling pipeline")
|
|
17
|
+
|
|
18
|
+
logger.info("Loading dataset...")
|
|
19
|
+
df = Ltr::Data::DatasetLoader.load(config)
|
|
20
|
+
|
|
21
|
+
logger.info("Training XGBoost model...")
|
|
22
|
+
booster = Ltr::Train::XgbTrainer.call(config, df: df)
|
|
23
|
+
|
|
24
|
+
metrics, optimization_split_metrics = evaluate(df, booster)
|
|
25
|
+
|
|
26
|
+
logger.info("Checking deployment eligibility...")
|
|
27
|
+
deployment = Ltr::Train::DeployGate.call(config, booster, metrics)
|
|
28
|
+
local_deployment = deploy_locally_if_configured(booster, metrics)
|
|
29
|
+
logger.info("Modelling pipeline completed successfully")
|
|
30
|
+
|
|
31
|
+
Ltr::PipelineResult.new(
|
|
32
|
+
metrics: metrics,
|
|
33
|
+
optimization_split_metrics: optimization_split_metrics,
|
|
34
|
+
deployed: deployment[:deployed],
|
|
35
|
+
deployment: deployment,
|
|
36
|
+
local_deployment: local_deployment
|
|
37
|
+
)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
private
|
|
41
|
+
|
|
42
|
+
attr_reader :config
|
|
43
|
+
|
|
44
|
+
def evaluate(df, booster)
|
|
45
|
+
logger.info("Evaluating trained model...")
|
|
46
|
+
evaluation_split = Ltr::Data::Splits.evaluation_in(df, config)
|
|
47
|
+
metrics = Ltr::Train::XgbEvaluator.call(config, booster, df: df, split: evaluation_split)
|
|
48
|
+
optimization_split_metrics = Ltr::Train::OptimizationSplitReport.call(config, df, booster, metrics, evaluation_split)
|
|
49
|
+
[metrics, optimization_split_metrics]
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def deploy_locally_if_configured(booster, metrics)
|
|
53
|
+
unless config.local_deploy_enabled?
|
|
54
|
+
logger.info("Local deployment disabled by config (deploy.local=false). Skipping.")
|
|
55
|
+
return { deployed: false, reason: :not_configured }
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
if config.local_deploy_path.blank?
|
|
59
|
+
raise Ltr::ConfigurationError, "deploy.local_path is required when deploy.local is true"
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
deploy_metric = Ltr::Train::DeployMetric.call(config, metrics)
|
|
63
|
+
return skip_local_deploy_below_threshold(deploy_metric) unless deploy_metric[:met]
|
|
64
|
+
|
|
65
|
+
logger.info("Saving model locally to #{config.local_deploy_path}...")
|
|
66
|
+
info = Ltr::Deploy::LocalDeployer.call(config: config, booster: booster)
|
|
67
|
+
logger.info("Local deployment info: #{info.inspect}")
|
|
68
|
+
|
|
69
|
+
{ deployed: true, reason: :local_saved, path: info[:path] }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def skip_local_deploy_below_threshold(deploy_metric)
|
|
73
|
+
logger.info do
|
|
74
|
+
"#{deploy_metric[:metric_name]}=#{deploy_metric[:score]} < #{deploy_metric[:threshold]} → not saving the model locally"
|
|
75
|
+
end
|
|
76
|
+
Ltr::Train::DeployMetric.below_threshold_result(deploy_metric)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def logger
|
|
80
|
+
Ltr.config.logger
|
|
81
|
+
end
|
|
82
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Compares the evaluation metrics with the metrics on the optimization split.
|
|
4
|
+
|
|
5
|
+
class Ltr::Train::OptimizationSplitReport
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config, df, booster, metrics, evaluation_split)
|
|
9
|
+
@config = config
|
|
10
|
+
@df = df
|
|
11
|
+
@booster = booster
|
|
12
|
+
@metrics = metrics
|
|
13
|
+
@evaluation_split = evaluation_split
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Scores the model on the optimization split and logs the gap to the evaluation metrics.
|
|
17
|
+
# The gap is the evaluation value minus the optimization value, for metrics in both.
|
|
18
|
+
# Returns the optimization split metrics, or nil with a warning when both splits are the same.
|
|
19
|
+
def call
|
|
20
|
+
optimization_split = Ltr::Data::Splits.optimization_in(df, config)
|
|
21
|
+
|
|
22
|
+
return warn_splits_are_identical if evaluation_split == optimization_split
|
|
23
|
+
|
|
24
|
+
optimization_split_metrics = Ltr::Train::XgbEvaluator.call(config, booster, df: df, split: optimization_split)
|
|
25
|
+
gaps = metric_gaps(optimization_split_metrics)
|
|
26
|
+
logger.info("Reported '#{evaluation_split}' vs optimized '#{optimization_split}' split: #{gaps.join(", ")}")
|
|
27
|
+
|
|
28
|
+
optimization_split_metrics
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
private
|
|
32
|
+
|
|
33
|
+
attr_reader :config, :df, :booster, :metrics, :evaluation_split
|
|
34
|
+
|
|
35
|
+
def warn_splits_are_identical
|
|
36
|
+
logger.warn("Evaluation and optimization both read the '#{evaluation_split}' split, so the reported " \
|
|
37
|
+
"metrics are the ones the optimizer maximized. Rebuild the dataset with " \
|
|
38
|
+
"dataset_builder.split_ratios to separate them.")
|
|
39
|
+
nil
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def metric_gaps(optimization_split_metrics)
|
|
43
|
+
metrics.filter_map do |name, value|
|
|
44
|
+
optimized = optimization_split_metrics[name]
|
|
45
|
+
next if optimized.nil?
|
|
46
|
+
|
|
47
|
+
"#{name} #{value} vs #{optimized} (#{(value - optimized).round(4)})"
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def logger
|
|
52
|
+
Ltr.config.logger
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Keeps the requested features that exist in the dataset and fails when none do.
|
|
4
|
+
|
|
5
|
+
module Ltr::Train::Utils
|
|
6
|
+
class << self
|
|
7
|
+
# Returns the requested features that are columns in the dataframe. Missing ones are dropped and logged at `warn`.
|
|
8
|
+
# Raises `ArgumentError` when none are columns. `mode` only labels the log and the error.
|
|
9
|
+
def filter_features(df, features, mode)
|
|
10
|
+
logger.info("Filtering features for #{mode}. Requested features: #{features.length}")
|
|
11
|
+
|
|
12
|
+
available_columns = df.vectors.keys.map(&:to_s)
|
|
13
|
+
missing_features = features.map(&:to_s) - available_columns
|
|
14
|
+
|
|
15
|
+
unless missing_features.empty?
|
|
16
|
+
logger.warn("Missing features in dataset: #{missing_features.join(", ")}. These features will be excluded for #{mode}.")
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
available_features = features.select { |feature| available_columns.include?(feature.to_s) }
|
|
20
|
+
logger.info("Feature filtering completed for #{mode}. Available features: #{available_features.length}")
|
|
21
|
+
|
|
22
|
+
if available_features.empty?
|
|
23
|
+
raise ArgumentError, "No valid features found in dataset. Missing features: #{features.join(", ")} for #{mode}"
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
available_features
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def logger
|
|
32
|
+
Ltr.config.logger
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Evaluates a trained model on a split and returns the metrics.
|
|
4
|
+
|
|
5
|
+
class Ltr::Train::XgbEvaluator
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
# Returns the metrics hash. Builds an evaluation cache when none is passed.
|
|
9
|
+
# It uses `features` as given and does not filter them against the dataframe.
|
|
10
|
+
def self.evaluate_model(model, df, features, config, evaluation_cache: nil)
|
|
11
|
+
new(config, model, df: df).evaluate_model(model, df, features, evaluation_cache: evaluation_cache)
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def initialize(config, model, df: nil, split: nil)
|
|
15
|
+
@config = config
|
|
16
|
+
@model = model
|
|
17
|
+
@df = df
|
|
18
|
+
@split = split
|
|
19
|
+
@metrics_list = config.evaluation["metrics"]
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Scores the model on the split and returns the metrics hash.
|
|
23
|
+
# The split is the `split:` argument, else `evaluation.split`. `Ltr::Data::Splits.resolve` falls back to the test split.
|
|
24
|
+
# The features come from the model, else from SSM when enabled, else from the config. Those missing from the dataframe are dropped.
|
|
25
|
+
# Only a dataset loaded here is checked for the required columns and evaluation settings.
|
|
26
|
+
def call
|
|
27
|
+
df = @df || load_df
|
|
28
|
+
features = load_features(df)
|
|
29
|
+
split = evaluation_split(df)
|
|
30
|
+
evaluation_cache = Ltr::Train::EvaluationCache.new(df, split:, config:)
|
|
31
|
+
metrics = evaluation_cache.evaluate(model, features)
|
|
32
|
+
logger.info("Model evaluation completed on the '#{split}' split. Final metrics: #{metrics}")
|
|
33
|
+
|
|
34
|
+
metrics
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# Scores a model on the given features, using the passed evaluation cache or a new one. Returns the metrics hash.
|
|
38
|
+
# A passed cache keeps its own split. `df` is used only to build a new cache.
|
|
39
|
+
def evaluate_model(model, df, features, evaluation_cache: nil)
|
|
40
|
+
cache = evaluation_cache ||
|
|
41
|
+
Ltr::Train::EvaluationCache.new(df, split: evaluation_split(df), config:)
|
|
42
|
+
cache.evaluate(model, features)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
attr_reader :config, :model, :metrics_list
|
|
48
|
+
|
|
49
|
+
def load_df
|
|
50
|
+
df = Ltr::Data::DatasetLoader.load(config)
|
|
51
|
+
logger.info("Dataset loaded. Rows: #{df.length}, Columns: #{df.keys.length}")
|
|
52
|
+
validate_inputs!
|
|
53
|
+
df
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def validate_inputs!
|
|
57
|
+
raise ArgumentError, "Missing 'metrics' in config.evaluation" unless config.evaluation.key?("metrics")
|
|
58
|
+
unless config.evaluation.key?("min_relevance_grade") || config.evaluation.key?("min_relevance_percentile")
|
|
59
|
+
raise ArgumentError, "Missing 'min_relevance_grade' or 'min_relevance_percentile' in config.evaluation"
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def load_features(df)
|
|
64
|
+
all_features = model.feature_names
|
|
65
|
+
|
|
66
|
+
if all_features.present?
|
|
67
|
+
logger.info("Loaded #{all_features.length} features from model")
|
|
68
|
+
elsif config.ssm_enabled?
|
|
69
|
+
ssm_result = load_from_ssm
|
|
70
|
+
all_features = ssm_result[:all_features]
|
|
71
|
+
raise ArgumentError, "SSM is enabled but all_features not found in SSM" if all_features.nil?
|
|
72
|
+
|
|
73
|
+
logger.info("Successfully loaded #{all_features.length} features from SSM (model had no feature names)")
|
|
74
|
+
else
|
|
75
|
+
all_features = config.all_features
|
|
76
|
+
logger.info("Loaded #{all_features.length} features from config (model had no feature names)")
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
Ltr::Train::Utils.filter_features(df, all_features, "evaluation")
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
def load_from_ssm
|
|
83
|
+
Ltr::Ssm::Loader.call(
|
|
84
|
+
config,
|
|
85
|
+
load_all_features: true
|
|
86
|
+
)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def evaluation_split(df)
|
|
90
|
+
Ltr::Data::Splits.resolve(df, @split || config.evaluation_split, role: Ltr::Data::Splits::EVALUATION_ROLE)
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def logger
|
|
94
|
+
Ltr.config.logger
|
|
95
|
+
end
|
|
96
|
+
end
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Trains an XGBoost ranking model from the config features and hyperparameters.
|
|
4
|
+
|
|
5
|
+
class Ltr::Train::XgbTrainer
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
MAXIMIZED_EVAL_METRICS = %w[auc aucpr map ndcg pre recall].freeze
|
|
9
|
+
RANKING_OBJECTIVE_PREFIX = "rank:"
|
|
10
|
+
DEFAULT_N_ESTIMATORS = 100
|
|
11
|
+
|
|
12
|
+
# Trains an XGBoost booster on `dtrain`, using `deval` as the eval set.
|
|
13
|
+
# `hyperparameters` needs symbol keys. It reads `:n_estimators` (100 rounds when missing, with a warning), `:early_stopping_rounds`, `:eval_metric`, `:objective` and `:verbose_eval`.
|
|
14
|
+
# A truthy `:verbose_eval` logs an eval line to `Ltr.config.logger` every that many rounds (`true` is every round).
|
|
15
|
+
# Stops early only when `early_stopping_rounds` is set. Adds `nthread` to the hyperparameters when it is given.
|
|
16
|
+
def self.train_model(dtrain, deval, hyperparameters, seed:, nthread: nil)
|
|
17
|
+
hyperparameters = hyperparameters.merge(seed: seed)
|
|
18
|
+
hyperparameters = hyperparameters.merge(nthread: nthread) if nthread
|
|
19
|
+
Ltr.config.logger.info("Starting model training with hyperparameters: #{hyperparameters}")
|
|
20
|
+
if hyperparameters[:n_estimators].nil?
|
|
21
|
+
Ltr.config.logger.warn("n_estimators is missing, so the model trains #{DEFAULT_N_ESTIMATORS} rounds.")
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
XGBoost.train(
|
|
25
|
+
hyperparameters,
|
|
26
|
+
dtrain,
|
|
27
|
+
num_boost_round: hyperparameters[:n_estimators] || DEFAULT_N_ESTIMATORS,
|
|
28
|
+
evals: [[deval, "eval"]],
|
|
29
|
+
early_stopping_rounds: hyperparameters[:early_stopping_rounds] || nil,
|
|
30
|
+
maximize: maximized_eval_metric?(hyperparameters[:eval_metric], hyperparameters[:objective]),
|
|
31
|
+
verbose_eval: false,
|
|
32
|
+
callbacks: hyperparameters[:verbose_eval] ? [Ltr::Train::EvalLogger.new(hyperparameters[:verbose_eval])] : []
|
|
33
|
+
)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Predicts with the rounds up to the best round that early stopping found.
|
|
37
|
+
# Predicts with every tree when the model has no `best_iteration`, which is the case without early stopping.
|
|
38
|
+
# `ntree_limit` counts trees, so the rounds are multiplied by `num_parallel_tree`.
|
|
39
|
+
def self.predict(model, dmatrix)
|
|
40
|
+
best_iteration = model.best_iteration
|
|
41
|
+
return model.predict(dmatrix) if best_iteration.nil?
|
|
42
|
+
|
|
43
|
+
model.predict(dmatrix, ntree_limit: (best_iteration + 1) * num_parallel_tree(model))
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def self.num_parallel_tree(model)
|
|
47
|
+
JSON.parse(model.save_config).dig("learner", "gradient_booster", "gbtree_model_param", "num_parallel_tree").to_i
|
|
48
|
+
end
|
|
49
|
+
private_class_method :num_parallel_tree
|
|
50
|
+
|
|
51
|
+
# Returns true when `eval_metric` is in `MAXIMIZED_EVAL_METRICS`. A `@k` cutoff and a `-` suffix are ignored.
|
|
52
|
+
# With no eval metric it returns true for any objective that starts with `rank:`, and false otherwise.
|
|
53
|
+
def self.maximized_eval_metric?(eval_metric, objective = nil)
|
|
54
|
+
if eval_metric.present?
|
|
55
|
+
return MAXIMIZED_EVAL_METRICS.include?(eval_metric.to_s[/\A[^@]*/].delete_suffix("-"))
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
objective.to_s.start_with?(RANKING_OBJECTIVE_PREFIX)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def initialize(config, df: nil)
|
|
62
|
+
@config = config
|
|
63
|
+
@df = df
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Loads the dataset when none was passed. Loads the features and hyperparameters from SSM when enabled, else from the config.
|
|
67
|
+
# Features missing from the dataframe are dropped. Raises `ArgumentError` when SSM is enabled but has no features or hyperparameters.
|
|
68
|
+
# Trains on the train split, with the early stopping split as the eval set.
|
|
69
|
+
# When `early_stopping_rounds` is set and the best round is before the last round, trains again for `best_iteration + 1` rounds with early stopping off, so the returned booster holds no rounds past the best one.
|
|
70
|
+
# The second run is at most `early_stopping_rounds` rounds shorter than the first, so this final training takes close to twice as long.
|
|
71
|
+
# Raises `ArgumentError` naming each feature whose name has `[`, `]` or `<`, which XGBoost rejects.
|
|
72
|
+
# Returns the booster.
|
|
73
|
+
def call
|
|
74
|
+
df = @df || Ltr::Data::DatasetLoader.load(config)
|
|
75
|
+
logger.info("Dataset loaded. Rows: #{df.length}, Columns: #{df.keys.length}")
|
|
76
|
+
|
|
77
|
+
logger.info("Loading features and hyperparameters...")
|
|
78
|
+
features, hyperparameters = load_features_and_hyperparameters
|
|
79
|
+
|
|
80
|
+
logger.info("Filtering features based on dataset availability...")
|
|
81
|
+
features = Ltr::Train::Utils.filter_features(df, features, "training")
|
|
82
|
+
logger.info("Final feature set: #{features}")
|
|
83
|
+
|
|
84
|
+
early_stopping_split = Ltr::Data::Splits.early_stopping_in(df, config)
|
|
85
|
+
|
|
86
|
+
dtrain, deval = build_dmatrices(df, features, early_stopping_split)
|
|
87
|
+
|
|
88
|
+
booster = train_model(dtrain, deval, hyperparameters)
|
|
89
|
+
logger.info("XGBoost training completed successfully")
|
|
90
|
+
|
|
91
|
+
retrain_to_best_round(booster, dtrain, deval, hyperparameters)
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
attr_reader :config, :df
|
|
97
|
+
|
|
98
|
+
def load_features_and_hyperparameters
|
|
99
|
+
features, hyperparameters = config.ssm_enabled? ? features_and_hyperparameters_from_ssm : features_and_hyperparameters_from_config
|
|
100
|
+
[features, hyperparameters.transform_keys(&:to_sym)]
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def features_and_hyperparameters_from_ssm
|
|
104
|
+
ssm_result = load_from_ssm
|
|
105
|
+
features = ssm_result[:all_features]
|
|
106
|
+
hyperparameters = ssm_result[:hyperparameters]
|
|
107
|
+
|
|
108
|
+
raise ArgumentError, "SSM is enabled but all_features not found in SSM" if features.nil?
|
|
109
|
+
raise ArgumentError, "SSM is enabled but hyperparameters not found in SSM" if hyperparameters.nil?
|
|
110
|
+
|
|
111
|
+
logger.info("Successfully loaded from SSM: #{features.length} features, #{hyperparameters.keys.length} hyperparameters")
|
|
112
|
+
[features, hyperparameters]
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def load_from_ssm
|
|
116
|
+
Ltr::Ssm::Loader.call(
|
|
117
|
+
config,
|
|
118
|
+
load_all_features: true,
|
|
119
|
+
load_hyperparameters: true
|
|
120
|
+
)
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def features_and_hyperparameters_from_config
|
|
124
|
+
features = config.all_features
|
|
125
|
+
hyperparameters = config.hyperparameters
|
|
126
|
+
logger.info("Loaded from config: #{features.length} features, #{hyperparameters.keys.length} hyperparameters")
|
|
127
|
+
[features, hyperparameters]
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def build_dmatrices(df, features, early_stopping_split)
|
|
131
|
+
logger.info("Creating train and #{early_stopping_split} DMatrix objects...")
|
|
132
|
+
dtrain = Ltr::Data::Dataframe.dmatrix_from_dataframe(df, features, split: Ltr::Data::Splits::TRAIN)
|
|
133
|
+
deval = Ltr::Data::Dataframe.dmatrix_from_dataframe(df, features, split: early_stopping_split)
|
|
134
|
+
logger.info("DMatrix creation completed. Training samples: #{dtrain.num_row}, " \
|
|
135
|
+
"#{early_stopping_split} samples: #{deval.num_row}")
|
|
136
|
+
[dtrain, deval]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def train_model(dtrain, deval, hyperparameters)
|
|
140
|
+
self.class.train_model(dtrain, deval, hyperparameters, seed: config.seed, nthread: config.nthread)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
def retrain_to_best_round(booster, dtrain, deval, hyperparameters)
|
|
144
|
+
best_iteration = booster.best_iteration
|
|
145
|
+
return booster if best_iteration.nil? || best_iteration + 1 == booster.num_boosted_rounds
|
|
146
|
+
|
|
147
|
+
logger.info("Best round is #{best_iteration}. Training again for #{best_iteration + 1} rounds, down from #{booster.num_boosted_rounds}.")
|
|
148
|
+
train_model(dtrain, deval, hyperparameters.except(:early_stopping_rounds).merge(n_estimators: best_iteration + 1))
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
def logger
|
|
152
|
+
Ltr.config.logger
|
|
153
|
+
end
|
|
154
|
+
end
|
data/lib/ltr/ubi.rb
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Builds UBI query and event records from search data.
|
|
4
|
+
# Checks the arguments and normalizes timestamps.
|
|
5
|
+
|
|
6
|
+
class Ltr::Ubi
|
|
7
|
+
class << self
|
|
8
|
+
# Builds a UBI query record from one search. Optional fields that are nil are left out.
|
|
9
|
+
# `config` is the model's `Ltr::ConfigLoader`. Its `query_id_field` and `hit_ids_field` name the keys.
|
|
10
|
+
# Raises ArgumentError when an argument is missing or has the wrong type.
|
|
11
|
+
# The timestamp becomes a UTC ISO8601 string. A `Time` is converted on a copy. A string without an offset is read as local time.
|
|
12
|
+
def query(config:, query_id:, user_query:, timestamp:, scores:, hit_ids:,
|
|
13
|
+
application: nil, client_id: nil, query_response_id: nil)
|
|
14
|
+
validate_query_args!(config, query_id, user_query, timestamp, scores, hit_ids, application, client_id, query_response_id)
|
|
15
|
+
|
|
16
|
+
{
|
|
17
|
+
config.query_id_field => query_id,
|
|
18
|
+
"user_query" => user_query,
|
|
19
|
+
"timestamp" => normalize_timestamp(timestamp),
|
|
20
|
+
"query_attributes" => { "scores" => scores },
|
|
21
|
+
config.hit_ids_field => hit_ids,
|
|
22
|
+
}.merge({
|
|
23
|
+
"application" => application,
|
|
24
|
+
"client_id" => client_id,
|
|
25
|
+
"query_response_id" => query_response_id,
|
|
26
|
+
}.compact)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Builds a UBI event record for one user action on a document.
|
|
30
|
+
# `config` is the model's `Ltr::ConfigLoader`. Its `query_id_field` and `doc_id_field` name the keys.
|
|
31
|
+
# Raises ArgumentError when an argument is missing or has the wrong type.
|
|
32
|
+
# The timestamp becomes a UTC ISO8601 string. A `Time` is converted on a copy. A string without an offset is read as local time.
|
|
33
|
+
def event(config:, query_id:, action_name:, doc_id:, timestamp:)
|
|
34
|
+
validate_event_args!(config, query_id, action_name, doc_id, timestamp)
|
|
35
|
+
|
|
36
|
+
{
|
|
37
|
+
config.query_id_field => query_id,
|
|
38
|
+
"action_name" => action_name,
|
|
39
|
+
"event_attributes" => { config.doc_id_field => doc_id },
|
|
40
|
+
"timestamp" => normalize_timestamp(timestamp),
|
|
41
|
+
}
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
private
|
|
45
|
+
|
|
46
|
+
def validate_query_args!(config, query_id, user_query, timestamp, scores, hit_ids, application, client_id, query_response_id)
|
|
47
|
+
raise ArgumentError, "Config must be a Ltr::ConfigLoader." unless config.is_a?(Ltr::ConfigLoader)
|
|
48
|
+
raise ArgumentError, "Query id must be a non-blank string." if query_id.blank? || !query_id.is_a?(String)
|
|
49
|
+
raise ArgumentError, "User query must be a non-blank string." if user_query.blank? || !user_query.is_a?(String)
|
|
50
|
+
raise ArgumentError, "Timestamp is required." if timestamp.nil?
|
|
51
|
+
raise ArgumentError, "Scores must be a non-empty hash." unless scores.is_a?(Hash) && !scores.empty?
|
|
52
|
+
raise ArgumentError, "Each scores entry must be a hash of score name to value." unless scores.values.all? { |v| v.is_a?(Hash) }
|
|
53
|
+
raise ArgumentError, "Hit ids must be a non-empty array." unless hit_ids.is_a?(Array) && !hit_ids.empty?
|
|
54
|
+
raise ArgumentError, "Application must be a string if given." if application && !application.is_a?(String)
|
|
55
|
+
raise ArgumentError, "Client id must be a string if given." if client_id && !client_id.is_a?(String)
|
|
56
|
+
raise ArgumentError, "Query response id must be a string if given." if query_response_id && !query_response_id.is_a?(String)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def validate_event_args!(config, query_id, action_name, doc_id, timestamp)
|
|
60
|
+
raise ArgumentError, "Config must be a Ltr::ConfigLoader." unless config.is_a?(Ltr::ConfigLoader)
|
|
61
|
+
raise ArgumentError, "Query id must be a non-blank string." if query_id.blank? || !query_id.is_a?(String)
|
|
62
|
+
raise ArgumentError, "Action name must be a non-blank string." if action_name.blank? || !action_name.is_a?(String)
|
|
63
|
+
raise ArgumentError, "Doc id must be a non-blank string." if doc_id.blank? || !doc_id.is_a?(String)
|
|
64
|
+
raise ArgumentError, "Timestamp is required." if timestamp.nil?
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def normalize_timestamp(timestamp)
|
|
68
|
+
case timestamp
|
|
69
|
+
when Time, DateTime, ActiveSupport::TimeWithZone
|
|
70
|
+
timestamp.getutc.iso8601
|
|
71
|
+
when Date
|
|
72
|
+
timestamp.to_time(:utc).iso8601
|
|
73
|
+
when String
|
|
74
|
+
validate_iso8601_string!(timestamp)
|
|
75
|
+
else
|
|
76
|
+
raise ArgumentError, "Timestamp must be a Time, Date, or ISO8601 string."
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def validate_iso8601_string!(timestamp)
|
|
81
|
+
Time.iso8601(timestamp).utc.iso8601
|
|
82
|
+
rescue ArgumentError
|
|
83
|
+
raise ArgumentError, "Timestamp string must be valid ISO8601."
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
data/lib/ltr.rb
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Loads the gem dependencies and sets up autoloading.
|
|
4
|
+
# Exposes the shared gem configuration.
|
|
5
|
+
|
|
6
|
+
require "csv"
|
|
7
|
+
require "digest"
|
|
8
|
+
require "erb"
|
|
9
|
+
require "fileutils"
|
|
10
|
+
require "json"
|
|
11
|
+
require "logger"
|
|
12
|
+
require "matrix"
|
|
13
|
+
require "pathname"
|
|
14
|
+
require "stringio"
|
|
15
|
+
require "tmpdir"
|
|
16
|
+
require "uri"
|
|
17
|
+
require "yaml"
|
|
18
|
+
require "zlib"
|
|
19
|
+
|
|
20
|
+
require "active_support"
|
|
21
|
+
require "active_support/core_ext/enumerable"
|
|
22
|
+
require "active_support/core_ext/object/blank"
|
|
23
|
+
require "active_support/core_ext/object/json"
|
|
24
|
+
require "active_support/core_ext/string/inflections"
|
|
25
|
+
require "active_support/time"
|
|
26
|
+
require "numo/narray"
|
|
27
|
+
require "rover"
|
|
28
|
+
require "xgb"
|
|
29
|
+
|
|
30
|
+
require "zeitwerk"
|
|
31
|
+
|
|
32
|
+
loader = Zeitwerk::Loader.for_gem
|
|
33
|
+
loader.inflector.inflect("version" => "VERSION")
|
|
34
|
+
loader.ignore("#{__dir__}/ltr/deploy/artifacts")
|
|
35
|
+
# Collapsed folders define classes directly under Ltr, not under Ltr::<Folder>.
|
|
36
|
+
loader.collapse("#{__dir__}/ltr/configuration")
|
|
37
|
+
loader.collapse("#{__dir__}/ltr/errors")
|
|
38
|
+
loader.collapse("#{__dir__}/ltr/support")
|
|
39
|
+
loader.collapse("#{__dir__}/ltr/dataset_aggregation/labels")
|
|
40
|
+
loader.collapse("#{__dir__}/ltr/dataset_aggregation/dataset_builder/steps")
|
|
41
|
+
loader.collapse("#{__dir__}/ltr/features/encoders")
|
|
42
|
+
loader.setup
|
|
43
|
+
|
|
44
|
+
module Ltr
|
|
45
|
+
class << self
|
|
46
|
+
# Returns the shared gem configuration and builds it on first use.
|
|
47
|
+
def config
|
|
48
|
+
@config ||= Configuration.new
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Yields the shared configuration to the block.
|
|
52
|
+
def configure
|
|
53
|
+
yield(config)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Replaces the shared configuration with a new default one.
|
|
57
|
+
def reset_config!
|
|
58
|
+
@config = Configuration.new
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
data/scripts/seed_ubi.rb
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "bundler/setup"
|
|
4
|
+
require "opensearch"
|
|
5
|
+
require_relative "../config/ltr_host"
|
|
6
|
+
|
|
7
|
+
SEARCHES = 3000
|
|
8
|
+
PRODUCTS_PER_QUERY = 30
|
|
9
|
+
QUERIES = [
|
|
10
|
+
"vitamin c", "magnesium", "fish oil", "probiotic", "vitamin d", "zinc", "melatonin", "turmeric",
|
|
11
|
+
"collagen", "iron", "b12", "ashwagandha", "elderberry", "creatine", "protein powder", "multivitamin",
|
|
12
|
+
"calcium", "biotin", "coq10", "omega 3", "vitamin k2", "quercetin", "nac", "lysine", "glutamine",
|
|
13
|
+
"folate", "potassium", "selenium", "berberine", "curcumin", "magnesium glycinate", "vitamin e",
|
|
14
|
+
"electrolytes", "l-theanine", "spirulina", "digestive enzymes", "iodine", "cinnamon", "gaba", "rhodiola"
|
|
15
|
+
].freeze
|
|
16
|
+
|
|
17
|
+
rng = Random.new(1967)
|
|
18
|
+
now = Time.now.utc
|
|
19
|
+
client = OpenSearch::Client.new(Ltr.config.opensearch_connect_options(
|
|
20
|
+
ENV.fetch("OPENSEARCH_URL", "http://localhost:9200"), ENV["OPENSEARCH_USERNAME"], ENV["OPENSEARCH_PASSWORD"]
|
|
21
|
+
))
|
|
22
|
+
|
|
23
|
+
catalog = QUERIES.each_with_index.to_h do |text, query_index|
|
|
24
|
+
products = Array.new(PRODUCTS_PER_QUERY) do |product_index|
|
|
25
|
+
quality = rng.rand
|
|
26
|
+
{
|
|
27
|
+
id: format("p%02d-%02d", query_index, product_index),
|
|
28
|
+
quality: quality,
|
|
29
|
+
bm25_name: [2 + (8 * quality) + rng.rand(-4.0..4.0), 0].max.round(3),
|
|
30
|
+
bm25_description: [1 + (5 * quality) + rng.rand(-3.0..3.0), 0].max.round(3),
|
|
31
|
+
}
|
|
32
|
+
end
|
|
33
|
+
products.each do |product|
|
|
34
|
+
product[:relevancy] = ((0.6 * product[:bm25_name]) + (0.4 * product[:bm25_description]) + rng.rand(-2.0..2.0)).round(3)
|
|
35
|
+
end
|
|
36
|
+
[text, products.sort_by { |product| -product[:relevancy] }]
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
documents = []
|
|
40
|
+
SEARCHES.times do |n|
|
|
41
|
+
text = QUERIES.sample(random: rng)
|
|
42
|
+
products = catalog.fetch(text)
|
|
43
|
+
query_id = format("q-%04d", n)
|
|
44
|
+
searched_at = now - rng.rand(0..(6 * 24 * 3600)) - 3600
|
|
45
|
+
scores = products.to_h { |product| [product[:id], product.slice(:bm25_name, :bm25_description, :relevancy).transform_keys(&:to_s)] }
|
|
46
|
+
documents << { _index: "ubi_queries", data: Ltr::Ubi.query(
|
|
47
|
+
config: UBI_CONFIG, query_id: query_id, user_query: text, timestamp: searched_at, scores: scores, hit_ids: products.map { |product| product[:id] }
|
|
48
|
+
) }
|
|
49
|
+
|
|
50
|
+
products.each_with_index do |product, position|
|
|
51
|
+
next if position > 0 && rng.rand > 0.97**position
|
|
52
|
+
next unless rng.rand < 0.03 + (0.9 * product[:quality]**2)
|
|
53
|
+
|
|
54
|
+
actions = %w[view]
|
|
55
|
+
actions << "add_to_cart" if rng.rand < 0.1 + (0.6 * product[:quality])
|
|
56
|
+
actions << "purchase" if actions.include?("add_to_cart") && rng.rand < 0.2 + (0.6 * product[:quality])
|
|
57
|
+
actions.each_with_index do |action, step|
|
|
58
|
+
documents << { _index: "ubi_events", data: Ltr::Ubi.event(
|
|
59
|
+
config: UBI_CONFIG, query_id: query_id, action_name: action, doc_id: product[:id], timestamp: searched_at + 10 + (30 * step)
|
|
60
|
+
) }
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
documents.each_slice(1000) do |slice|
|
|
66
|
+
response = client.bulk(body: slice.map { |doc| { index: doc } }, refresh: true)
|
|
67
|
+
abort "bulk load failed: #{response["items"].find { |item| item.values.first["error"] }}" if response["errors"]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
FileUtils.mkdir_p("tmp/ltr")
|
|
71
|
+
truth = catalog.values.flatten.to_h { |product| [product[:id], product[:quality].round(4)] }
|
|
72
|
+
File.write("tmp/ltr/truth.json", JSON.pretty_generate(truth))
|
|
73
|
+
|
|
74
|
+
puts "queries: #{client.count(index: "ubi_queries")["count"]}"
|
|
75
|
+
puts "events: #{client.count(index: "ubi_events")["count"]}"
|