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,371 @@
|
|
|
1
|
+
# Handlers that load the XGBoost ranker on SageMaker and score items with engineered features.
|
|
2
|
+
# The SageMaker XGBoost container calls `model_fn` once and `transform_fn` for each request.
|
|
3
|
+
|
|
4
|
+
from json import dumps, load, loads
|
|
5
|
+
from math import isnan, log, sqrt
|
|
6
|
+
from os.path import join
|
|
7
|
+
from time import perf_counter
|
|
8
|
+
|
|
9
|
+
import xgboost
|
|
10
|
+
from numpy import array, finfo, nan
|
|
11
|
+
from sagemaker_containers.beta.framework import worker
|
|
12
|
+
from xgboost import Booster, DMatrix
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
AVAILABLE_METHODS = ["rank", "relative_score"]
|
|
16
|
+
BM25_FEATURE_PREFIX = "bm25_"
|
|
17
|
+
ADDITIONAL_ENGINEERED_FEATURES = ["relevancy"]
|
|
18
|
+
FEATURE_ENGINEERING_EXCLUDED = ["bm25_fields_matched"]
|
|
19
|
+
FLOAT32_MAX = float(finfo("float32").max)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BadRequestError(ValueError):
|
|
23
|
+
"""
|
|
24
|
+
Bad input from the client. `transform_fn` answers it with HTTP 400. Any other exception becomes a 500 in the container.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def model_fn(model_dir):
|
|
29
|
+
"""
|
|
30
|
+
Load the XGBoost ranker with the feature transforms and one-hot column names stored in the model file. Load the feature list and, if present, the feature store from code/.
|
|
31
|
+
"""
|
|
32
|
+
model_path = join(model_dir, "xgboost-model.ubj")
|
|
33
|
+
features_path = join(model_dir, "code", "features.json")
|
|
34
|
+
feature_store_path = join(model_dir, "code", "feature_store.json")
|
|
35
|
+
|
|
36
|
+
print(f"model_fn: loading the model with xgboost {xgboost.__version__}", flush=True)
|
|
37
|
+
booster = Booster()
|
|
38
|
+
booster.load_model(model_path)
|
|
39
|
+
|
|
40
|
+
with open(features_path, "r") as f:
|
|
41
|
+
features = load(f)
|
|
42
|
+
|
|
43
|
+
feature_transforms = loads(booster.attr("feature_transforms") or "[]")
|
|
44
|
+
one_hot_columns = loads(booster.attr("one_hot_columns") or "[]")
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
with open(feature_store_path, "r") as f:
|
|
48
|
+
feature_store = load(f)
|
|
49
|
+
except FileNotFoundError:
|
|
50
|
+
feature_store = {}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
"model": booster,
|
|
54
|
+
"features": features,
|
|
55
|
+
"feature_transforms": feature_transforms,
|
|
56
|
+
"one_hot_columns": one_hot_columns,
|
|
57
|
+
"feature_store": feature_store,
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def transform_fn(model_assets, request_body, content_type, accept):
|
|
62
|
+
"""
|
|
63
|
+
Answer one request. Bad input gets an HTTP 400 response with the message as JSON.
|
|
64
|
+
|
|
65
|
+
The container ignores a status on an exception and answers 500 for any exception.
|
|
66
|
+
So only BadRequestError is caught here. A bug of ours still reaches the container as a 500.
|
|
67
|
+
The container also refuses a module that defines `transform_fn` next to `input_fn`, `predict_fn` or `output_fn`.
|
|
68
|
+
That is why the three steps below are private.
|
|
69
|
+
"""
|
|
70
|
+
try:
|
|
71
|
+
_check_accept(accept)
|
|
72
|
+
body = dumps(_predict(_parse_input(request_body, content_type), model_assets))
|
|
73
|
+
except BadRequestError as error:
|
|
74
|
+
return worker.Response(response=dumps({"error": str(error)}), status=400, mimetype="application/json")
|
|
75
|
+
return worker.Response(response=body, mimetype="application/json")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _parse_input(request_body, content_type):
|
|
79
|
+
"""
|
|
80
|
+
Parse incoming JSON request and return the raw payload.
|
|
81
|
+
|
|
82
|
+
Raises BadRequestError (HTTP 400) for a body that is not JSON, a payload or item of the wrong shape,
|
|
83
|
+
an item without an `id` or with a null `id`, a field without a string `name`, and a field whose value is a boolean, because a boolean is not a feature value.
|
|
84
|
+
"""
|
|
85
|
+
if content_type != "application/json":
|
|
86
|
+
raise BadRequestError(f"Unsupported content type: {content_type}")
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
payload = loads(request_body)
|
|
90
|
+
except ValueError as error:
|
|
91
|
+
raise BadRequestError(f"Request body is not valid JSON: {error}") from error
|
|
92
|
+
|
|
93
|
+
if not isinstance(payload, dict) or "items" not in payload:
|
|
94
|
+
raise BadRequestError("Missing 'items' in request payload")
|
|
95
|
+
if not isinstance(payload["items"], list):
|
|
96
|
+
raise BadRequestError("'items' must be a list")
|
|
97
|
+
|
|
98
|
+
for item in payload["items"]:
|
|
99
|
+
_validate_item(item)
|
|
100
|
+
|
|
101
|
+
return payload
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _validate_item(item):
|
|
105
|
+
if not isinstance(item, dict):
|
|
106
|
+
raise BadRequestError("Each item must be an object")
|
|
107
|
+
if item.get("id") is None:
|
|
108
|
+
raise BadRequestError("Each item needs an 'id'")
|
|
109
|
+
|
|
110
|
+
if item.get("fields") is not None and not isinstance(item["fields"], list):
|
|
111
|
+
raise BadRequestError(f"'fields' of item {item['id']} must be a list")
|
|
112
|
+
|
|
113
|
+
for field in item.get("fields") or []:
|
|
114
|
+
if not isinstance(field, dict) or not isinstance(field.get("name"), str):
|
|
115
|
+
raise BadRequestError(f"Each field of item {item['id']} must be an object with a string 'name'")
|
|
116
|
+
if isinstance(field.get("value"), bool):
|
|
117
|
+
raise BadRequestError(f"Field {field['name']} of item {item['id']} is a boolean. Send a number.")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _predict(input_data, model_assets):
|
|
121
|
+
"""
|
|
122
|
+
Transform input into DMatrix and predict using the booster.
|
|
123
|
+
|
|
124
|
+
Uses the model's expected feature names to ensure correct ordering.
|
|
125
|
+
Missing features are filled with NaN, except one-hot columns, which get the transformed value of 0.
|
|
126
|
+
"""
|
|
127
|
+
t0 = perf_counter()
|
|
128
|
+
booster = model_assets["model"]
|
|
129
|
+
feature_store = model_assets["feature_store"]
|
|
130
|
+
|
|
131
|
+
feature_names = booster.feature_names or model_assets["features"]
|
|
132
|
+
items = input_data["items"]
|
|
133
|
+
|
|
134
|
+
if not items:
|
|
135
|
+
return {"items": [], "took_seconds": perf_counter() - t0}
|
|
136
|
+
|
|
137
|
+
apply_feature_engineering(items, feature_names)
|
|
138
|
+
|
|
139
|
+
item_features, item_ids = to_feature_matrix(
|
|
140
|
+
items,
|
|
141
|
+
feature_names,
|
|
142
|
+
feature_store,
|
|
143
|
+
feature_transforms=model_assets["feature_transforms"],
|
|
144
|
+
one_hot_columns=model_assets["one_hot_columns"],
|
|
145
|
+
)
|
|
146
|
+
dmatrix = DMatrix(item_features, feature_names=feature_names)
|
|
147
|
+
pred = booster.predict(dmatrix)
|
|
148
|
+
|
|
149
|
+
results = sorted(
|
|
150
|
+
({"item": str(iid), "score": float(scr)} for iid, scr in zip(item_ids, pred)),
|
|
151
|
+
key=lambda d: d["score"],
|
|
152
|
+
reverse=True,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
took = perf_counter() - t0
|
|
156
|
+
|
|
157
|
+
return {"items": results, "took_seconds": took}
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def to_feature_matrix(items, feature_names, feature_store, feature_transforms, dtype="float32", one_hot_columns=()):
|
|
161
|
+
"""
|
|
162
|
+
Build a 2D numpy array (rows = items, cols = feature_names)
|
|
163
|
+
and the corresponding item_ids list.
|
|
164
|
+
|
|
165
|
+
Features are extracted in the exact order specified by feature_names.
|
|
166
|
+
Missing features are filled with NaN, which XGBoost handles as missing values.
|
|
167
|
+
A one-hot column missing from both the request and the feature store is filled with
|
|
168
|
+
the transformed raw 0, which is what training saw for that flag.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
items: List of items with fields
|
|
172
|
+
feature_names: List of feature names to extract (typically from model.feature_names)
|
|
173
|
+
feature_store: Dict in format {feature_name: {item_id: value}}
|
|
174
|
+
Note: item_id keys are always strings
|
|
175
|
+
dtype: Data type for numpy array
|
|
176
|
+
feature_transforms: Steps saved at training, applied to every value the request sends.
|
|
177
|
+
Feature store values are already on the training scale, so they are not transformed.
|
|
178
|
+
one_hot_columns: Names of the columns that training one-hot encoded.
|
|
179
|
+
"""
|
|
180
|
+
features_in_store = set(feature_store.keys())
|
|
181
|
+
one_hot_names = set(one_hot_columns)
|
|
182
|
+
|
|
183
|
+
rows = []
|
|
184
|
+
item_ids = []
|
|
185
|
+
|
|
186
|
+
for item in items:
|
|
187
|
+
item_id = str(item["id"])
|
|
188
|
+
field_dict = {feature["name"]: feature.get("value") for feature in item.get("fields") or []}
|
|
189
|
+
|
|
190
|
+
feature_row = []
|
|
191
|
+
for feature_name in feature_names:
|
|
192
|
+
value = field_dict.get(feature_name)
|
|
193
|
+
if value is not None:
|
|
194
|
+
value = _to_number(value, feature_name, item_id)
|
|
195
|
+
value = apply_feature_transforms(feature_transforms, feature_name, value)
|
|
196
|
+
|
|
197
|
+
if (value is None) and (feature_name in features_in_store):
|
|
198
|
+
value = feature_store[feature_name].get(item_id)
|
|
199
|
+
|
|
200
|
+
if value is None:
|
|
201
|
+
value = apply_feature_transforms(feature_transforms, feature_name, 0) if feature_name in one_hot_names else nan
|
|
202
|
+
|
|
203
|
+
feature_row.append(_clamp_to_float32(value))
|
|
204
|
+
|
|
205
|
+
rows.append(feature_row)
|
|
206
|
+
item_ids.append(item_id)
|
|
207
|
+
|
|
208
|
+
return array(rows, dtype=dtype), item_ids
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _to_number(value, feature_name, item_id):
|
|
212
|
+
"""
|
|
213
|
+
Return a float for a number or numeric string, or raise BadRequestError.
|
|
214
|
+
|
|
215
|
+
An infinity or a number past the float32 range is clamped to plus or minus FLOAT32_MAX,
|
|
216
|
+
because XGBoost rejects an infinity in the float32 matrix. A NaN returns None, so it is
|
|
217
|
+
missing like null and takes the feature store value or the one-hot 0.
|
|
218
|
+
Only a value that is not a number is rejected.
|
|
219
|
+
"""
|
|
220
|
+
if isinstance(value, (int, float, str)):
|
|
221
|
+
try:
|
|
222
|
+
number = float(value)
|
|
223
|
+
return None if isnan(number) else _clamp_to_float32(number)
|
|
224
|
+
except OverflowError:
|
|
225
|
+
return FLOAT32_MAX if value > 0 else -FLOAT32_MAX
|
|
226
|
+
except ValueError:
|
|
227
|
+
pass
|
|
228
|
+
raise BadRequestError(f"Field {feature_name} of item {item_id} is not a number: {str(value)[:50]!r}")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _clamp_to_float32(value):
|
|
232
|
+
"""Return value limited to the float32 range. NaN and non-numbers are returned as they are."""
|
|
233
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or isnan(value):
|
|
234
|
+
return value
|
|
235
|
+
return max(-FLOAT32_MAX, min(FLOAT32_MAX, value))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def apply_feature_transforms(feature_transforms, feature_name, value):
|
|
239
|
+
"""
|
|
240
|
+
Apply the transform steps saved at training to one request value.
|
|
241
|
+
|
|
242
|
+
Steps for the feature run in saved order. Values that are not numbers are
|
|
243
|
+
returned as they are, as in training.
|
|
244
|
+
"""
|
|
245
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
246
|
+
return value
|
|
247
|
+
|
|
248
|
+
for step in feature_transforms:
|
|
249
|
+
if step["feature"] == feature_name:
|
|
250
|
+
value = _apply_transform_step(step, value)
|
|
251
|
+
return value
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _apply_transform_step(step, value):
|
|
255
|
+
"""Apply one step. log1p and sqrt leave negative values as they are."""
|
|
256
|
+
transform = step["transform"]
|
|
257
|
+
if transform == "log1p":
|
|
258
|
+
return log(value + 1) if value >= 0 else value
|
|
259
|
+
if transform == "sqrt":
|
|
260
|
+
return sqrt(value) if value >= 0 else value
|
|
261
|
+
if transform == "z_score":
|
|
262
|
+
if isnan(value):
|
|
263
|
+
return value
|
|
264
|
+
return 0.0 if step["std"] == 0 else (value - step["mean"]) / step["std"]
|
|
265
|
+
raise ValueError(f"Unknown feature transformation: {transform}.")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def apply_feature_engineering(items, feature_names):
|
|
269
|
+
"""
|
|
270
|
+
Apply feature engineering to items in-place.
|
|
271
|
+
|
|
272
|
+
Detects which derived features are needed by inspecting feature_names.
|
|
273
|
+
For example, if 'bm25_name_rank' is in feature_names, computes the rank
|
|
274
|
+
of each item's bm25_name score across all items.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
items: List of items with 'fields' containing {name, value} dicts
|
|
278
|
+
feature_names: List of all expected feature names
|
|
279
|
+
"""
|
|
280
|
+
feature_engineering_map = _detect_engineering_from_feature_names(feature_names)
|
|
281
|
+
if not feature_engineering_map:
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
field_lookups = [
|
|
285
|
+
{f["name"]: f.get("value") for f in item.get("fields") or []}
|
|
286
|
+
for item in items
|
|
287
|
+
]
|
|
288
|
+
|
|
289
|
+
fields_to_extend = [(index, item["fields"]) for index, item in enumerate(items) if item.get("fields") is not None]
|
|
290
|
+
|
|
291
|
+
for base_feature, feature_engineering_methods in feature_engineering_map.items():
|
|
292
|
+
scores = [_read_score(lookup.get(base_feature), base_feature, item["id"]) for lookup, item in zip(field_lookups, items)]
|
|
293
|
+
|
|
294
|
+
for method in feature_engineering_methods:
|
|
295
|
+
feature_engineering_scores = _compute_method(method, scores)
|
|
296
|
+
|
|
297
|
+
for index, fields in fields_to_extend:
|
|
298
|
+
fields.append({"name": f"{base_feature}_{method}", "value": feature_engineering_scores[index]})
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _read_score(value, feature_name, item_id):
|
|
302
|
+
"""Return the score as a number. A missing score or a NaN score is None, which later becomes NaN."""
|
|
303
|
+
return None if value is None else _to_number(value, feature_name, item_id)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _detect_engineering_from_feature_names(feature_names):
|
|
307
|
+
"""
|
|
308
|
+
Detect which feature engineering is needed from feature names.
|
|
309
|
+
|
|
310
|
+
Covers the BM25 score columns and the extra score columns named in
|
|
311
|
+
ADDITIONAL_ENGINEERED_FEATURES, minus the columns in
|
|
312
|
+
FEATURE_ENGINEERING_EXCLUDED. Returns a dict mapping base feature names to
|
|
313
|
+
lists of methods, for example {'bm25_name': ['rank', 'relative_score']}.
|
|
314
|
+
"""
|
|
315
|
+
engineering_map = {}
|
|
316
|
+
for name in feature_names:
|
|
317
|
+
for method in AVAILABLE_METHODS:
|
|
318
|
+
suffix = f"_{method}"
|
|
319
|
+
if name.endswith(suffix):
|
|
320
|
+
base_name = name[: -len(suffix)]
|
|
321
|
+
if base_name in FEATURE_ENGINEERING_EXCLUDED:
|
|
322
|
+
continue
|
|
323
|
+
if base_name.startswith(BM25_FEATURE_PREFIX) or base_name in ADDITIONAL_ENGINEERED_FEATURES:
|
|
324
|
+
engineering_map.setdefault(base_name, []).append(method)
|
|
325
|
+
return engineering_map
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _compute_method(method, scores):
|
|
329
|
+
"""Compute derived values for a given engineering method."""
|
|
330
|
+
return {"rank": _compute_rank, "relative_score": _compute_relative_score}[method](scores)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _compute_rank(scores):
|
|
334
|
+
"""Compute rank (1-based, descending) for each score.
|
|
335
|
+
|
|
336
|
+
Equal scores share the lowest rank they span (1, 2, 2, 4), so the result is
|
|
337
|
+
independent of the input order and matches the Ruby implementation exactly.
|
|
338
|
+
Scores that are zero or negative are assigned rank -1 (unranked).
|
|
339
|
+
A missing score (None) gets NaN and does not change the other ranks.
|
|
340
|
+
"""
|
|
341
|
+
descending = sorted((score for score in scores if score is not None and score > 0.0), reverse=True)
|
|
342
|
+
|
|
343
|
+
rank_by_score = {}
|
|
344
|
+
for index, score in enumerate(descending):
|
|
345
|
+
rank_by_score.setdefault(score, index + 1)
|
|
346
|
+
|
|
347
|
+
return [
|
|
348
|
+
nan if score is None else float(rank_by_score[score]) if score > 0.0 else -1.0
|
|
349
|
+
for score in scores
|
|
350
|
+
]
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _compute_relative_score(scores):
|
|
354
|
+
"""Compute relative score (score / max_score) for each score.
|
|
355
|
+
|
|
356
|
+
The largest present score is the divisor. A missing score (None) gets NaN.
|
|
357
|
+
"""
|
|
358
|
+
present = [score for score in scores if score is not None]
|
|
359
|
+
max_score = max(present) if present else 0.0
|
|
360
|
+
return [
|
|
361
|
+
nan if score is None else 0.0 if max_score <= 0.0 else round(score / max_score, 3)
|
|
362
|
+
for score in scores
|
|
363
|
+
]
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _check_accept(accept):
|
|
367
|
+
"""
|
|
368
|
+
A missing, empty or `*/*` accept means JSON. Raises BadRequestError for any other accept type.
|
|
369
|
+
"""
|
|
370
|
+
if accept not in (None, "", "*/*", "application/json"):
|
|
371
|
+
raise BadRequestError(f"Unsupported accept type: {accept}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
xgboost==3.2.0
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Reads the modelling dataset and returns the feature values for each document.
|
|
4
|
+
|
|
5
|
+
class Ltr::Deploy::FeatureExtractor
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config, features)
|
|
9
|
+
@config = config
|
|
10
|
+
@features = features
|
|
11
|
+
@dataset_path = config.modelling_dataset_path
|
|
12
|
+
@doc_id_field = config.doc_id_field
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# Returns a hash of doc id to a hash of feature values from the modelling dataset.
|
|
16
|
+
# Nil, empty and `NaN` values are skipped. Numeric strings become floats and other strings stay strings.
|
|
17
|
+
# A repeated doc id keeps its first row that has a usable value. A doc with no usable value is left out.
|
|
18
|
+
# Raises `ArgumentError` for blank features or a missing `training.modelling_dataset_path`. Raises `RuntimeError` when the CSV lacks a needed column.
|
|
19
|
+
def call
|
|
20
|
+
validate_input!
|
|
21
|
+
get_doc_features
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
private
|
|
25
|
+
|
|
26
|
+
attr_reader :config, :features, :dataset_path, :doc_id_field
|
|
27
|
+
|
|
28
|
+
def validate_input!
|
|
29
|
+
raise ArgumentError, "Features cannot be empty" if features.blank?
|
|
30
|
+
raise ArgumentError, "Missing modelling_dataset_path in config" unless dataset_path
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def get_doc_features
|
|
34
|
+
rows, headers = load_and_parse_csv
|
|
35
|
+
return {} if rows.empty?
|
|
36
|
+
|
|
37
|
+
validate_csv_headers!(headers, [doc_id_field] + features)
|
|
38
|
+
|
|
39
|
+
rows.each_with_object({}) do |row, doc_features|
|
|
40
|
+
doc_id = get_valid_doc_id(row)
|
|
41
|
+
next if doc_id.nil? || doc_features.key?(doc_id)
|
|
42
|
+
|
|
43
|
+
feature_values = extract_feature_values(row)
|
|
44
|
+
doc_features[doc_id] = feature_values unless feature_values.empty?
|
|
45
|
+
end
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def load_and_parse_csv
|
|
49
|
+
df = Ltr::Data::Csv.read(config)
|
|
50
|
+
rows = df.to_a
|
|
51
|
+
headers = df.keys
|
|
52
|
+
[rows, headers]
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def validate_csv_headers!(headers, required_columns)
|
|
56
|
+
missing_columns = required_columns - headers
|
|
57
|
+
raise "Missing required columns in CSV: #{missing_columns.join(", ")}" if missing_columns.any?
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def get_valid_doc_id(row)
|
|
61
|
+
doc_id_value = row[doc_id_field]
|
|
62
|
+
return nil if doc_id_value.nil?
|
|
63
|
+
|
|
64
|
+
doc_id = doc_id_value.to_s.strip
|
|
65
|
+
return nil if doc_id.empty?
|
|
66
|
+
|
|
67
|
+
doc_id
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def extract_feature_values(row)
|
|
71
|
+
feature_values = {}
|
|
72
|
+
|
|
73
|
+
features.each do |feature_name|
|
|
74
|
+
value_raw = row[feature_name]
|
|
75
|
+
next if value_raw.nil?
|
|
76
|
+
|
|
77
|
+
value_str = value_raw.to_s.strip
|
|
78
|
+
next if value_str.empty? || value_str == "NaN"
|
|
79
|
+
|
|
80
|
+
parsed_value = parse_value(value_str)
|
|
81
|
+
feature_values[feature_name] = parsed_value unless parsed_value.nil?
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
feature_values
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
def parse_value(value_str)
|
|
88
|
+
if value_str.match?(/\A-?\d*\.?\d+([eE][+-]?\d+)?\z/)
|
|
89
|
+
value_str.to_f
|
|
90
|
+
else
|
|
91
|
+
value_str
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Builds the feature store in memory for the local model file and the SageMaker model archive.
|
|
4
|
+
|
|
5
|
+
class Ltr::Deploy::FeatureStoreDeployer
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def self.for_deployment(config, dataset:)
|
|
9
|
+
return unless config.feature_store&.dig("include_in_deployment") == true
|
|
10
|
+
|
|
11
|
+
Ltr.config.logger.info("[FeatureStoreDeployer] Building feature store data for deployment")
|
|
12
|
+
call(config, dataset: dataset)
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
def initialize(config, dataset:)
|
|
16
|
+
@config = config
|
|
17
|
+
@dataset = dataset
|
|
18
|
+
@feature_store_config = config.feature_store
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# Builds a hash of feature name to doc id to value.
|
|
22
|
+
# The features come from SSM when `ssm.enabled` is true, else from `feature_store.features`.
|
|
23
|
+
# A doc with no value in the dataset gets its value from the fallback totals in the serving file, when it has one.
|
|
24
|
+
# Returns `nil` when that list is empty, because there is nothing to store.
|
|
25
|
+
# On an error it reports the error and raises it again.
|
|
26
|
+
def call
|
|
27
|
+
validate_input!
|
|
28
|
+
generate_feature_store_data
|
|
29
|
+
rescue => error
|
|
30
|
+
logger.error("FeatureStoreDeployer failed: #{error.message}")
|
|
31
|
+
logger.error(error.backtrace.join("\n")) if error.backtrace
|
|
32
|
+
Ltr.config.report_error(error, message: "Error while deploying feature store data")
|
|
33
|
+
raise
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
private
|
|
37
|
+
|
|
38
|
+
attr_reader :config, :feature_store_config, :dataset
|
|
39
|
+
|
|
40
|
+
def validate_input!
|
|
41
|
+
raise "Missing feature_store config fields: features" if Ltr::Ssm::ParameterPaths.missing_value?(:feature_store_features, feature_store_config["features"])
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def generate_feature_store_data
|
|
45
|
+
inference_features = load_inference_features
|
|
46
|
+
|
|
47
|
+
if inference_features.empty?
|
|
48
|
+
logger.info("[FeatureStoreDeployer] No feature store features were selected, so the model is deployed without a feature store")
|
|
49
|
+
return
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
product_features = Ltr::Deploy::FeatureExtractor.call(config, inference_features)
|
|
53
|
+
feature_store_data = inference_features.index_with { {} }
|
|
54
|
+
|
|
55
|
+
product_features.each do |product_id, features|
|
|
56
|
+
features.each do |feature_name, value|
|
|
57
|
+
feature_store_data[feature_name][product_id] = value
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
fill_from_fallback_totals(feature_store_data)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def fill_from_fallback_totals(feature_store_data)
|
|
65
|
+
dataset.fetch(Ltr::Features::TransformStore::FALLBACK_FEATURE_TOTALS_KEY.to_s, {}).each do |doc_id, totals|
|
|
66
|
+
totals.slice(*feature_store_data.keys).each do |feature_name, value|
|
|
67
|
+
feature_store_data[feature_name][doc_id] = value unless feature_store_data[feature_name].key?(doc_id)
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
feature_store_data
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def load_inference_features
|
|
75
|
+
return feature_store_config["features"] unless config.ssm_enabled?
|
|
76
|
+
|
|
77
|
+
logger.info("[FeatureStoreDeployer] Loading optimized features from SSM")
|
|
78
|
+
ssm_feature_source.load(:feature_store_features)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def ssm_feature_source
|
|
82
|
+
@ssm_feature_source ||= Ltr::Deploy::SsmFeatureSource.new(config, log_prefix: "FeatureStoreDeployer")
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def logger
|
|
86
|
+
Ltr.config.logger
|
|
87
|
+
end
|
|
88
|
+
end
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Saves the trained model to a local file path.
|
|
4
|
+
|
|
5
|
+
class Ltr::Deploy::LocalDeployer
|
|
6
|
+
extend Ltr::Callable
|
|
7
|
+
|
|
8
|
+
def initialize(config:, booster:)
|
|
9
|
+
@config = config
|
|
10
|
+
@booster = booster
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# Saves the model to `deploy.local_path` and returns `{ path: }`. A relative path starts at `Ltr.config.root`.
|
|
14
|
+
# The feature transform steps and the one-hot column names from training are stored in the model file.
|
|
15
|
+
# So is the feature store, when `feature_store.include_in_deployment` is `true`.
|
|
16
|
+
# The feature store is removed from the booster after the save, so a SageMaker deploy of the same booster does not carry it.
|
|
17
|
+
# It writes a temp file and renames it, so a reader never sees a half-written model.
|
|
18
|
+
# Raises `Ltr::ConfigurationError` if `deploy.local` is not `true` or `deploy.local_path` is blank.
|
|
19
|
+
# The same error is raised if the local `.serving.json` is missing or S3 returns `NoSuchKey` for it.
|
|
20
|
+
def call
|
|
21
|
+
validate!
|
|
22
|
+
path = config.local_deploy_path
|
|
23
|
+
FileUtils.mkdir_p(File.dirname(path))
|
|
24
|
+
dataset = Ltr::Features::TransformStore.read_dataset(config)
|
|
25
|
+
Ltr::Features::TransformStore.write_model_attributes(booster, config, dataset)
|
|
26
|
+
Ltr::Features::TransformStore.write_model_feature_store(booster, Ltr::Deploy::FeatureStoreDeployer.for_deployment(config, dataset: dataset))
|
|
27
|
+
save_atomically(path)
|
|
28
|
+
logger.info("Model saved locally to #{path}")
|
|
29
|
+
|
|
30
|
+
{ path: path }
|
|
31
|
+
ensure
|
|
32
|
+
Ltr::Features::TransformStore.write_model_feature_store(booster, nil)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
private
|
|
36
|
+
|
|
37
|
+
attr_reader :config, :booster
|
|
38
|
+
|
|
39
|
+
def save_atomically(path)
|
|
40
|
+
extension = File.extname(path)
|
|
41
|
+
temp_path = File.join(File.dirname(path), "#{File.basename(path, extension)}.#{SecureRandom.hex(8)}.tmp#{extension}")
|
|
42
|
+
booster.save_model(temp_path)
|
|
43
|
+
File.rename(temp_path, path)
|
|
44
|
+
ensure
|
|
45
|
+
FileUtils.rm_f(temp_path) if temp_path
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def validate!
|
|
49
|
+
unless config.local_deploy_enabled?
|
|
50
|
+
raise Ltr::ConfigurationError, "deploy.local must be true to save a model locally"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
if config.local_deploy_path.blank?
|
|
54
|
+
raise Ltr::ConfigurationError, "deploy.local_path is required when deploy.local is true"
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def logger
|
|
59
|
+
Ltr.config.logger
|
|
60
|
+
end
|
|
61
|
+
end
|