kumoai 2.13.0.dev202512091732__cp311-cp311-macosx_11_0_arm64.whl → 2.14.0.dev202601051732__cp311-cp311-macosx_11_0_arm64.whl
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.
- kumoai/__init__.py +23 -26
- kumoai/_version.py +1 -1
- kumoai/client/client.py +6 -0
- kumoai/client/jobs.py +24 -0
- kumoai/client/pquery.py +6 -2
- kumoai/connector/utils.py +21 -7
- kumoai/experimental/rfm/__init__.py +51 -24
- kumoai/experimental/rfm/authenticate.py +3 -4
- kumoai/experimental/rfm/backend/local/graph_store.py +52 -104
- kumoai/experimental/rfm/backend/local/sampler.py +125 -55
- kumoai/experimental/rfm/backend/local/table.py +35 -31
- kumoai/experimental/rfm/backend/snow/__init__.py +2 -0
- kumoai/experimental/rfm/backend/snow/sampler.py +297 -0
- kumoai/experimental/rfm/backend/snow/table.py +174 -49
- kumoai/experimental/rfm/backend/sqlite/__init__.py +4 -2
- kumoai/experimental/rfm/backend/sqlite/sampler.py +398 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +131 -48
- kumoai/experimental/rfm/base/__init__.py +21 -5
- kumoai/experimental/rfm/base/column.py +96 -10
- kumoai/experimental/rfm/base/expression.py +44 -0
- kumoai/experimental/rfm/base/sampler.py +422 -35
- kumoai/experimental/rfm/base/source.py +2 -1
- kumoai/experimental/rfm/base/sql_sampler.py +144 -0
- kumoai/experimental/rfm/base/table.py +386 -195
- kumoai/experimental/rfm/graph.py +350 -178
- kumoai/experimental/rfm/infer/__init__.py +6 -4
- kumoai/experimental/rfm/infer/dtype.py +7 -4
- kumoai/experimental/rfm/infer/multicategorical.py +1 -1
- kumoai/experimental/rfm/infer/pkey.py +4 -2
- kumoai/experimental/rfm/infer/stype.py +35 -0
- kumoai/experimental/rfm/infer/time_col.py +1 -2
- kumoai/experimental/rfm/pquery/executor.py +27 -27
- kumoai/experimental/rfm/pquery/pandas_executor.py +29 -31
- kumoai/experimental/rfm/relbench.py +76 -0
- kumoai/experimental/rfm/rfm.py +630 -408
- kumoai/experimental/rfm/sagemaker.py +4 -4
- kumoai/experimental/rfm/task_table.py +290 -0
- kumoai/pquery/predictive_query.py +10 -6
- kumoai/testing/snow.py +50 -0
- kumoai/trainer/distilled_trainer.py +175 -0
- kumoai/utils/__init__.py +3 -2
- kumoai/utils/display.py +51 -0
- kumoai/utils/progress_logger.py +190 -12
- kumoai/utils/sql.py +3 -0
- {kumoai-2.13.0.dev202512091732.dist-info → kumoai-2.14.0.dev202601051732.dist-info}/METADATA +3 -2
- {kumoai-2.13.0.dev202512091732.dist-info → kumoai-2.14.0.dev202601051732.dist-info}/RECORD +49 -40
- kumoai/experimental/rfm/local_graph_sampler.py +0 -223
- kumoai/experimental/rfm/local_pquery_driver.py +0 -689
- {kumoai-2.13.0.dev202512091732.dist-info → kumoai-2.14.0.dev202601051732.dist-info}/WHEEL +0 -0
- {kumoai-2.13.0.dev202512091732.dist-info → kumoai-2.14.0.dev202601051732.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.13.0.dev202512091732.dist-info → kumoai-2.14.0.dev202601051732.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import base64
|
|
2
2
|
import json
|
|
3
|
-
from typing import Any
|
|
3
|
+
from typing import Any
|
|
4
4
|
|
|
5
5
|
import requests
|
|
6
6
|
|
|
@@ -48,8 +48,8 @@ class KumoClient_SageMakerAdapter(KumoClient):
|
|
|
48
48
|
|
|
49
49
|
# Recording buffers.
|
|
50
50
|
self._recording_active = False
|
|
51
|
-
self._recorded_reqs:
|
|
52
|
-
self._recorded_resps:
|
|
51
|
+
self._recorded_reqs: list[dict[str, Any]] = []
|
|
52
|
+
self._recorded_resps: list[dict[str, Any]] = []
|
|
53
53
|
|
|
54
54
|
def authenticate(self) -> None:
|
|
55
55
|
# TODO(siyang): call /ping to verify?
|
|
@@ -92,7 +92,7 @@ class KumoClient_SageMakerAdapter(KumoClient):
|
|
|
92
92
|
self._recorded_reqs.clear()
|
|
93
93
|
self._recorded_resps.clear()
|
|
94
94
|
|
|
95
|
-
def end_recording(self) ->
|
|
95
|
+
def end_recording(self) -> list[tuple[dict[str, Any], dict[str, Any]]]:
|
|
96
96
|
"""Stop recording and return recorded requests/responses."""
|
|
97
97
|
assert self._recording_active
|
|
98
98
|
self._recording_active = False
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
from collections.abc import Sequence
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
from kumoapi.task import TaskType
|
|
6
|
+
from kumoapi.typing import Dtype, Stype
|
|
7
|
+
from typing_extensions import Self
|
|
8
|
+
|
|
9
|
+
from kumoai.experimental.rfm.base import Column
|
|
10
|
+
from kumoai.experimental.rfm.infer import contains_timestamp, infer_dtype
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TaskTable:
|
|
14
|
+
r"""A :class:`TaskTable` fully specifies the task, *i.e.* its context and
|
|
15
|
+
prediction examples with entity IDs, targets and timestamps.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
task_type: The task type.
|
|
19
|
+
context_df: The data frame holding context examples.
|
|
20
|
+
pred_df: The data frame holding prediction examples.
|
|
21
|
+
entity_table_name: The entity table to predict for. For link prediction
|
|
22
|
+
tasks, needs to hold both entity and target table names.
|
|
23
|
+
entity_column: The name of the entity column.
|
|
24
|
+
target_column: The name of the target column.
|
|
25
|
+
time_column: The name of the time column to use as anchor time. If
|
|
26
|
+
``TaskTable.ENTITY_TIME``, use the timestamp of the entity table
|
|
27
|
+
as anchor time.
|
|
28
|
+
"""
|
|
29
|
+
ENTITY_TIME = '__entity_time__'
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
task_type: TaskType,
|
|
34
|
+
context_df: pd.DataFrame,
|
|
35
|
+
pred_df: pd.DataFrame,
|
|
36
|
+
entity_table_name: str | Sequence[str],
|
|
37
|
+
entity_column: str,
|
|
38
|
+
target_column: str,
|
|
39
|
+
time_column: str | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
|
|
42
|
+
task_type = TaskType(task_type)
|
|
43
|
+
if task_type not in { # Currently supported task types:
|
|
44
|
+
TaskType.BINARY_CLASSIFICATION,
|
|
45
|
+
TaskType.MULTICLASS_CLASSIFICATION,
|
|
46
|
+
TaskType.REGRESSION,
|
|
47
|
+
TaskType.TEMPORAL_LINK_PREDICTION,
|
|
48
|
+
}:
|
|
49
|
+
raise ValueError # TODO
|
|
50
|
+
self._task_type = task_type
|
|
51
|
+
|
|
52
|
+
# TODO Binary classification and regression checks
|
|
53
|
+
|
|
54
|
+
# TODO Check dfs (unify from local table)
|
|
55
|
+
if context_df.empty:
|
|
56
|
+
raise ValueError("No context examples given")
|
|
57
|
+
self._context_df = context_df.copy(deep=False)
|
|
58
|
+
|
|
59
|
+
if pred_df.empty:
|
|
60
|
+
raise ValueError("Provide at least one entity to predict for")
|
|
61
|
+
self._pred_df = pred_df.copy(deep=False)
|
|
62
|
+
|
|
63
|
+
self._dtype_dict: dict[str, Dtype] = {
|
|
64
|
+
column_name: infer_dtype(context_df[column_name])
|
|
65
|
+
for column_name in context_df.columns
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
self._entity_table_names: tuple[str] | tuple[str, str]
|
|
69
|
+
if isinstance(entity_table_name, str):
|
|
70
|
+
self._entity_table_names = (entity_table_name, )
|
|
71
|
+
elif len(entity_table_name) == 1:
|
|
72
|
+
self._entity_table_names = (entity_table_name[0], )
|
|
73
|
+
elif len(entity_table_name) == 2:
|
|
74
|
+
self._entity_table_names = (
|
|
75
|
+
entity_table_name[0],
|
|
76
|
+
entity_table_name[1],
|
|
77
|
+
)
|
|
78
|
+
else:
|
|
79
|
+
raise ValueError # TODO
|
|
80
|
+
|
|
81
|
+
self._entity_column: str = ''
|
|
82
|
+
self._target_column: str = ''
|
|
83
|
+
self._time_column: str | None = None
|
|
84
|
+
|
|
85
|
+
self.entity_column = entity_column
|
|
86
|
+
self.target_column = target_column
|
|
87
|
+
if time_column is not None:
|
|
88
|
+
self.time_column = time_column
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def num_context_examples(self) -> int:
|
|
92
|
+
return len(self._context_df)
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def num_prediction_examples(self) -> int:
|
|
96
|
+
return len(self._pred_df)
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def task_type(self) -> TaskType:
|
|
100
|
+
r"""The task type."""
|
|
101
|
+
return self._task_type
|
|
102
|
+
|
|
103
|
+
def narrow_context(self, start: int, length: int) -> Self:
|
|
104
|
+
r"""Returns a new :class:`TaskTable` that holds a narrowed version of
|
|
105
|
+
context examples.
|
|
106
|
+
|
|
107
|
+
Args:
|
|
108
|
+
start: Index of the prediction examples to start narrowing.
|
|
109
|
+
length: Length of the prediction examples.
|
|
110
|
+
"""
|
|
111
|
+
out = copy.copy(self)
|
|
112
|
+
df = out._context_df.iloc[start:start + length].reset_index(drop=True)
|
|
113
|
+
out._context_df = df
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
def narrow_prediction(self, start: int, length: int) -> Self:
|
|
117
|
+
r"""Returns a new :class:`TaskTable` that holds a narrowed version of
|
|
118
|
+
prediction examples.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
start: Index of the prediction examples to start narrowing.
|
|
122
|
+
length: Length of the prediction examples.
|
|
123
|
+
"""
|
|
124
|
+
out = copy.copy(self)
|
|
125
|
+
df = out._pred_df.iloc[start:start + length].reset_index(drop=True)
|
|
126
|
+
out._pred_df = df
|
|
127
|
+
return out
|
|
128
|
+
|
|
129
|
+
# Entity column ###########################################################
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def entity_table_name(self) -> str:
|
|
133
|
+
return self._entity_table_names[0]
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def entity_table_names(self) -> tuple[str] | tuple[str, str]:
|
|
137
|
+
return self._entity_table_names
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def entity_column(self) -> Column:
|
|
141
|
+
return Column(
|
|
142
|
+
name=self._entity_column,
|
|
143
|
+
expr=None,
|
|
144
|
+
dtype=self._dtype_dict[self._entity_column],
|
|
145
|
+
stype=Stype.ID,
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
@entity_column.setter
|
|
149
|
+
def entity_column(self, name: str) -> None:
|
|
150
|
+
if name not in self._context_df:
|
|
151
|
+
raise ValueError # TODO
|
|
152
|
+
if name not in self._pred_df:
|
|
153
|
+
raise ValueError # TODO
|
|
154
|
+
if not Stype.ID.supports_dtype(self._dtype_dict[name]):
|
|
155
|
+
raise ValueError # TODO
|
|
156
|
+
|
|
157
|
+
self._entity_column = name
|
|
158
|
+
|
|
159
|
+
# Target column ###########################################################
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def evaluate(self) -> bool:
|
|
163
|
+
r"""Returns ``True`` if this task can be used for model evaluation."""
|
|
164
|
+
return self._target_column in self._pred_df
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def _target_stype(self) -> Stype:
|
|
168
|
+
if self.task_type in {
|
|
169
|
+
TaskType.BINARY_CLASSIFICATION,
|
|
170
|
+
TaskType.MULTICLASS_CLASSIFICATION,
|
|
171
|
+
}:
|
|
172
|
+
return Stype.categorical
|
|
173
|
+
if self.task_type in {TaskType.REGRESSION}:
|
|
174
|
+
return Stype.numerical
|
|
175
|
+
if self.task_type.is_link_pred:
|
|
176
|
+
return Stype.multicategorical
|
|
177
|
+
raise ValueError
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def target_column(self) -> Column:
|
|
181
|
+
return Column(
|
|
182
|
+
name=self._target_column,
|
|
183
|
+
expr=None,
|
|
184
|
+
dtype=self._dtype_dict[self._target_column],
|
|
185
|
+
stype=self._target_stype,
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
@target_column.setter
|
|
189
|
+
def target_column(self, name: str) -> None:
|
|
190
|
+
if name not in self._context_df:
|
|
191
|
+
raise ValueError # TODO
|
|
192
|
+
if not self._target_stype.supports_dtype(self._dtype_dict[name]):
|
|
193
|
+
raise ValueError # TODO
|
|
194
|
+
|
|
195
|
+
self._target_column = name
|
|
196
|
+
|
|
197
|
+
# Time column #############################################################
|
|
198
|
+
|
|
199
|
+
def has_time_column(self) -> bool:
|
|
200
|
+
r"""Returns ``True`` if this task has a time column; ``False``
|
|
201
|
+
otherwise.
|
|
202
|
+
"""
|
|
203
|
+
return self._time_column not in {None, self.ENTITY_TIME}
|
|
204
|
+
|
|
205
|
+
@property
|
|
206
|
+
def use_entity_time(self) -> bool:
|
|
207
|
+
r"""Whether to use the timestamp of the entity table as anchor time."""
|
|
208
|
+
return self._time_column == self.ENTITY_TIME
|
|
209
|
+
|
|
210
|
+
@property
|
|
211
|
+
def time_column(self) -> Column | None:
|
|
212
|
+
r"""The time column of this task.
|
|
213
|
+
|
|
214
|
+
The getter returns the time column of this task, or ``None`` if no
|
|
215
|
+
such time column is present.
|
|
216
|
+
|
|
217
|
+
The setter sets a column as a time column for this task, and raises a
|
|
218
|
+
:class:`ValueError` if the time column has a non-timestamp compatible
|
|
219
|
+
data type or if the column name does not match a column in the data
|
|
220
|
+
frame.
|
|
221
|
+
"""
|
|
222
|
+
if not self.has_time_column():
|
|
223
|
+
return None
|
|
224
|
+
assert self._time_column is not None
|
|
225
|
+
return Column(
|
|
226
|
+
name=self._time_column,
|
|
227
|
+
expr=None,
|
|
228
|
+
dtype=self._dtype_dict[self._time_column],
|
|
229
|
+
stype=Stype.timestamp,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
@time_column.setter
|
|
233
|
+
def time_column(self, name: str | None) -> None:
|
|
234
|
+
if name is None or name == self.ENTITY_TIME:
|
|
235
|
+
self._time_column = name
|
|
236
|
+
return
|
|
237
|
+
|
|
238
|
+
if name not in self._context_df:
|
|
239
|
+
raise ValueError # TODO
|
|
240
|
+
if name not in self._pred_df:
|
|
241
|
+
raise ValueError # TODO
|
|
242
|
+
if not contains_timestamp(
|
|
243
|
+
ser=self._context_df[name],
|
|
244
|
+
column_name=name,
|
|
245
|
+
dtype=self._dtype_dict[name],
|
|
246
|
+
):
|
|
247
|
+
raise ValueError # TODO
|
|
248
|
+
|
|
249
|
+
self._time_column = name
|
|
250
|
+
|
|
251
|
+
# Metadata ################################################################
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def metadata(self) -> pd.DataFrame:
|
|
255
|
+
raise NotImplementedError
|
|
256
|
+
|
|
257
|
+
def print_metadata(self) -> None:
|
|
258
|
+
raise NotImplementedError
|
|
259
|
+
|
|
260
|
+
# Python builtins #########################################################
|
|
261
|
+
|
|
262
|
+
def __hash__(self) -> int:
|
|
263
|
+
return hash((
|
|
264
|
+
self.task_type,
|
|
265
|
+
self.entity_table_names,
|
|
266
|
+
self._entity_column,
|
|
267
|
+
self._target_column,
|
|
268
|
+
self._time_column,
|
|
269
|
+
))
|
|
270
|
+
|
|
271
|
+
def __repr__(self) -> str:
|
|
272
|
+
if self.task_type.is_link_pred:
|
|
273
|
+
entity_table_repr = f'entity_table_names={self.entity_table_names}'
|
|
274
|
+
else:
|
|
275
|
+
entity_table_repr = f'entity_table_name={self.entity_table_name}'
|
|
276
|
+
|
|
277
|
+
if self.use_entity_time:
|
|
278
|
+
time_repr = 'use_entity_time=True'
|
|
279
|
+
else:
|
|
280
|
+
time_repr = f'time_column={self._time_column}'
|
|
281
|
+
|
|
282
|
+
return (f'{self.__class__.__name__}(\n'
|
|
283
|
+
f' task_type={self.task_type},\n'
|
|
284
|
+
f' num_context_examples={self.num_context_examples},\n'
|
|
285
|
+
f' num_prediction_examples={self.num_prediction_examples},\n'
|
|
286
|
+
f' {entity_table_repr},\n'
|
|
287
|
+
f' entity_column={self._entity_column},\n'
|
|
288
|
+
f' target_column={self._target_column},\n'
|
|
289
|
+
f' {time_repr},\n'
|
|
290
|
+
f')')
|
|
@@ -370,9 +370,11 @@ class PredictiveQuery:
|
|
|
370
370
|
train_table_job_api = global_state.client.generate_train_table_job_api
|
|
371
371
|
job_id: GenerateTrainTableJobID = train_table_job_api.create(
|
|
372
372
|
GenerateTrainTableRequest(
|
|
373
|
-
dict(custom_tags),
|
|
374
|
-
|
|
375
|
-
|
|
373
|
+
dict(custom_tags),
|
|
374
|
+
pq_id,
|
|
375
|
+
plan,
|
|
376
|
+
None,
|
|
377
|
+
))
|
|
376
378
|
|
|
377
379
|
self._train_table = TrainingTableJob(job_id=job_id)
|
|
378
380
|
if non_blocking:
|
|
@@ -451,9 +453,11 @@ class PredictiveQuery:
|
|
|
451
453
|
bp_table_api = global_state.client.generate_prediction_table_job_api
|
|
452
454
|
job_id: GeneratePredictionTableJobID = bp_table_api.create(
|
|
453
455
|
GeneratePredictionTableRequest(
|
|
454
|
-
dict(custom_tags),
|
|
455
|
-
|
|
456
|
-
|
|
456
|
+
dict(custom_tags),
|
|
457
|
+
pq_id,
|
|
458
|
+
plan,
|
|
459
|
+
None,
|
|
460
|
+
))
|
|
457
461
|
|
|
458
462
|
self._prediction_table = PredictionTableJob(job_id=job_id)
|
|
459
463
|
if non_blocking:
|
kumoai/testing/snow.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
from kumoai.experimental.rfm.backend.snow import Connection
|
|
5
|
+
from kumoai.experimental.rfm.backend.snow import connect as _connect
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def connect(
|
|
9
|
+
region: str,
|
|
10
|
+
id: str,
|
|
11
|
+
account: str,
|
|
12
|
+
user: str,
|
|
13
|
+
warehouse: str,
|
|
14
|
+
database: str | None = None,
|
|
15
|
+
schema: str | None = None,
|
|
16
|
+
) -> Connection:
|
|
17
|
+
|
|
18
|
+
kwargs = dict(password=os.getenv('SNOWFLAKE_PASSWORD'))
|
|
19
|
+
if kwargs['password'] is None:
|
|
20
|
+
import boto3
|
|
21
|
+
from cryptography.hazmat.primitives import serialization
|
|
22
|
+
|
|
23
|
+
client = boto3.client(
|
|
24
|
+
service_name='secretsmanager',
|
|
25
|
+
region_name=region,
|
|
26
|
+
)
|
|
27
|
+
secret_id = (f'arn:aws:secretsmanager:{region}:{id}:secret:'
|
|
28
|
+
f'{account}.snowflakecomputing.com')
|
|
29
|
+
response = client.get_secret_value(SecretId=secret_id)['SecretString']
|
|
30
|
+
secret = json.loads(response)
|
|
31
|
+
|
|
32
|
+
private_key = serialization.load_pem_private_key(
|
|
33
|
+
secret['kumo_user_secretkey'].encode(),
|
|
34
|
+
password=None,
|
|
35
|
+
)
|
|
36
|
+
kwargs['private_key'] = private_key.private_bytes(
|
|
37
|
+
encoding=serialization.Encoding.DER,
|
|
38
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
39
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
return _connect(
|
|
43
|
+
account=account,
|
|
44
|
+
user=user,
|
|
45
|
+
warehouse='WH_XS',
|
|
46
|
+
database='KUMO',
|
|
47
|
+
schema=schema,
|
|
48
|
+
session_parameters=dict(CLIENT_TELEMETRY_ENABLED=False),
|
|
49
|
+
**kwargs,
|
|
50
|
+
)
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from typing import Literal, Mapping, Optional, Union, overload
|
|
3
|
+
|
|
4
|
+
from kumoapi.distilled_model_plan import DistilledModelPlan
|
|
5
|
+
from kumoapi.jobs import DistillationJobRequest, DistillationJobResource
|
|
6
|
+
|
|
7
|
+
from kumoai import global_state
|
|
8
|
+
from kumoai.client.jobs import TrainingJobID
|
|
9
|
+
from kumoai.graph import Graph
|
|
10
|
+
from kumoai.pquery.training_table import TrainingTable, TrainingTableJob
|
|
11
|
+
from kumoai.trainer.job import TrainingJob, TrainingJobResult
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class DistillationTrainer:
|
|
17
|
+
r"""A trainer supports creating a Kumo machine learning model
|
|
18
|
+
for use in an online serving endpoint. The distllation process involes
|
|
19
|
+
training a shallow model on a :class:`~kumoai.pquery.PredictiveQuery` using
|
|
20
|
+
the embeddings generated by a base model :args:`base_training_job_id`.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
model_plan: The distilled model plan to use for the distillation process.
|
|
24
|
+
base_training_job_id: The ID of the base training job to use for the distillation process.
|
|
25
|
+
""" # noqa: E501
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
model_plan: DistilledModelPlan,
|
|
30
|
+
base_training_job_id: TrainingJobID,
|
|
31
|
+
) -> None:
|
|
32
|
+
self.model_plan: DistilledModelPlan = model_plan
|
|
33
|
+
self.base_training_job_id: TrainingJobID = base_training_job_id
|
|
34
|
+
|
|
35
|
+
# Cached from backend:
|
|
36
|
+
self._training_job_id: Optional[TrainingJobID] = None
|
|
37
|
+
|
|
38
|
+
# Metadata ################################################################
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def is_trained(self) -> bool:
|
|
42
|
+
r"""Returns ``True`` if this trainer instance has successfully been
|
|
43
|
+
trained (and is therefore ready for prediction); ``False`` otherwise.
|
|
44
|
+
"""
|
|
45
|
+
raise NotImplementedError(
|
|
46
|
+
"Checking if a distilled trainer is trained is not "
|
|
47
|
+
"implemented yet.")
|
|
48
|
+
|
|
49
|
+
@overload
|
|
50
|
+
def fit(
|
|
51
|
+
self,
|
|
52
|
+
graph: Graph,
|
|
53
|
+
train_table: Union[TrainingTable, TrainingTableJob],
|
|
54
|
+
) -> TrainingJobResult:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
@overload
|
|
58
|
+
def fit(
|
|
59
|
+
self,
|
|
60
|
+
graph: Graph,
|
|
61
|
+
train_table: Union[TrainingTable, TrainingTableJob],
|
|
62
|
+
*,
|
|
63
|
+
non_blocking: Literal[False],
|
|
64
|
+
) -> TrainingJobResult:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
@overload
|
|
68
|
+
def fit(
|
|
69
|
+
self,
|
|
70
|
+
graph: Graph,
|
|
71
|
+
train_table: Union[TrainingTable, TrainingTableJob],
|
|
72
|
+
*,
|
|
73
|
+
non_blocking: Literal[True],
|
|
74
|
+
) -> TrainingJob:
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
@overload
|
|
78
|
+
def fit(
|
|
79
|
+
self,
|
|
80
|
+
graph: Graph,
|
|
81
|
+
train_table: Union[TrainingTable, TrainingTableJob],
|
|
82
|
+
*,
|
|
83
|
+
non_blocking: bool,
|
|
84
|
+
) -> Union[TrainingJob, TrainingJobResult]:
|
|
85
|
+
pass
|
|
86
|
+
|
|
87
|
+
def fit(
|
|
88
|
+
self,
|
|
89
|
+
graph: Graph,
|
|
90
|
+
train_table: Union[TrainingTable, TrainingTableJob],
|
|
91
|
+
*,
|
|
92
|
+
non_blocking: bool = False,
|
|
93
|
+
custom_tags: Mapping[str, str] = {},
|
|
94
|
+
) -> Union[TrainingJob, TrainingJobResult]:
|
|
95
|
+
r"""Fits a model to the specified graph and training table, with the
|
|
96
|
+
strategy defined by :class:`DistilledTrainer`'s :obj:`model_plan`.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
graph: The :class:`~kumoai.graph.Graph` object that represents the
|
|
100
|
+
tables and relationships that Kumo will learn from.
|
|
101
|
+
train_table: The :class:`~kumoai.pquery.TrainingTable`, or
|
|
102
|
+
in-progress :class:`~kumoai.pquery.TrainingTableJob`, that
|
|
103
|
+
represents the training data produced by a
|
|
104
|
+
:class:`~kumoai.pquery.PredictiveQuery` on :obj:`graph`.
|
|
105
|
+
non_blocking: Whether this operation should return immediately
|
|
106
|
+
after launching the training job, or await completion of the
|
|
107
|
+
training job.
|
|
108
|
+
custom_tags: Additional, customer defined k-v tags to be associated
|
|
109
|
+
with the job to be launched. Job tags are useful for grouping
|
|
110
|
+
and searching jobs.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
Union[TrainingJobResult, TrainingJob]:
|
|
114
|
+
If ``non_blocking=False``, returns a training job object. If
|
|
115
|
+
``non_blocking=True``, returns a training job future object.
|
|
116
|
+
"""
|
|
117
|
+
# TODO(manan, siyang): remove soon:
|
|
118
|
+
job_id = train_table.job_id
|
|
119
|
+
assert job_id is not None
|
|
120
|
+
|
|
121
|
+
train_table_job_api = global_state.client.generate_train_table_job_api
|
|
122
|
+
pq_id = train_table_job_api.get(job_id).config.pquery_id
|
|
123
|
+
assert pq_id is not None
|
|
124
|
+
|
|
125
|
+
custom_table = None
|
|
126
|
+
if isinstance(train_table, TrainingTable):
|
|
127
|
+
custom_table = train_table._custom_train_table
|
|
128
|
+
|
|
129
|
+
# NOTE the backend implementation currently handles sequentialization
|
|
130
|
+
# between a training table future and a training job; that is, if the
|
|
131
|
+
# training table future is still executing, the backend will wait on
|
|
132
|
+
# the job ID completion before executing a training job. This preserves
|
|
133
|
+
# semantics for both futures, ensures that Kumo works as expected if
|
|
134
|
+
# used only via REST API, and allows us to avoid chaining calllbacks
|
|
135
|
+
# in an ugly way here:
|
|
136
|
+
api = global_state.client.distillation_job_api
|
|
137
|
+
self._training_job_id = api.create(
|
|
138
|
+
DistillationJobRequest(
|
|
139
|
+
dict(custom_tags),
|
|
140
|
+
pquery_id=pq_id,
|
|
141
|
+
base_training_job_id=self.base_training_job_id,
|
|
142
|
+
distilled_model_plan=self.model_plan,
|
|
143
|
+
graph_snapshot_id=graph.snapshot(non_blocking=non_blocking),
|
|
144
|
+
train_table_job_id=job_id,
|
|
145
|
+
custom_train_table=custom_table,
|
|
146
|
+
))
|
|
147
|
+
|
|
148
|
+
out = TrainingJob(job_id=self._training_job_id)
|
|
149
|
+
if non_blocking:
|
|
150
|
+
return out
|
|
151
|
+
return out.attach()
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def _load_from_job(
|
|
155
|
+
cls,
|
|
156
|
+
job: DistillationJobResource,
|
|
157
|
+
) -> 'DistillationTrainer':
|
|
158
|
+
trainer = cls(job.config.distilled_model_plan,
|
|
159
|
+
job.config.base_training_job_id)
|
|
160
|
+
trainer._training_job_id = job.job_id
|
|
161
|
+
return trainer
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def load(cls, job_id: TrainingJobID) -> 'DistillationTrainer':
|
|
165
|
+
r"""Creates a :class:`~kumoai.trainer.Trainer` instance from a training
|
|
166
|
+
job ID.
|
|
167
|
+
"""
|
|
168
|
+
raise NotImplementedError(
|
|
169
|
+
"Loading a distilled trainer from a job ID is not implemented yet."
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def load_from_tags(cls, tags: Mapping[str, str]) -> 'DistillationTrainer':
|
|
174
|
+
raise NotImplementedError(
|
|
175
|
+
"Loading a distilled trainer from tags is not implemented yet.")
|
kumoai/utils/__init__.py
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
from .
|
|
1
|
+
from .sql import quote_ident
|
|
2
|
+
from .progress_logger import ProgressLogger
|
|
2
3
|
from .forecasting import ForecastVisualizer
|
|
3
4
|
from .datasets import from_relbench
|
|
4
5
|
|
|
5
6
|
__all__ = [
|
|
7
|
+
'quote_ident',
|
|
6
8
|
'ProgressLogger',
|
|
7
|
-
'InteractiveProgressLogger',
|
|
8
9
|
'ForecastVisualizer',
|
|
9
10
|
'from_relbench',
|
|
10
11
|
]
|
kumoai/utils/display.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from collections.abc import Sequence
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
from kumoai import in_notebook, in_snowflake_notebook
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def message(msg: str) -> None:
|
|
9
|
+
msg = msg.replace("`", "'") if not in_notebook() else msg
|
|
10
|
+
|
|
11
|
+
if in_snowflake_notebook():
|
|
12
|
+
import streamlit as st
|
|
13
|
+
st.markdown(msg)
|
|
14
|
+
elif in_notebook():
|
|
15
|
+
from IPython.display import Markdown, display
|
|
16
|
+
display(Markdown(msg))
|
|
17
|
+
else:
|
|
18
|
+
print(msg)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def title(msg: str) -> None:
|
|
22
|
+
message(f"### {msg}" if in_notebook() else f"{msg}:")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def italic(msg: str) -> None:
|
|
26
|
+
message(f"*{msg}*" if in_notebook() else msg)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def unordered_list(items: Sequence[str]) -> None:
|
|
30
|
+
if in_notebook():
|
|
31
|
+
msg = '\n'.join([f"- {item}" for item in items])
|
|
32
|
+
else:
|
|
33
|
+
msg = '\n'.join([f"• {item.replace('`', '')}" for item in items])
|
|
34
|
+
message(msg)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def dataframe(df: pd.DataFrame) -> None:
|
|
38
|
+
if in_snowflake_notebook():
|
|
39
|
+
import streamlit as st
|
|
40
|
+
st.dataframe(df, hide_index=True)
|
|
41
|
+
elif in_notebook():
|
|
42
|
+
from IPython.display import display
|
|
43
|
+
try:
|
|
44
|
+
if hasattr(df.style, 'hide'):
|
|
45
|
+
display(df.style.hide(axis='index')) # pandas=2
|
|
46
|
+
else:
|
|
47
|
+
display(df.style.hide_index()) # pandas<1.3
|
|
48
|
+
except ImportError:
|
|
49
|
+
print(df.to_string(index=False)) # missing jinja2
|
|
50
|
+
else:
|
|
51
|
+
print(df.to_string(index=False))
|