From e665a5cb5123be8885b4edff80a6bbcb12ee0a17 Mon Sep 17 00:00:00 2001 From: sperlingxx Date: Sat, 10 Aug 2019 17:56:57 +0800 Subject: [PATCH 1/2] xgboost/sqlflow_data_source --- scripts/image_build.sh | 5 +- sql/python/sqlflow_submitter/db.py | 8 +- sql/python/sqlflow_submitter/maxcompute.py | 31 ++- .../sqlflow_submitter/xgboost/__init__.py | 12 + .../sqlflow_submitter/xgboost/common.py | 16 ++ .../xgboost/sqlflow_data_source.py | 207 ++++++++++++++++++ .../xgboost/sqlflow_data_source_test.py | 178 +++++++++++++++ 7 files changed, 441 insertions(+), 16 deletions(-) create mode 100644 sql/python/sqlflow_submitter/xgboost/__init__.py create mode 100644 sql/python/sqlflow_submitter/xgboost/common.py create mode 100644 sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py create mode 100644 sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py diff --git a/scripts/image_build.sh b/scripts/image_build.sh index 65ee99cca3..1dcf862f30 100644 --- a/scripts/image_build.sh +++ b/scripts/image_build.sh @@ -104,7 +104,7 @@ fi wget -q http://docs-aliyun.cn-hangzhou.oss.aliyun-inc.com/assets/attach/119096/cn_zh/1557995455961/odpscmd_public.zip unzip -qq odpscmd_public.zip -d /usr/local/odpscmd ln -s /usr/local/odpscmd/bin/odpscmd /usr/local/bin/odpscmd -rm -rf odpscmd_public.zip +rm -rf odpscmd_public.zip # 8. Load sqlflow Jupyter magic command automatically. c.f. https://stackoverflow.com/a/32683001. mkdir -p $IPYTHON_STARTUP @@ -112,3 +112,6 @@ mkdir -p /workspace echo 'get_ipython().magic(u"%reload_ext sqlflow.magic")' >> $IPYTHON_STARTUP/00-first.py echo 'get_ipython().magic(u"%autoreload 2")' >> $IPYTHON_STARTUP/00-first.py curl https://raw.githubusercontent.com/sql-machine-learning/sqlflow/develop/example/jupyter/example.ipynb --output /workspace/example.ipynb + +# 9. install xgboost-launcher +pip install xgboost-launcher==0.0.1 diff --git a/sql/python/sqlflow_submitter/db.py b/sql/python/sqlflow_submitter/db.py index 83c3cd6b6c..f3d56c0c8f 100644 --- a/sql/python/sqlflow_submitter/db.py +++ b/sql/python/sqlflow_submitter/db.py @@ -52,8 +52,10 @@ def reader(): else: field_names = None if cursor.description is None \ else [i[0] for i in cursor.description] - label_idx = field_names.index(label_column_name) - + if label_column_name: + label_idx = field_names.index(label_column_name) + else: + label_idx = None while True: rows = cursor.fetchmany(size = fetch_size) @@ -63,7 +65,7 @@ def reader(): if driver == "mysql": conn.ping(True) for row in rows: - label = row[label_idx] + label = row[label_idx] if label_idx is not None else None features = [] for name in feature_column_names: # FIXME(typhoonzero): Should use correct dtype here. diff --git a/sql/python/sqlflow_submitter/maxcompute.py b/sql/python/sqlflow_submitter/maxcompute.py index 5144aacf02..ab14aa8b37 100644 --- a/sql/python/sqlflow_submitter/maxcompute.py +++ b/sql/python/sqlflow_submitter/maxcompute.py @@ -14,36 +14,41 @@ import numpy as np from odps import ODPS, tunnel + # MaxCompute(odps) does not provide dbapi # Here we use the sdk to operate the database class MaxCompute: @staticmethod def connect(database, user, password, host): return ODPS(user, password, project=database, endpoint=host) - + @staticmethod def db_generator(conn, statement, feature_column_names, - label_column_name, feature_specs, fetch_size): + label_column_name, feature_specs, fetch_size): def reader(): compress = tunnel.CompressOption.CompressAlgorithm.ODPS_ZLIB inst = conn.execute_sql(statement) if not inst.is_successful(): return None - + r = inst.open_reader(tunnel=True, compress_option=compress) field_names = None if r._schema.columns is None \ - else [col.name for col in r._schema.columns] - label_idx = field_names.index(label_column_name) - + else [col.name for col in r._schema.columns] + if label_column_name: + label_idx = field_names.index(label_column_name) + else: + label_idx = None + i = 0 while i < r.count: - expected = r.count-i if r.count-i < fetch_size else fetch_size - for row in [[v[1] for v in rec] for rec in r[i: i+expected]]: - label = row[label_idx] + expected = r.count - i if r.count - i < fetch_size else fetch_size + for row in [[v[1] for v in rec] for rec in r[i: i + expected]]: + label = row[label_idx] if label_idx is not None else None features = [] for name in feature_column_names: if feature_specs[name]["is_sparse"]: - indices = np.fromstring(row[field_names.index(name)], dtype=int, sep=feature_specs[name]["delimiter"]) + indices = np.fromstring(row[field_names.index(name)], dtype=int, + sep=feature_specs[name]["delimiter"]) indices = indices.reshape(indices.size, 1) values = np.ones([indices.size], dtype=np.int32) dense_shape = np.array(feature_specs[name]["shape"], dtype=np.int64) @@ -51,14 +56,16 @@ def reader(): else: # Dense string vector if feature_specs[name]["delimiter"] != "": - cell = np.fromstring(row[field_names.index(name)], dtype=int, sep=feature_specs[name]["delimiter"]) + cell = np.fromstring(row[field_names.index(name)], dtype=int, + sep=feature_specs[name]["delimiter"]) else: cell = row[field_names.index(name)] features.append(cell) yield (tuple(features), [label]) i += expected + return reader - + @staticmethod def insert_values(conn, table, values): compress = tunnel.CompressOption.CompressAlgorithm.ODPS_ZLIB diff --git a/sql/python/sqlflow_submitter/xgboost/__init__.py b/sql/python/sqlflow_submitter/xgboost/__init__.py new file mode 100644 index 0000000000..aa16ad420d --- /dev/null +++ b/sql/python/sqlflow_submitter/xgboost/__init__.py @@ -0,0 +1,12 @@ +# Copyright 2019 The SQLFlow Authors. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/sql/python/sqlflow_submitter/xgboost/common.py b/sql/python/sqlflow_submitter/xgboost/common.py new file mode 100644 index 0000000000..098f183836 --- /dev/null +++ b/sql/python/sqlflow_submitter/xgboost/common.py @@ -0,0 +1,16 @@ +# Copyright 2019 The SQLFlow Authors. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class XGBoostError(Exception): + pass diff --git a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py new file mode 100644 index 0000000000..5ed59643fb --- /dev/null +++ b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py @@ -0,0 +1,207 @@ +# Copyright 2019 The SQLFlow Authors. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import typing +from typing import Iterator + +from launcher.data_units import RecordBuilder + +from .common import XGBoostError +from ..db import connect, insert_values, db_generator +from launcher import DataSource, config_fields, XGBoostResult, XGBoostRecord + + +class FeatureMeta(typing.NamedTuple): + feature_name: str + dtype: str = 'string' + delimiter: str = '' + shape: typing.List[int] = [1] + is_sparse: bool = False + fc_code: str = None + + @classmethod + def convert_shape(cls, value) -> typing.List: + if isinstance(value, str): + shape = eval(value) + assert isinstance(shape, typing.List) + return shape + elif isinstance(value, typing.List): + return value + else: + raise XGBoostError('invalid shape %s of FeatureMeta' % value) + + +class SqlflowDSConfig(typing.NamedTuple): + is_train: bool + standard_select: str + db_config: typing.Dict + is_tf_integrated: bool + # FeatureMetas are useless temporarily, since tf transformation is not supported. + x: typing.List[typing.Dict] + label: typing.Dict = None + group: typing.Dict = None + weight: typing.Dict = None + output_table: str = None + write_batch_size: int = 1024 + + +class SqlflowDataSource(DataSource): + def __init__(self, rank: int, num_worker: int, + column_conf: config_fields.ColumnFields, + source_conf): + super().__init__(rank, num_worker, column_conf, source_conf) + if not isinstance(source_conf, SqlflowDSConfig): + raise XGBoostError("SqlflowDataSource: invalid source conf") + + # TODO: support tf.feature_column transformation + if source_conf.is_tf_integrated: + raise XGBoostError('So far, tf transformation is not supported in xgboost job.') + + self._train = source_conf.is_train + self._rcd_builder = RecordBuilder(column_conf.features) + + spec_temp = {'is_sparse': False, 'shape': [1], 'delimiter': ''} + metas = {} + col_names = [] + for col in column_conf.features.columns: + col_names.append(col) + metas[col] = spec_temp + self._feature_len = len(col_names) + + self._label_offset = -1 + self._group_offset = -1 + self._weight_offset = -1 + self._append_indices = [] + if self._train: + # label, group, weight column are training specialized + if column_conf.label: + self._label_offset = len(col_names) + col_names.append(column_conf.label) + metas[column_conf.label] = spec_temp + + if column_conf.group: + self._group_offset = len(col_names) + col_names.append(column_conf.group) + metas[column_conf.group] = spec_temp + + if column_conf.weight: + self._weight_offset = len(col_names) + col_names.append(column_conf.weight) + metas[column_conf.weight] = spec_temp + else: + # append columns are prediction specialized + for col in column_conf.append_columns: + if col in metas: + self._append_indices.append(col_names.index(col)) + else: + self._append_indices.append(len(col_names)) + col_names.append(col) + metas[col] = spec_temp + + self._result_schema = {'append_columns': column_conf.append_columns or []} + self._result_schema.update(column_conf.result_columns._asdict()) + + conn = connect(**source_conf.db_config) + + self._reader = db_generator( + driver=source_conf.db_config['driver'], + conn=conn, + statement=source_conf.standard_select, + feature_column_names=col_names, + label_column_name=None, + feature_specs=metas) + + self._write_partial = None + if not self._train: + if not source_conf.output_table: + raise XGBoostError('Output_table must be defined in xgboost prediction job.') + + def write_data_partial(table_schema, data): + insert_values( + driver=source_conf.db_config['driver'], + conn=conn, + table_name=source_conf.output_table, + table_schema=table_schema, + values=data) + + self._write_partial = write_data_partial + self._write_batch_size = source_conf.write_batch_size + self._write_buffer = [] + + def _read_impl(self): + label = None + group = None + weight = 1.0 + append_cols = [] + for columns, _ in self._reader(): + features = columns[:self._feature_len] + if self._label_offset >= 0: + label = columns[self._label_offset] + if self._group_offset >= 0: + group = columns[self._group_offset] + if self._weight_offset >= 0: + weight = columns[self._weight_offset] + if self._append_indices: + append_cols = [columns[i] for i in self._append_indices] + yield features, label, group, weight, append_cols + + def read(self) -> Iterator[XGBoostRecord]: + for features, label, group, weight, append_cols in self._read_impl(): + yield self._rcd_builder.build(features, label, group, weight, append_info=append_cols) + + def write(self, result_iter: Iterator[XGBoostResult]): + # peek one record for schema inference + peek_ret = result_iter.__next__() + + # build table_schema + table_schema = [self._result_schema['result_column']] + table_schema.extend(self._result_schema['append_columns']) + output_leaf = False + if peek_ret.leaf_indices and self._result_schema['leaf_column']: + output_leaf = True + table_schema.append(self._result_schema['leaf_column']) + output_prob = False + if peek_ret.classification_prob and self._result_schema['probability_column']: + output_prob = True + table_schema.append(self._result_schema['probability_column']) + output_detail = False + if peek_ret.classification_detail and self._result_schema['detail_column']: + output_detail = True + table_schema.append(self._result_schema['detail_column']) + + def append_row(xgb_ret: XGBoostResult): + row = [xgb_ret.result] + if xgb_ret.append_info: + row.extend(xgb_ret.append_info) + if output_leaf: + row.append(','.join(map(str, xgb_ret.leaf_indices))) + if output_prob: + row.append(xgb_ret.classification_prob) + if output_detail: + detail = {i: p for i, p in enumerate(xgb_ret.classification_detail)} + row.append(json.dumps(detail)) + self._write_buffer.append(row) + + # append the peek record + append_row(peek_ret) + + # batching write with a buffer + for ret in result_iter: + append_row(ret) + if len(self._write_buffer) >= self._write_batch_size: + self._write_partial(table_schema, self._write_buffer) + self._write_buffer = [] + + # clean the buffer + if self._write_buffer: + self._write_partial(table_schema, self._write_buffer) diff --git a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py new file mode 100644 index 0000000000..f6b0fcbd39 --- /dev/null +++ b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py @@ -0,0 +1,178 @@ +# Copyright 2019 The SQLFlow Authors. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import os +from unittest import TestCase + +from sqlflow_submitter.xgboost.sqlflow_data_source import SqlflowDSConfig, SqlflowDataSource +from launcher import config_helper, config_fields, register_data_source, XGBoostRecord, XGBoostResult +from launcher.data_source import create_data_source_init_fn +from sqlflow_submitter.db_test import execute as db_exec +from sqlflow_submitter.db import connect, insert_values + + +class TestSqlflowDataSource(TestCase): + def setUp(self) -> None: + register_data_source('sqlflow', SqlflowDSConfig, SqlflowDataSource) + + db_conf = { + 'driver': 'mysql', + 'database': "iris", + 'user': os.environ.get('SQLFLOW_TEST_DB_MYSQL_USER') or "root", + 'password': os.environ.get('SQLFLOW_TEST_DB_MYSQL_PASSWD') or "root", + 'host': '127.0.0.1', + 'port': '3306', + } + + def mk_ds_conf(is_train): + return { + 'db_config': db_conf, + 'standard_select': 'select * from input_table', + 'is_tf_integrated': False, + 'is_train': is_train, + 'x': [], + 'output_table': None if is_train else 'output_table', + } + + train_ds_conf = mk_ds_conf(True) + pred_ds_conf = mk_ds_conf(False) + + def mk_col_conf(is_train): + col_conf = { + 'features': {'columns': 'f1,f3,f2', 'feature_num': 3}, + } + if is_train: + col_conf['label'] = 'label1' + col_conf['group'] = 'group1' + col_conf['weight'] = 'weight1' + else: + col_conf['append_columns'] = ['a1', 'a2', 'f3'] + col_conf['result_columns'] = { + 'result_column': 'result', + 'probability_column': 'prob', + 'detail_column': 'detail', + 'leaf_column': 'leaf' + } + return col_conf + + train_col_conf = mk_col_conf(True) + pred_col_conf = mk_col_conf(False) + + conn = connect(**db_conf) + + def run_sql(statement): + return db_exec(db_conf['driver'], conn, statement) + + run_sql("DROP TABLE IF EXISTS input_table") + run_sql(""" + CREATE TABLE input_table( + f1 float, f2 float, f3 float, + label1 int, weight1 float, group1 int, + a1 varchar(10), a2 varchar(10) + )""") + self._data = [1.1, 2.2, 3.3, 4.5, 1, 2, 'A1', "A2"] + data = [self._data[:] for _ in range(100)] + schema = ['f1', 'f2', 'f3', 'weight1', 'label1', 'group1', 'a1', 'a2'] + insert_values(db_conf['driver'], conn, 'input_table', schema, data) + self._sql = run_sql + + run_sql("DROP TABLE IF EXISTS output_table") + run_sql(""" + CREATE TABLE output_table( + result float, prob float, detail VARCHAR(100), leaf VARCHAR(100), + a1 varchar(10), a2 varchar(10), f3 float + )""") + self._ret = XGBoostResult( + result=1.0, + classification_prob=0.8, + classification_detail=[0.15, 0.8, 0.05], + leaf_indices=[1, 2, 3, 4, 5], + append_info=["A1", "A2", 3.3]) + + def build_ds(is_train): + ds_conf = train_ds_conf if is_train else pred_ds_conf + col_conf = train_col_conf if is_train else pred_col_conf + ds_fields = config_helper.load_config( + config_fields.DataSourceFields, + **{'name': "sqlflow", 'config': ds_conf}) + init_fn = create_data_source_init_fn(ds_fields) + col_fields = config_helper.load_config(config_fields.ColumnFields, **col_conf) + return init_fn(0, 1, col_fields) + + self._ds_builder = build_ds + + def test_build(self): + if os.environ.get('SQLFLOW_TEST_DB') != "mysql": + return + + ds = self._ds_builder(True) + assert isinstance(ds, SqlflowDataSource) + assert ds._label_offset == 3 + assert ds._group_offset == 4 + assert ds._weight_offset == 5 + + ds = self._ds_builder(False) + assert isinstance(ds, SqlflowDataSource) + assert ds._append_indices == [3, 4, 1] + + def test_read(self): + if os.environ.get('SQLFLOW_TEST_DB') != "mysql": + return + + ds = self._ds_builder(True) + i = 0 + for rcd in ds.read(): + assert rcd.indices == [0, 1, 2] + # order of feature columns: [f1, f3, f2] + assert rcd.values == [self._data[0], self._data[2], self._data[1]] + assert rcd.weight == self._data[3] + assert rcd.label == self._data[4] + assert rcd.group == self._data[5] + i += 1 + assert i == 100 + + ds = self._ds_builder(False) + i = 0 + for rcd in ds.read(): + assert rcd.indices == [0, 1, 2] + # order of feature columns: [f1, f3, f2] + assert rcd.values == [self._data[0], self._data[2], self._data[1]] + # append columns: [a1, a2, f3] + assert rcd.append_info == [self._data[-2], self._data[-1], self._data[2]] + i += 1 + assert i == 100 + + def test_write(self): + if os.environ.get('SQLFLOW_TEST_DB') != "mysql": + return + + ds = self._ds_builder(False) + ds.write((self._ret for _ in range(100))) + + indices, cols = self._sql("select * from output_table") + app_fields = ds._result_schema['append_columns'] + for idx, c_values in zip(*(indices, cols)): + for c_val in c_values: + if idx == 'result': + assert c_val == self._ret.result + elif idx == 'prob': + assert c_val == self._ret.classification_prob + elif idx == 'detail': + detail = [(k, v) for k, v in json.loads(c_val).items()] + sorted(detail, key=lambda x: x[0]) + detail = [v for _, v in detail] + assert detail == self._ret.classification_detail + elif idx == 'leaf': + assert list(map(int, c_val.split(','))) == self._ret.leaf_indices + if idx in app_fields: + assert c_val == self._ret.append_info[app_fields.index(idx)] From 37c288bb8374fee2a86a3d150c437f84a45961a4 Mon Sep 17 00:00:00 2001 From: sperlingxx Date: Mon, 12 Aug 2019 10:52:50 +0800 Subject: [PATCH 2/2] refine --- .../sqlflow_submitter/xgboost/sqlflow_data_source.py | 6 +++++- .../xgboost/sqlflow_data_source_test.py | 10 +++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py index 5ed59643fb..d773b72826 100644 --- a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py +++ b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py @@ -55,7 +55,7 @@ class SqlflowDSConfig(typing.NamedTuple): write_batch_size: int = 1024 -class SqlflowDataSource(DataSource): +class SqlFlowDataSource(DataSource): def __init__(self, rank: int, num_worker: int, column_conf: config_fields.ColumnFields, source_conf): @@ -70,6 +70,9 @@ def __init__(self, rank: int, num_worker: int, self._train = source_conf.is_train self._rcd_builder = RecordBuilder(column_conf.features) + # concatenate all column fields in use into `col_names` + # in training mode, there exists [features, label, group(optional), weight(optional)] + # in prediction mode, there exists [features, result_columns, additional_columns(optional)] spec_temp = {'is_sparse': False, 'shape': [1], 'delimiter': ''} metas = {} col_names = [] @@ -113,6 +116,7 @@ def __init__(self, rank: int, num_worker: int, conn = connect(**source_conf.db_config) + # Since label field has already been included into `col_names`, we just fill `label_column_name` with None. self._reader = db_generator( driver=source_conf.db_config['driver'], conn=conn, diff --git a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py index f6b0fcbd39..51f98909fc 100644 --- a/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py +++ b/sql/python/sqlflow_submitter/xgboost/sqlflow_data_source_test.py @@ -14,16 +14,16 @@ import os from unittest import TestCase -from sqlflow_submitter.xgboost.sqlflow_data_source import SqlflowDSConfig, SqlflowDataSource +from sqlflow_submitter.xgboost.sqlflow_data_source import SqlflowDSConfig, SqlFlowDataSource from launcher import config_helper, config_fields, register_data_source, XGBoostRecord, XGBoostResult from launcher.data_source import create_data_source_init_fn from sqlflow_submitter.db_test import execute as db_exec from sqlflow_submitter.db import connect, insert_values -class TestSqlflowDataSource(TestCase): +class TestSqlFlowDataSource(TestCase): def setUp(self) -> None: - register_data_source('sqlflow', SqlflowDSConfig, SqlflowDataSource) + register_data_source('sqlflow', SqlflowDSConfig, SqlFlowDataSource) db_conf = { 'driver': 'mysql', @@ -116,13 +116,13 @@ def test_build(self): return ds = self._ds_builder(True) - assert isinstance(ds, SqlflowDataSource) + assert isinstance(ds, SqlFlowDataSource) assert ds._label_offset == 3 assert ds._group_offset == 4 assert ds._weight_offset == 5 ds = self._ds_builder(False) - assert isinstance(ds, SqlflowDataSource) + assert isinstance(ds, SqlFlowDataSource) assert ds._append_indices == [3, 4, 1] def test_read(self):