kumoai 2.13.0.dev202511191731__cp310-cp310-macosx_11_0_arm64.whl → 2.14.0.dev202512271732__cp310-cp310-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.
Files changed (53) hide show
  1. kumoai/__init__.py +12 -0
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +6 -0
  4. kumoai/client/jobs.py +24 -0
  5. kumoai/client/pquery.py +6 -2
  6. kumoai/connector/utils.py +23 -2
  7. kumoai/experimental/rfm/__init__.py +52 -52
  8. kumoai/experimental/rfm/authenticate.py +3 -4
  9. kumoai/experimental/rfm/backend/__init__.py +0 -0
  10. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  11. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +65 -127
  12. kumoai/experimental/rfm/backend/local/sampler.py +312 -0
  13. kumoai/experimental/rfm/backend/local/table.py +113 -0
  14. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  15. kumoai/experimental/rfm/backend/snow/sampler.py +297 -0
  16. kumoai/experimental/rfm/backend/snow/table.py +242 -0
  17. kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
  18. kumoai/experimental/rfm/backend/sqlite/sampler.py +398 -0
  19. kumoai/experimental/rfm/backend/sqlite/table.py +184 -0
  20. kumoai/experimental/rfm/base/__init__.py +30 -0
  21. kumoai/experimental/rfm/base/column.py +152 -0
  22. kumoai/experimental/rfm/base/expression.py +44 -0
  23. kumoai/experimental/rfm/base/sampler.py +761 -0
  24. kumoai/experimental/rfm/base/source.py +19 -0
  25. kumoai/experimental/rfm/base/sql_sampler.py +143 -0
  26. kumoai/experimental/rfm/base/table.py +753 -0
  27. kumoai/experimental/rfm/{local_graph.py → graph.py} +546 -116
  28. kumoai/experimental/rfm/infer/__init__.py +8 -0
  29. kumoai/experimental/rfm/infer/dtype.py +81 -0
  30. kumoai/experimental/rfm/infer/multicategorical.py +1 -1
  31. kumoai/experimental/rfm/infer/pkey.py +128 -0
  32. kumoai/experimental/rfm/infer/stype.py +35 -0
  33. kumoai/experimental/rfm/infer/time_col.py +61 -0
  34. kumoai/experimental/rfm/pquery/executor.py +27 -27
  35. kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
  36. kumoai/experimental/rfm/rfm.py +313 -245
  37. kumoai/experimental/rfm/sagemaker.py +15 -7
  38. kumoai/pquery/predictive_query.py +10 -6
  39. kumoai/testing/decorators.py +1 -1
  40. kumoai/testing/snow.py +50 -0
  41. kumoai/trainer/distilled_trainer.py +175 -0
  42. kumoai/utils/__init__.py +3 -2
  43. kumoai/utils/progress_logger.py +178 -12
  44. kumoai/utils/sql.py +3 -0
  45. {kumoai-2.13.0.dev202511191731.dist-info → kumoai-2.14.0.dev202512271732.dist-info}/METADATA +10 -8
  46. {kumoai-2.13.0.dev202511191731.dist-info → kumoai-2.14.0.dev202512271732.dist-info}/RECORD +49 -29
  47. kumoai/experimental/rfm/local_graph_sampler.py +0 -182
  48. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  49. kumoai/experimental/rfm/local_table.py +0 -545
  50. kumoai/experimental/rfm/utils.py +0 -344
  51. {kumoai-2.13.0.dev202511191731.dist-info → kumoai-2.14.0.dev202512271732.dist-info}/WHEEL +0 -0
  52. {kumoai-2.13.0.dev202511191731.dist-info → kumoai-2.14.0.dev202512271732.dist-info}/licenses/LICENSE +0 -0
  53. {kumoai-2.13.0.dev202511191731.dist-info → kumoai-2.14.0.dev202512271732.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,312 @@
1
+ from typing import TYPE_CHECKING, Literal
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ from kumoapi.pquery import ValidatedPredictiveQuery
6
+
7
+ from kumoai.experimental.rfm.backend.local import LocalGraphStore
8
+ from kumoai.experimental.rfm.base import Sampler, SamplerOutput
9
+ from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
10
+ from kumoai.utils import ProgressLogger
11
+
12
+ if TYPE_CHECKING:
13
+ from kumoai.experimental.rfm import Graph
14
+
15
+
16
+ class LocalSampler(Sampler):
17
+ def __init__(
18
+ self,
19
+ graph: 'Graph',
20
+ verbose: bool | ProgressLogger = True,
21
+ ) -> None:
22
+ super().__init__(graph=graph, verbose=verbose)
23
+
24
+ import kumoai.kumolib as kumolib
25
+
26
+ self._graph_store = LocalGraphStore(graph, verbose)
27
+ self._graph_sampler = kumolib.NeighborSampler(
28
+ list(self.table_stype_dict.keys()),
29
+ self.edge_types,
30
+ {
31
+ '__'.join(edge_type): colptr
32
+ for edge_type, colptr in self._graph_store.colptr_dict.items()
33
+ },
34
+ {
35
+ '__'.join(edge_type): row
36
+ for edge_type, row in self._graph_store.row_dict.items()
37
+ },
38
+ self._graph_store.time_dict,
39
+ )
40
+
41
+ def _get_min_max_time_dict(
42
+ self,
43
+ table_names: list[str],
44
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
45
+ return {
46
+ key: value
47
+ for key, value in self._graph_store.min_max_time_dict.items()
48
+ if key in table_names
49
+ }
50
+
51
+ def _sample_subgraph(
52
+ self,
53
+ entity_table_name: str,
54
+ entity_pkey: pd.Series,
55
+ anchor_time: pd.Series | Literal['entity'],
56
+ columns_dict: dict[str, set[str]],
57
+ num_neighbors: list[int],
58
+ ) -> SamplerOutput:
59
+
60
+ index = self._graph_store.get_node_id(entity_table_name, entity_pkey)
61
+
62
+ if isinstance(anchor_time, pd.Series):
63
+ time = anchor_time.astype(int).to_numpy() // 1000**3 # to seconds
64
+ else:
65
+ assert anchor_time == 'entity'
66
+ time = self._graph_store.time_dict[entity_table_name][index]
67
+
68
+ (
69
+ row_dict,
70
+ col_dict,
71
+ node_dict,
72
+ batch_dict,
73
+ num_sampled_nodes_dict,
74
+ num_sampled_edges_dict,
75
+ ) = self._graph_sampler.sample(
76
+ {
77
+ '__'.join(edge_type): num_neighbors
78
+ for edge_type in self.edge_types
79
+ },
80
+ {},
81
+ entity_table_name,
82
+ index,
83
+ time,
84
+ )
85
+
86
+ df_dict: dict[str, pd.DataFrame] = {}
87
+ inverse_dict: dict[str, np.ndarray] = {}
88
+ for table_name, node in node_dict.items():
89
+ df = self._graph_store.df_dict[table_name]
90
+ columns = columns_dict[table_name]
91
+ if self.end_time_column_dict.get(table_name, None) in columns:
92
+ df = df.iloc[node]
93
+ elif len(columns) == 0:
94
+ df = df.iloc[node]
95
+ else:
96
+ # Only store unique rows in `df` above a certain threshold:
97
+ unique_node, inverse = np.unique(node, return_inverse=True)
98
+ if len(node) > 1.05 * len(unique_node):
99
+ df = df.iloc[unique_node]
100
+ inverse_dict[table_name] = inverse
101
+ else:
102
+ df = df.iloc[node]
103
+ df = df.reset_index(drop=True)
104
+ df = df[list(columns)]
105
+ df_dict[table_name] = df
106
+
107
+ num_sampled_nodes_dict = {
108
+ table_name: num_sampled_nodes.tolist()
109
+ for table_name, num_sampled_nodes in
110
+ num_sampled_nodes_dict.items()
111
+ }
112
+
113
+ row_dict = {
114
+ edge_type: row_dict['__'.join(edge_type)]
115
+ for edge_type in self.edge_types
116
+ }
117
+ col_dict = {
118
+ edge_type: col_dict['__'.join(edge_type)]
119
+ for edge_type in self.edge_types
120
+ }
121
+ num_sampled_edges_dict = {
122
+ edge_type: num_sampled_edges_dict['__'.join(edge_type)].tolist()
123
+ for edge_type in self.edge_types
124
+ }
125
+
126
+ return SamplerOutput(
127
+ anchor_time=time * 1000**3, # to nanoseconds
128
+ df_dict=df_dict,
129
+ inverse_dict=inverse_dict,
130
+ batch_dict=batch_dict,
131
+ num_sampled_nodes_dict=num_sampled_nodes_dict,
132
+ row_dict=row_dict,
133
+ col_dict=col_dict,
134
+ num_sampled_edges_dict=num_sampled_edges_dict,
135
+ )
136
+
137
+ def _sample_entity_table(
138
+ self,
139
+ table_name: str,
140
+ columns: set[str],
141
+ num_rows: int,
142
+ random_seed: int | None = None,
143
+ ) -> pd.DataFrame:
144
+ pkey_map = self._graph_store.pkey_map_dict[table_name]
145
+ if len(pkey_map) > num_rows:
146
+ pkey_map = pkey_map.sample(
147
+ n=num_rows,
148
+ random_state=random_seed,
149
+ ignore_index=True,
150
+ )
151
+ df = self._graph_store.df_dict[table_name]
152
+ df = df.iloc[pkey_map['arange']][list(columns)]
153
+ return df
154
+
155
+ def _sample_target(
156
+ self,
157
+ query: ValidatedPredictiveQuery,
158
+ entity_df: pd.DataFrame,
159
+ train_index: np.ndarray,
160
+ train_time: pd.Series,
161
+ num_train_examples: int,
162
+ test_index: np.ndarray,
163
+ test_time: pd.Series,
164
+ num_test_examples: int,
165
+ columns_dict: dict[str, set[str]],
166
+ time_offset_dict: dict[
167
+ tuple[str, str, str],
168
+ tuple[pd.DateOffset | None, pd.DateOffset],
169
+ ],
170
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
171
+
172
+ train_y, train_mask = self._sample_target_set(
173
+ query=query,
174
+ pkey=entity_df[self.primary_key_dict[query.entity_table]],
175
+ index=train_index,
176
+ anchor_time=train_time,
177
+ num_examples=num_train_examples,
178
+ columns_dict=columns_dict,
179
+ time_offset_dict=time_offset_dict,
180
+ )
181
+
182
+ test_y, test_mask = self._sample_target_set(
183
+ query=query,
184
+ pkey=entity_df[self.primary_key_dict[query.entity_table]],
185
+ index=test_index,
186
+ anchor_time=test_time,
187
+ num_examples=num_test_examples,
188
+ columns_dict=columns_dict,
189
+ time_offset_dict=time_offset_dict,
190
+ )
191
+
192
+ return train_y, train_mask, test_y, test_mask
193
+
194
+ # Helper Methods ##########################################################
195
+
196
+ def _sample_target_set(
197
+ self,
198
+ query: ValidatedPredictiveQuery,
199
+ pkey: pd.Series,
200
+ index: np.ndarray,
201
+ anchor_time: pd.Series,
202
+ num_examples: int,
203
+ columns_dict: dict[str, set[str]],
204
+ time_offset_dict: dict[
205
+ tuple[str, str, str],
206
+ tuple[pd.DateOffset | None, pd.DateOffset],
207
+ ],
208
+ batch_size: int = 10_000,
209
+ ) -> tuple[pd.Series, np.ndarray]:
210
+
211
+ num_hops = 1 if len(time_offset_dict) > 0 else 0
212
+ num_neighbors_dict: dict[str, list[int]] = {}
213
+ unix_time_offset_dict: dict[str, list[list[int | None]]] = {}
214
+ for edge_type, (start, end) in time_offset_dict.items():
215
+ unix_time_offset_dict['__'.join(edge_type)] = [[
216
+ date_offset_to_seconds(start) if start is not None else None,
217
+ date_offset_to_seconds(end),
218
+ ]]
219
+ for edge_type in set(self.edge_types) - set(time_offset_dict.keys()):
220
+ num_neighbors_dict['__'.join(edge_type)] = [0] * num_hops
221
+
222
+ count = 0
223
+ ys: list[pd.Series] = []
224
+ mask = np.full(len(index), False, dtype=bool)
225
+ for start in range(0, len(index), batch_size):
226
+ subset = pkey.iloc[index[start:start + batch_size]]
227
+ time = anchor_time.iloc[start:start + batch_size]
228
+
229
+ _, _, node_dict, batch_dict, _, _ = self._graph_sampler.sample(
230
+ num_neighbors_dict,
231
+ unix_time_offset_dict,
232
+ query.entity_table,
233
+ self._graph_store.get_node_id(query.entity_table, subset),
234
+ time.astype(int).to_numpy() // 1000**3, # to seconds
235
+ )
236
+
237
+ feat_dict: dict[str, pd.DataFrame] = {}
238
+ time_dict: dict[str, pd.Series] = {}
239
+ for table_name, columns in columns_dict.items():
240
+ df = self._graph_store.df_dict[table_name]
241
+ df = df.iloc[node_dict[table_name]].reset_index(drop=True)
242
+ df = df[list(columns)]
243
+ feat_dict[table_name] = df
244
+
245
+ time_column = self.time_column_dict.get(table_name)
246
+ if time_column in columns:
247
+ time_dict[table_name] = df[time_column]
248
+
249
+ y, _mask = PQueryPandasExecutor().execute(
250
+ query=query,
251
+ feat_dict=feat_dict,
252
+ time_dict=time_dict,
253
+ batch_dict=batch_dict,
254
+ anchor_time=time,
255
+ num_forecasts=query.num_forecasts,
256
+ )
257
+ ys.append(y)
258
+ mask[start:start + batch_size] = _mask
259
+
260
+ count += len(y)
261
+ if count >= num_examples:
262
+ break
263
+
264
+ if len(ys) == 0:
265
+ y = pd.Series([], dtype=float)
266
+ elif len(ys) == 1:
267
+ y = ys[0]
268
+ else:
269
+ y = pd.concat(ys, axis=0, ignore_index=True)
270
+
271
+ return y, mask
272
+
273
+
274
+ # Helper Functions ############################################################
275
+
276
+
277
+ def date_offset_to_seconds(offset: pd.DateOffset) -> int:
278
+ r"""Convert a :class:`pandas.DateOffset` into a number of seconds.
279
+
280
+ .. note::
281
+ We are conservative and take months and years as their maximum value.
282
+ Additional values are then dropped in label computation where we know
283
+ the actual dates.
284
+ """
285
+ MAX_DAYS_IN_MONTH = 31
286
+ MAX_DAYS_IN_YEAR = 366
287
+
288
+ SECONDS_IN_MINUTE = 60
289
+ SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE
290
+ SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR
291
+
292
+ total_sec = 0
293
+ multiplier = getattr(offset, 'n', 1) # The multiplier (if present).
294
+
295
+ for attr, value in offset.__dict__.items():
296
+ if value is None or value == 0:
297
+ continue
298
+ scaled_value = value * multiplier
299
+ if attr == 'years':
300
+ total_sec += scaled_value * MAX_DAYS_IN_YEAR * SECONDS_IN_DAY
301
+ elif attr == 'months':
302
+ total_sec += scaled_value * MAX_DAYS_IN_MONTH * SECONDS_IN_DAY
303
+ elif attr == 'days':
304
+ total_sec += scaled_value * SECONDS_IN_DAY
305
+ elif attr == 'hours':
306
+ total_sec += scaled_value * SECONDS_IN_HOUR
307
+ elif attr == 'minutes':
308
+ total_sec += scaled_value * SECONDS_IN_MINUTE
309
+ elif attr == 'seconds':
310
+ total_sec += scaled_value
311
+
312
+ return total_sec
@@ -0,0 +1,113 @@
1
+ from typing import Sequence, cast
2
+
3
+ import pandas as pd
4
+ from kumoapi.model_plan import MissingType
5
+
6
+ from kumoai.experimental.rfm.base import (
7
+ ColumnSpec,
8
+ DataBackend,
9
+ SourceColumn,
10
+ SourceForeignKey,
11
+ Table,
12
+ )
13
+
14
+
15
+ class LocalTable(Table):
16
+ r"""A table backed by a :class:`pandas.DataFrame`.
17
+
18
+ A :class:`LocalTable` fully specifies the relevant metadata, *i.e.*
19
+ selected columns, column semantic types, primary keys and time columns.
20
+ :class:`LocalTable` is used to create a :class:`Graph`.
21
+
22
+ .. code-block:: python
23
+
24
+ import pandas as pd
25
+ import kumoai.experimental.rfm as rfm
26
+
27
+ # Load data from a CSV file:
28
+ df = pd.read_csv("data.csv")
29
+
30
+ # Create a table from a `pandas.DataFrame` and infer its metadata ...
31
+ table = rfm.LocalTable(df, name="my_table").infer_metadata()
32
+
33
+ # ... or create a table explicitly:
34
+ table = rfm.LocalTable(
35
+ df=df,
36
+ name="my_table",
37
+ primary_key="id",
38
+ time_column="time",
39
+ end_time_column=None,
40
+ )
41
+
42
+ # Verify metadata:
43
+ table.print_metadata()
44
+
45
+ # Change the semantic type of a column:
46
+ table[column].stype = "text"
47
+
48
+ Args:
49
+ df: The data frame to create this table from.
50
+ name: The name of this table.
51
+ primary_key: The name of the primary key of this table, if it exists.
52
+ time_column: The name of the time column of this table, if it exists.
53
+ end_time_column: The name of the end time column of this table, if it
54
+ exists.
55
+ """
56
+ def __init__(
57
+ self,
58
+ df: pd.DataFrame,
59
+ name: str,
60
+ primary_key: MissingType | str | None = MissingType.VALUE,
61
+ time_column: str | None = None,
62
+ end_time_column: str | None = None,
63
+ ) -> None:
64
+
65
+ if df.empty:
66
+ raise ValueError("Data frame is empty")
67
+ if isinstance(df.columns, pd.MultiIndex):
68
+ raise ValueError("Data frame must not have a multi-index")
69
+ if not df.columns.is_unique:
70
+ raise ValueError("Data frame must have unique column names")
71
+ if any(col == '' for col in df.columns):
72
+ raise ValueError("Data frame must have non-empty column names")
73
+
74
+ self._data = df.copy(deep=False)
75
+
76
+ super().__init__(
77
+ name=name,
78
+ primary_key=primary_key,
79
+ time_column=time_column,
80
+ end_time_column=end_time_column,
81
+ )
82
+
83
+ @property
84
+ def backend(self) -> DataBackend:
85
+ return cast(DataBackend, DataBackend.LOCAL)
86
+
87
+ def _get_source_columns(self) -> list[SourceColumn]:
88
+ return [
89
+ SourceColumn(
90
+ name=column_name,
91
+ dtype=None,
92
+ is_primary_key=False,
93
+ is_unique_key=False,
94
+ is_nullable=True,
95
+ ) for column_name in self._data.columns
96
+ ]
97
+
98
+ def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
99
+ return []
100
+
101
+ def _get_source_sample_df(self) -> pd.DataFrame:
102
+ return self._data
103
+
104
+ def _get_expr_sample_df(
105
+ self,
106
+ columns: Sequence[ColumnSpec],
107
+ ) -> pd.DataFrame:
108
+ raise RuntimeError(f"Column expressions are not supported in "
109
+ f"'{self.__class__.__name__}'. Please apply your "
110
+ f"expressions on the `pd.DataFrame` directly.")
111
+
112
+ def _get_num_rows(self) -> int | None:
113
+ return len(self._data)
@@ -0,0 +1,37 @@
1
+ from typing import Any, TypeAlias
2
+
3
+ try:
4
+ import snowflake.connector
5
+ except ImportError:
6
+ raise ImportError("No module named 'snowflake'. Please install Kumo SDK "
7
+ "with the 'snowflake' extension via "
8
+ "`pip install kumoai[snowflake]`.")
9
+
10
+ Connection: TypeAlias = snowflake.connector.SnowflakeConnection
11
+
12
+
13
+ def connect(**kwargs: Any) -> Connection:
14
+ r"""Opens a connection to a :class:`snowflake` database.
15
+
16
+ If available, will return a connection to the active session.
17
+
18
+ kwargs: Connection arguments, following the :class:`snowflake` protocol.
19
+ """
20
+ try:
21
+ from snowflake.snowpark.context import get_active_session
22
+ return get_active_session().connection
23
+ except Exception:
24
+ pass
25
+
26
+ return snowflake.connector.connect(**kwargs)
27
+
28
+
29
+ from .table import SnowTable # noqa: E402
30
+ from .sampler import SnowSampler # noqa: E402
31
+
32
+ __all__ = [
33
+ 'connect',
34
+ 'Connection',
35
+ 'SnowTable',
36
+ 'SnowSampler',
37
+ ]