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,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Packages the model and inference code into a tarball and uploads it to S3.
4
+
5
+ require "fileutils"
6
+ require "open3"
7
+ require "tmpdir"
8
+
9
+ class Ltr::Deploy::ModelPackager
10
+ ARTIFACTS_DIR = File.expand_path("artifacts", __dir__).freeze
11
+ CODE_FILES = %w[inference.py requirements.txt].freeze
12
+ MODEL_FILE_NAME = "xgboost-model.ubj"
13
+ CODE_DIR_NAME = "code"
14
+ TARBALL_NAME = "model.tar.gz"
15
+
16
+ def initialize(booster:, bucket:, stamped_model_name:, features:, feature_store_data: nil)
17
+ @booster = booster
18
+ @bucket = bucket
19
+ @stamped_model_name = stamped_model_name
20
+ @features = features
21
+ @feature_store_data = feature_store_data
22
+ end
23
+
24
+ # Returns the S3 uri that `upload_model_tarball` writes to. It uploads nothing itself.
25
+ def model_s3_uri
26
+ @model_s3_uri ||= "s3://#{bucket}/#{s3_model_key}"
27
+ end
28
+
29
+ # Builds the tarball in a temp folder, so nothing is written inside the installed gem.
30
+ # The tarball holds the model at the root, then `code/` with `inference.py`, `requirements.txt` and `features.json`.
31
+ # It also holds `code/feature_store.json` when feature store data was given.
32
+ # Returns the tarball path. The file stays in its own temp folder until `upload_model_tarball` deletes it.
33
+ # Raises when `code/inference.py` is missing, or `Ltr::Error` with the command and its stderr when `tar` fails.
34
+ def package_model_and_code
35
+ raise "Missing inference.py at #{inference_path}" unless File.exist?(inference_path)
36
+
37
+ @output_dir = Dir.mktmpdir("ltr-model-tarball")
38
+ tarball_path = Dir.mktmpdir("ltr-model-build") do |build_dir|
39
+ stage_files(build_dir)
40
+ run_tar(build_dir, File.join(@output_dir, TARBALL_NAME))
41
+ end
42
+ packaged = true
43
+ tarball_path
44
+ ensure
45
+ FileUtils.rm_rf(@output_dir) if @output_dir && !packaged
46
+ end
47
+
48
+ # Uploads the tarball to S3, then deletes the temp folder from `package_model_and_code`. The folder is deleted if the upload raises too.
49
+ def upload_model_tarball(tarball_path)
50
+ File.open(tarball_path, "rb") do |file|
51
+ Ltr.config.s3_client.put_object(
52
+ bucket: bucket,
53
+ key: s3_model_key,
54
+ body: file,
55
+ content_type: "application/gzip"
56
+ )
57
+ end
58
+ ensure
59
+ FileUtils.rm_rf(@output_dir) if @output_dir
60
+ end
61
+
62
+ private
63
+
64
+ attr_reader :booster, :bucket, :stamped_model_name, :features, :feature_store_data
65
+
66
+ def s3_model_key
67
+ @s3_model_key ||= "ltr/models/#{stamped_model_name}/model.tar.gz"
68
+ end
69
+
70
+ def inference_path
71
+ File.join(ARTIFACTS_DIR, CODE_DIR_NAME, "inference.py")
72
+ end
73
+
74
+ def stage_files(build_dir)
75
+ code_dir = File.join(build_dir, CODE_DIR_NAME)
76
+ FileUtils.mkdir_p(code_dir)
77
+ CODE_FILES.each { |name| FileUtils.cp(File.join(ARTIFACTS_DIR, CODE_DIR_NAME, name), code_dir) }
78
+ booster.save_model(File.join(build_dir, MODEL_FILE_NAME))
79
+ File.write(File.join(code_dir, "features.json"), JSON.pretty_generate(features.call))
80
+ File.write(File.join(code_dir, "feature_store.json"), JSON.pretty_generate(feature_store_data)) if feature_store_data
81
+ end
82
+
83
+ def run_tar(build_dir, tarball_path)
84
+ command = ["tar", "-czf", tarball_path, MODEL_FILE_NAME, CODE_DIR_NAME]
85
+ _stdout, stderr, status = Open3.capture3(*command, chdir: build_dir)
86
+ raise Ltr::Error, "`#{command.join(" ")}` failed with exit status #{status.exitstatus.inspect}: #{stderr.strip}" unless status.success?
87
+
88
+ tarball_path
89
+ end
90
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Deploys the trained model to a SageMaker endpoint.
4
+
5
+ class Ltr::Deploy::SagemakerDeployer
6
+ extend Ltr::Callable
7
+
8
+ def initialize(config:, booster:)
9
+ @config = config
10
+ @booster = booster
11
+ @region = config.s3_region
12
+ @bucket = config.deploy["sagemaker_bucket"]
13
+ @role_arn = config.deploy["execution_role"]
14
+
15
+ @model_name = config.model_name
16
+ @stamped_model_name = "#{@model_name}-#{Time.now.to_i}"
17
+ @endpoint_config_name = "#{@stamped_model_name}-config"
18
+ @endpoint_name = "#{@model_name}-endpoint"
19
+ end
20
+
21
+ # Packages the model, uploads it and creates or updates the SageMaker endpoint.
22
+ # Feature store data goes into the package only when `feature_store.include_in_deployment` is `true`.
23
+ # The model file holds the feature transform steps and the one-hot column names from training.
24
+ # The feature list comes from SSM when `ssm.enabled` is true, else from the config.
25
+ # Waits until the endpoint is `InService`, then returns the endpoint info hash.
26
+ # Raises when the endpoint fails, rolls back to the old config, or does not become ready in time.
27
+ def call
28
+ dataset = Ltr::Features::TransformStore.read_dataset(config)
29
+ Ltr::Features::TransformStore.write_model_attributes(booster, config, dataset)
30
+ packager = build_packager(Ltr::Deploy::FeatureStoreDeployer.for_deployment(config, dataset: dataset))
31
+ endpoint = build_endpoint(packager)
32
+ tarball_path = packager.package_model_and_code
33
+ packager.upload_model_tarball(tarball_path)
34
+ endpoint.create_model
35
+ endpoint.create_endpoint_config
36
+ endpoint.create_or_update_endpoint
37
+ endpoint.wait_for_endpoint
38
+ endpoint.get_endpoint_info
39
+ end
40
+
41
+ private
42
+
43
+ attr_reader :config, :booster, :stamped_model_name,
44
+ :region, :bucket, :role_arn,
45
+ :model_name, :endpoint_config_name, :endpoint_name
46
+
47
+ def build_packager(feature_store_data)
48
+ Ltr::Deploy::ModelPackager.new(
49
+ booster: booster,
50
+ bucket: bucket,
51
+ stamped_model_name: stamped_model_name,
52
+ features: -> { inference_features },
53
+ feature_store_data: feature_store_data
54
+ )
55
+ end
56
+
57
+ def build_endpoint(packager)
58
+ Ltr::Deploy::SagemakerEndpoint.new(
59
+ region: region,
60
+ role_arn: role_arn,
61
+ deploy_config: config.deploy,
62
+ stamped_model_name: stamped_model_name,
63
+ endpoint_config_name: endpoint_config_name,
64
+ endpoint_name: endpoint_name,
65
+ model_s3_uri: packager.model_s3_uri
66
+ )
67
+ end
68
+
69
+ def inference_features
70
+ @inference_features ||= if config.ssm_enabled?
71
+ logger.info("[SagemakerDeployer] Loading optimized features from SSM")
72
+ ssm_feature_source.load(:all_features)
73
+ else
74
+ config.all_features
75
+ end
76
+ end
77
+
78
+ def ssm_feature_source
79
+ @ssm_feature_source ||= Ltr::Deploy::SsmFeatureSource.new(config, log_prefix: "SagemakerDeployer")
80
+ end
81
+
82
+ def logger
83
+ Ltr.config.logger
84
+ end
85
+ end
@@ -0,0 +1,199 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Creates the SageMaker model, endpoint config and endpoint and waits until the endpoint is ready.
4
+
5
+ class Ltr::Deploy::SagemakerEndpoint
6
+ # The SageMaker XGBoost container serves the model. It loads `inference.py` as a user module and calls its `transform_fn`.
7
+ IMAGE = "sagemaker-xgboost:3.0-5"
8
+
9
+ # Registry account of the 3.0-5 image in each region. AWS publishes no 3.0-5 image in ap-east-2, ap-southeast-5,
10
+ # ap-southeast-6, ap-southeast-7 and mx-central-1. A deploy there must set `deploy.image_uri`.
11
+ IMAGE_REGISTRY_ACCOUNTS = {
12
+ "af-south-1" => "510948584623",
13
+ "ap-east-1" => "651117190479",
14
+ "ap-northeast-1" => "354813040037",
15
+ "ap-northeast-2" => "366743142698",
16
+ "ap-northeast-3" => "867004704886",
17
+ "ap-south-1" => "720646828776",
18
+ "ap-south-2" => "628508329040",
19
+ "ap-southeast-1" => "121021644041",
20
+ "ap-southeast-2" => "783357654285",
21
+ "ap-southeast-3" => "951798379941",
22
+ "ap-southeast-4" => "106583098589",
23
+ "ca-central-1" => "341280168497",
24
+ "ca-west-1" => "190319476487",
25
+ "eu-central-1" => "492215442770",
26
+ "eu-central-2" => "680994064768",
27
+ "eu-north-1" => "662702820516",
28
+ "eu-south-1" => "978288397137",
29
+ "eu-south-2" => "104374241257",
30
+ "eu-west-1" => "141502667606",
31
+ "eu-west-2" => "764974769150",
32
+ "eu-west-3" => "659782779980",
33
+ "il-central-1" => "898809789911",
34
+ "me-central-1" => "272398656194",
35
+ "me-south-1" => "801668240914",
36
+ "sa-east-1" => "737474898029",
37
+ "us-east-1" => "683313688378",
38
+ "us-east-2" => "257758044811",
39
+ "us-west-1" => "746614075791",
40
+ "us-west-2" => "246618743249",
41
+ }.freeze
42
+
43
+ ENDPOINT_CONFIG_SETTLE_SECONDS = 2
44
+
45
+ # Uses `deploy.image_uri` when it is set. Otherwise it uses `IMAGE` in the region's registry account.
46
+ # Raises when neither exists, or when the image is not an ECR image in the region,
47
+ # so a deploy fails before it uploads anything.
48
+ def initialize(region:, role_arn:, deploy_config:, stamped_model_name:, endpoint_config_name:, endpoint_name:,
49
+ model_s3_uri:)
50
+ @region = region
51
+ @role_arn = role_arn
52
+ @deploy_config = deploy_config
53
+ @stamped_model_name = stamped_model_name
54
+ @endpoint_config_name = endpoint_config_name
55
+ @endpoint_name = endpoint_name
56
+ @model_s3_uri = model_s3_uri
57
+ @image_uri = deploy_config["image_uri"].presence || built_in_image_uri
58
+ raise_unless_ecr_image_in_region
59
+ Ltr::OptionalDependency.require!("aws-sdk-sagemaker", feature: "SageMaker deployment")
60
+ end
61
+
62
+ # Creates the SageMaker model from the uploaded model tarball.
63
+ def create_model
64
+ sagemaker_client.create_model(
65
+ model_name: stamped_model_name,
66
+ primary_container: {
67
+ image: image_uri,
68
+ model_data_url: model_s3_uri,
69
+ environment: {
70
+ "SAGEMAKER_PROGRAM" => "inference.py",
71
+ "SAGEMAKER_SUBMIT_DIRECTORY" => "/opt/ml/model/code",
72
+ "PYTHONPATH" => "/opt/ml/model/code",
73
+ },
74
+ image_config: { repository_access_mode: "Platform" },
75
+ },
76
+ execution_role_arn: role_arn
77
+ )
78
+ end
79
+
80
+ # Creates the endpoint config with one variant.
81
+ # The instance type and count come from the deploy config. They default to `ml.m5.large` and 1.
82
+ # Then it sleeps `ENDPOINT_CONFIG_SETTLE_SECONDS`.
83
+ def create_endpoint_config
84
+ sagemaker_client.create_endpoint_config(
85
+ endpoint_config_name: endpoint_config_name,
86
+ production_variants: [
87
+ {
88
+ variant_name: "primary",
89
+ model_name: stamped_model_name,
90
+ initial_instance_count: deploy_config["instance_count"] || 1,
91
+ instance_type: deploy_config["instance_type"] || "ml.m5.large",
92
+ initial_variant_weight: 1.0,
93
+ },
94
+ ]
95
+ )
96
+ sleep ENDPOINT_CONFIG_SETTLE_SECONDS
97
+ end
98
+
99
+ # Creates the endpoint. When SageMaker says it already exists, updates it with the new endpoint config.
100
+ # Any other SageMaker error is raised.
101
+ def create_or_update_endpoint
102
+ sagemaker_client.create_endpoint(
103
+ endpoint_name: endpoint_name,
104
+ endpoint_config_name: endpoint_config_name
105
+ )
106
+ rescue Aws::SageMaker::Errors::ServiceError => e
107
+ # SageMaker has no upsert, so an existing endpoint is detected from the error text and updated.
108
+ msg = e.message.to_s
109
+ if msg.include?("Cannot create already existing endpoint") && msg.include?(endpoint_name)
110
+ sagemaker_client.update_endpoint(
111
+ endpoint_name: endpoint_name,
112
+ endpoint_config_name: endpoint_config_name
113
+ )
114
+ else
115
+ raise
116
+ end
117
+ end
118
+
119
+ # Polls until the endpoint is `InService` on the new endpoint config. By default it checks 60 times, 60 seconds apart.
120
+ # When `InService` shows a different config name, the update rolled back and it raises `Ltr::DeployError`.
121
+ # It keeps polling on `Creating`, `Updating`, `SystemUpdating` and `RollingBack`. It raises on `Failed` and on any other status.
122
+ # It also raises when the attempts run out. It does not sleep after the last attempt.
123
+ def wait_for_endpoint(attempts: 60, interval: 60)
124
+ 1.upto(attempts) do |attempt|
125
+ status, reason, serving_config_name = fetch_endpoint_status
126
+
127
+ case status
128
+ when "InService"
129
+ raise_if_rolled_back(serving_config_name, reason)
130
+ return true
131
+ when "Failed"
132
+ raise Ltr::DeployError, "Endpoint failed: #{reason}"
133
+ when "Creating", "Updating", "SystemUpdating", "RollingBack"
134
+ next if attempt == attempts
135
+
136
+ logger.info("[SagemakerDeployer] Endpoint '#{endpoint_name}' not ready yet, retrying in #{interval} seconds...")
137
+ sleep interval
138
+ else
139
+ raise Ltr::DeployError, "Unexpected status: #{status}"
140
+ end
141
+ end
142
+
143
+ raise Ltr::DeployError, "Timeout waiting for endpoint '#{endpoint_name}' to be ready"
144
+ end
145
+
146
+ # Returns a hash with the endpoint name, ARN, status and creation and last modified times.
147
+ def get_endpoint_info
148
+ response = sagemaker_client.describe_endpoint(endpoint_name: endpoint_name)
149
+
150
+ {
151
+ endpoint_name: endpoint_name,
152
+ endpoint_arn: response.endpoint_arn,
153
+ status: response.endpoint_status,
154
+ creation_time: response.creation_time,
155
+ last_modified_time: response.last_modified_time,
156
+ }
157
+ end
158
+
159
+ private
160
+
161
+ attr_reader :region, :role_arn, :deploy_config, :stamped_model_name, :endpoint_config_name, :endpoint_name,
162
+ :model_s3_uri, :image_uri
163
+
164
+ def built_in_image_uri
165
+ account = IMAGE_REGISTRY_ACCOUNTS.fetch(region) do
166
+ raise "Unsupported region: #{region}. Set deploy.image_uri to a sagemaker-xgboost image in that region."
167
+ end
168
+ "#{account}.dkr.ecr.#{region}.amazonaws.com/#{IMAGE}"
169
+ end
170
+
171
+ def raise_unless_ecr_image_in_region
172
+ ecr_host = "dkr.ecr.#{region}.amazonaws.com"
173
+ return if image_uri.match?(%r{\A\d{12}\.#{Regexp.escape(ecr_host)}/})
174
+
175
+ raise "deploy.image_uri must be an ECR image in #{region}, on the host <12-digit account>.#{ecr_host} " \
176
+ "(got #{image_uri})"
177
+ end
178
+
179
+ def fetch_endpoint_status
180
+ response = sagemaker_client.describe_endpoint(endpoint_name: endpoint_name)
181
+ [response.endpoint_status, response.failure_reason, response.endpoint_config_name]
182
+ end
183
+
184
+ def raise_if_rolled_back(serving_config_name, reason)
185
+ return if serving_config_name == endpoint_config_name
186
+
187
+ message = "Endpoint '#{endpoint_name}' is serving '#{serving_config_name}' instead of '#{endpoint_config_name}'."
188
+ message += " Reason: #{reason}" unless reason.to_s.empty?
189
+ raise Ltr::DeployError, message
190
+ end
191
+
192
+ def sagemaker_client
193
+ @sagemaker_client ||= Aws::SageMaker::Client.new(region: region)
194
+ end
195
+
196
+ def logger
197
+ Ltr.config.logger
198
+ end
199
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Loads feature lists from SSM.
4
+
5
+ class Ltr::Deploy::SsmFeatureSource
6
+ LOAD_OPTIONS = {
7
+ all_features: :load_all_features,
8
+ feature_store_features: :load_feature_store_features,
9
+ }.freeze
10
+
11
+ def initialize(config, log_prefix:)
12
+ @config = config
13
+ @log_prefix = log_prefix
14
+ end
15
+
16
+ # Loads the feature list for `key` from SSM. The key is `:all_features` or `:feature_store_features`.
17
+ # Raises `KeyError` for any other key, and `RuntimeError` when the list is missing (see `Ltr::Ssm::ParameterPaths.missing_value?`).
18
+ def load(key)
19
+ ssm_data = Ltr::Ssm::Loader.call(config, LOAD_OPTIONS.fetch(key) => true)
20
+ features = ssm_data[key]
21
+
22
+ raise "No #{key} found in SSM data" if Ltr::Ssm::ParameterPaths.missing_value?(key, features)
23
+
24
+ logger.info("[#{log_prefix}] Successfully loaded #{features.length} #{key} from SSM")
25
+ features
26
+ end
27
+
28
+ private
29
+
30
+ attr_reader :config, :log_prefix
31
+
32
+ def logger
33
+ Ltr.config.logger
34
+ end
35
+ end
@@ -0,0 +1,16 @@
1
+ # `lib/ltr/errors`
2
+
3
+ The gem's own exception classes. Each one descends from `Ltr::Error`, so a host app can rescue the gem's own failures with that one class.
4
+
5
+ Not every error the gem raises is one of these. The [Errors](../../../docs/errors.md) guide lists the ones that escape as other classes.
6
+
7
+ ## Files
8
+
9
+ | File | Purpose |
10
+ |---|---|
11
+ | `error.rb` | Base class (`< StandardError`) for the gem's own errors. |
12
+ | `configuration_error.rb` | Raised when the config is invalid (`ConfigValidator`), a `dataset_enricher` class can't be resolved, or a setting a stage needs is missing (for example `deploy.local_path` for `LocalDeployer`). |
13
+ | `invalid_dataset_error.rb` | Raised when a modelling dataset file is missing, has no header, lacks required columns, has a bad value in a typed column, or lacks the splits a role needs. |
14
+ | `deploy_error.rb` | Raised when a SageMaker endpoint update rolls back and the endpoint is `InService` on the old endpoint config. |
15
+ | `sqlite_error.rb` | Raised when the aggregation SQL in `SqliteAggregator` fails. Carries the failing `statement` and `error_code`. |
16
+ | `missing_dependency_error.rb` | Raised when a feature needs an optional gem that is missing from the host app's Gemfile or is outside its version limits. The message gives the Gemfile line to add. |
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Raised when the config is invalid.
4
+
5
+ class Ltr::ConfigurationError < Ltr::Error; end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Raised when a SageMaker endpoint reports `Failed` or an unexpected status. Also raised if the endpoint is `InService` on a different config or the wait times out.
4
+
5
+ class Ltr::DeployError < Ltr::Error; end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Base class for all errors raised by the gem.
4
+
5
+ class Ltr::Error < StandardError; end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Raised when the dataset is missing or malformed.
4
+
5
+ class Ltr::InvalidDatasetError < Ltr::Error; end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Raised when a feature needs a gem that is missing from the host app's Gemfile or is outside its version limits.
4
+
5
+ class Ltr::MissingDependencyError < Ltr::Error; end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Raised when a SQLite operation fails.
4
+ # Keeps the failed statement and error code.
5
+
6
+ class Ltr::SqliteError < Ltr::Error
7
+ attr_reader :statement, :error_code
8
+
9
+ def initialize(message, statement: nil, error_code: nil)
10
+ @statement = statement
11
+ @error_code = error_code
12
+ super(message)
13
+ end
14
+ end
@@ -0,0 +1,19 @@
1
+ # `lib/ltr/features`
2
+
3
+ Feature engineering and encoding within the `Ltr::Features` namespace, shared across the training and inference paths. Covers deriving additional features from raw relevance scores, applying per-feature transformations, and one-hot encoding categorical features.
4
+
5
+ ## Subfolders
6
+
7
+ | Folder | Purpose |
8
+ |---|---|
9
+ | `encoders/` | Categorical feature encoding (one-hot encoding of string-valued features). |
10
+
11
+ ## Files
12
+
13
+ | File | Purpose |
14
+ |---|---|
15
+ | `feature_engineering.rb` | Derives rank and relative-score features per query. A missing score gets NaN. `engineer_features` works on an `Ltr::Data::RowStore`. `engineer_features_for_items` works on an inference item list and clamps an infinite score first. |
16
+ | `feature_transformer.rb` | Applies configured `log1p`, `sqrt` and `z_score` steps to an `Ltr::Data::RowStore` before training. Its `z_score` mean and std skip `NaN`. It keeps the steps it applied. |
17
+ | `float32_range.rb` | Clamps a number to plus or minus the float32 maximum. `NaN` and `nil` stay as they are. Serving uses it so an infinite or too large value is scored, because XGBoost rejects an infinity in the matrix. |
18
+ | `transform_steps.rb` | Applies saved transform steps to one value. `FeatureTransformer` and `LocalReranker` both use it, and the Python scorer mirrors it. |
19
+ | `transform_store.rb` | Manages the [`.serving.json` file](../../../docs/model-files.md#dataset-serving-file) next to the modelling dataset. Copies the transform steps and one-hot column names into the model file as attributes. The file can also hold `fallback_feature_totals`, the values for documents with no train rows. |
@@ -0,0 +1,10 @@
1
+ # `lib/ltr/features/encoders`
2
+
3
+ Categorical feature encoders within the `Ltr::Features` namespace, used to turn non-numeric feature columns into a numeric representation the model can consume.
4
+
5
+ ## Files
6
+
7
+ | File | Purpose |
8
+ |---|---|
9
+ | `feature_encoder.rb` | One-hot encodes string-valued categorical features, replacing each string column with 0/1 indicator columns per distinct value. |
10
+ | `enriched_column_encoder.rb` | Runs `FeatureEncoder` on the text columns that a dataset enricher added, and leaves the build columns such as `split` alone. The pipeline calls it after the enricher. |
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ # One-hot encodes the text columns an enricher added to the dataset.
4
+
5
+ class Ltr::Features::EnrichedColumnEncoder
6
+ extend Ltr::Callable
7
+
8
+ WARN_DISTINCT_VALUES = 10
9
+ MAX_DISTINCT_VALUES = 100
10
+
11
+ Context = Struct.new(:doc_id_field, :one_hot_columns)
12
+
13
+ def initialize(dataset, base_columns:, doc_id_field:)
14
+ @dataset = dataset
15
+ @base_columns = base_columns
16
+ @doc_id_field = doc_id_field
17
+ end
18
+
19
+ # Encodes each text column that is not in `base_columns` with `FeatureEncoder`, so the build columns such as `split` stay as they are.
20
+ # Replaces each text column with one int 0 or 1 column per value, named `<column>_<value>`. A nil gives 0 in every flag.
21
+ # Logs at info how many flags each text column becomes. Logs a warning when a column has `WARN_DISTINCT_VALUES` or more distinct values.
22
+ # Updates the dataset in place and returns `[dataset, flag_names]`. The names are empty when there is no text column.
23
+ # Raises `ArgumentError` if a text column has `MAX_DISTINCT_VALUES` or more distinct values, or if a flag has the name of a dataset column, or if two columns give the same flag name.
24
+ def call
25
+ text_columns = (dataset.keys - base_columns).select { |column| dataset[column].type == :object }
26
+ return [dataset, []] if text_columns.empty?
27
+
28
+ distinct_counts = distinct_value_counts(text_columns)
29
+ validate_counts!(distinct_counts)
30
+ log_flag_counts(distinct_counts)
31
+ context = Context.new(doc_id_field, [])
32
+ store = Ltr::Data::RowStore.from_rows(dataset[text_columns].to_a)
33
+ Ltr::Features::FeatureEncoder.new(context).call(store)
34
+ names = context.one_hot_columns
35
+ validate_names!(names)
36
+
37
+ text_columns.each { |column| dataset.delete(column) }
38
+ names.each { |name| dataset[name] = Rover::Vector.new(store.pluck(name.to_sym), type: :int) }
39
+ [dataset, names]
40
+ end
41
+
42
+ private
43
+
44
+ attr_reader :dataset, :base_columns, :doc_id_field
45
+
46
+ def distinct_value_counts(text_columns)
47
+ text_columns.index_with { |column| dataset[column].to_a.reject(&:blank?).uniq.size }
48
+ end
49
+
50
+ def validate_counts!(distinct_counts)
51
+ distinct_counts.each do |column, count|
52
+ next if count < MAX_DISTINCT_VALUES
53
+
54
+ raise ArgumentError,
55
+ "Enricher text column '#{column}' has #{count} distinct values, which is #{MAX_DISTINCT_VALUES} or more. Drop the column or bucket its values into fewer categories."
56
+ end
57
+ end
58
+
59
+ def log_flag_counts(distinct_counts)
60
+ distinct_counts.each do |column, count|
61
+ logger.warn("EnrichedColumnEncoder: column '#{column}' has #{count} distinct values and becomes #{count} flags. Consider bucketing its values into fewer categories.") if count >= WARN_DISTINCT_VALUES
62
+ logger.info("EnrichedColumnEncoder: column '#{column}' becomes #{count} #{"flag".pluralize(count)}")
63
+ end
64
+ end
65
+
66
+ def logger
67
+ Ltr.config.logger
68
+ end
69
+
70
+ def validate_names!(names)
71
+ duplicated = names.tally.select { |_name, count| count > 1 }.keys
72
+ clashing = names & dataset.keys
73
+ return if (duplicated + clashing).empty?
74
+
75
+ raise ArgumentError, "Enricher text columns would give flag columns that already exist: #{(duplicated + clashing).uniq.join(", ")}"
76
+ end
77
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Replaces each string feature with one 0 or 1 column per value.
4
+
5
+ # Turns string features into 0 or 1 columns so XGBoost can read them.
6
+ class Ltr::Features::FeatureEncoder
7
+ # Takes the context that supplies `doc_id_field`.
8
+ def initialize(context)
9
+ @context = context
10
+ end
11
+
12
+ # A column can be encoded if all its non-nil values are strings and at least one is not `"NaN"`.
13
+ # Encoding adds one `<name>_<value>` column per distinct non-blank value.
14
+ # Adds the new column names to `context.one_hot_columns`.
15
+ # Skips `user_query`, the document ID column and `qid`.
16
+ # Updates and returns the given `RowStore`.
17
+ # Raises `Ltr::InvalidDatasetError` if a column mixes a string other than `"NaN"` with a non-string value other than nil.
18
+ def call(aggregated_data)
19
+ skipped = [:user_query, context.doc_id_field.to_sym, :qid]
20
+ (aggregated_data.keys - skipped).each do |key|
21
+ values = aggregated_data.pluck(key)
22
+ encode_feature(aggregated_data, key, values) if string_column?(key, values)
23
+ end
24
+ aggregated_data
25
+ end
26
+
27
+ private
28
+
29
+ attr_reader :context
30
+
31
+ def string_column?(key, values)
32
+ present = values.compact
33
+ return false unless present.any? { |value| value.is_a?(String) && value != Ltr::Data::Csv::NAN_TOKEN }
34
+ return true if present.all?(String)
35
+
36
+ raise Ltr::InvalidDatasetError, "Column '#{key}' mixes text with other values, so it can't be one-hot encoded or read as a number"
37
+ end
38
+
39
+ def encode_feature(aggregated_data, feature_name, encoded_values)
40
+ value_counts = count_feature_values(encoded_values)
41
+ return aggregated_data if value_counts.empty?
42
+
43
+ all_values = value_counts.keys
44
+ aggregated_data.delete_column(feature_name)
45
+
46
+ all_values.each do |value|
47
+ encoded_feature_name = :"#{feature_name}_#{value}"
48
+ context.one_hot_columns << encoded_feature_name.to_s
49
+ aggregated_data.set_column(
50
+ encoded_feature_name,
51
+ encoded_values.map { |feature_value| (feature_value == value) ? 1 : 0 }
52
+ )
53
+ end
54
+ end
55
+
56
+ def count_feature_values(values)
57
+ values.each_with_object(Hash.new(0)) do |value, counts|
58
+ counts[value] += 1 if value.present?
59
+ end
60
+ end
61
+ end