feature_column.py 13.1 KB
Newer Older
C
chenxuyi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019 PaddlePaddle 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.
C
chenxuyi 已提交
14
"""FeatureColumns and many Column"""
C
chenxuyi 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals

import os
import sys
import struct
from six.moves import zip, map
import itertools
import gzip
from functools import partial
import multiprocessing
import six
import logging

import numpy as np
from glob import glob
from propeller.paddle.train import distribution

C
chenxuyi 已提交
34
from propeller.data.functional import _interleave_func
C
chenxuyi 已提交
35 36 37 38 39 40 41 42 43 44 45 46
from propeller.paddle.data.functional import Dataset
from propeller.paddle.data import example_pb2, feature_pb2

log = logging.getLogger(__name__)

__all__ = [
    'FeatureColumns', 'TextColumn', 'TextIDColumn', 'LabelColumn',
    'basic_tokenizer', 'Column'
]


def basic_tokenizer(sen):
C
chenxuyi 已提交
47
    """doc"""
C
chenxuyi 已提交
48 49 50 51 52
    seg = sen.split(b' ')
    seg = filter(lambda i: i != b' ', seg)
    return seg


C
chenxuyi 已提交
53 54 55
class Column(object):
    """doc"""

C
chenxuyi 已提交
56
    def __init__(self, name):
C
chenxuyi 已提交
57
        """doc"""
C
chenxuyi 已提交
58 59 60
        pass

    def raw_to_proto(self, raw):
C
chenxuyi 已提交
61
        """doc"""
C
chenxuyi 已提交
62 63 64 65
        return feature_pb2.Feature()

    @property
    def output_shapes(self):
C
chenxuyi 已提交
66
        """doc"""
C
chenxuyi 已提交
67 68 69 70
        pass

    @property
    def output_types(self):
C
chenxuyi 已提交
71
        """doc"""
C
chenxuyi 已提交
72 73 74
        pass

    def proto_to_instance(self, proto):
C
chenxuyi 已提交
75
        """doc"""
C
chenxuyi 已提交
76 77 78
        raise NotImplementedError()

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
79
        """doc"""
C
chenxuyi 已提交
80 81 82 83
        raise NotImplementedError()


class LabelColumn(Column):
C
chenxuyi 已提交
84 85
    """doc"""

C
chenxuyi 已提交
86
    def __init__(self, name, vocab_dict=None, vocab_file=None):
C
chenxuyi 已提交
87
        """doc"""
C
chenxuyi 已提交
88 89 90 91 92 93 94 95 96 97 98 99
        self.name = name
        self.vocab = None
        if vocab_file:
            self.vocab = {
                j.strip(): i
                for i, j in enumerate(open(vocab_file, 'rb').readlines())
            }
        if vocab_dict:
            self.vocab = vocab_dict

    @property
    def output_shapes(self):
C
chenxuyi 已提交
100
        """doc"""
C
chenxuyi 已提交
101 102 103 104
        return [1]

    @property
    def output_types(self):
C
chenxuyi 已提交
105
        """doc"""
C
chenxuyi 已提交
106 107 108
        return 'int64'

    def raw_to_proto(self, raw):
C
chenxuyi 已提交
109
        """doc"""
C
chenxuyi 已提交
110 111 112 113 114 115 116 117
        if self.vocab is None:
            ids = [int(raw)]
        else:
            ids = [self.vocab[raw]]
        fe = feature_pb2.Feature(int64_list=feature_pb2.Int64List(value=ids))
        return fe

    def proto_to_instance(self, feature):
C
chenxuyi 已提交
118
        """doc"""
C
chenxuyi 已提交
119 120 121 122
        ret = np.array(feature.int64_list.value[0], dtype=np.int64)
        return ret

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
123
        """doc"""
C
chenxuyi 已提交
124 125 126 127 128 129 130 131
        if self.vocab is None:
            ids = int(raw)
        else:
            ids = self.vocab[raw]
        return ids


class TextColumn(Column):
C
chenxuyi 已提交
132 133
    """doc"""

C
chenxuyi 已提交
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    def __init__(self,
                 name,
                 unk_id,
                 vocab_file=None,
                 vocab_dict=None,
                 tokenizer=basic_tokenizer):
        self.name = name
        self.tokenizer = tokenizer
        self.unk_id = unk_id
        if not (vocab_file or vocab_dict):
            raise ValueError('at least specify vocab_file or vocab_dict')
        if vocab_file:
            self.vocab = {
                j.strip(): i
                for i, j in enumerate(open(vocab_file, 'rb').readlines())
            }
        if vocab_dict:
            self.vocab = vocab_dict

    @property
    def output_shapes(self):
C
chenxuyi 已提交
155
        """doc"""
C
chenxuyi 已提交
156 157 158 159
        return [-1]

    @property
    def output_types(self):
C
chenxuyi 已提交
160
        """doc"""
C
chenxuyi 已提交
161 162 163
        return 'int64'

    def raw_to_proto(self, raw):
C
chenxuyi 已提交
164
        """doc"""
C
chenxuyi 已提交
165 166 167 168 169
        ids = [self.vocab.get(s, self.unk_id) for s in self.tokenizer(raw)]
        fe = feature_pb2.Feature(int64_list=feature_pb2.Int64List(value=ids))
        return fe

    def proto_to_instance(self, feature):
C
chenxuyi 已提交
170
        """doc"""
C
chenxuyi 已提交
171 172 173 174
        ret = np.array(feature.int64_list.value, dtype=np.int64)
        return ret

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
175
        """doc"""
C
chenxuyi 已提交
176 177 178 179 180
        ids = [self.vocab.get(s, self.unk_id) for s in self.tokenizer(raw)]
        return np.array(ids, dtype=np.int64)


class TextIDColumn(Column):
C
chenxuyi 已提交
181 182
    """doc"""

C
chenxuyi 已提交
183
    def __init__(self, name):
C
chenxuyi 已提交
184
        """doc"""
C
chenxuyi 已提交
185 186 187 188
        self.name = name

    @property
    def output_shapes(self):
C
chenxuyi 已提交
189
        """doc"""
C
chenxuyi 已提交
190 191 192 193
        return [-1]

    @property
    def output_types(self):
C
chenxuyi 已提交
194
        """doc"""
C
chenxuyi 已提交
195 196 197
        return 'int64'

    def raw_to_proto(self, raw):
C
chenxuyi 已提交
198
        """doc"""
C
chenxuyi 已提交
199 200 201 202 203
        ids = [int(s) for s in raw.split(b' ')]
        fe = feature_pb2.Feature(int64_list=feature_pb2.Int64List(value=ids))
        return fe

    def proto_to_instance(self, feature):
C
chenxuyi 已提交
204
        """doc"""
C
chenxuyi 已提交
205 206 207 208
        ret = np.array(feature.int64_list.value, dtype=np.int64)
        return ret

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
209
        """doc"""
C
chenxuyi 已提交
210 211 212 213
        ret = np.array([int(i) for i in raw.split(b' ')], dtype=np.int64)
        return ret


C
chenxuyi 已提交
214 215 216
def _list_files(raw_dir):
    return [os.path.join(raw_dir, p) for p in os.listdir(raw_dir)]

C
chenxuyi 已提交
217

C
chenxuyi 已提交
218 219
class FeatureColumns(object):
    """A Dataset Factory object"""
C
chenxuyi 已提交
220

C
chenxuyi 已提交
221 222 223
    def __init__(self, columns):
        """doc"""
        self._columns = columns
C
chenxuyi 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271

    def _make_gz_dataset(self, raw_dir, gz_dir):
        assert raw_dir or gz_dir, 'data_dir not specified when using gz mode'
        if raw_dir is not None:
            assert os.path.exists(raw_dir), 'raw_dir not exists: %s' % raw_dir
            raw_file = os.listdir(raw_dir)
        if gz_dir is None:
            gz_dir = '%s_gz' % raw_dir.rstrip('/')

        if not os.path.exists(gz_dir):
            os.mkdir(gz_dir)

        if raw_dir is not None:
            if len(raw_file) != 0:
                log.debug('try making gz')
                pool = multiprocessing.Pool()
                args = [(os.path.join(raw_dir, f), os.path.join(gz_dir, f),
                         self._columns, b'\t') for f in raw_file]
                pool.map(_make_gz, args)
                pool.terminate()
            else:
                assert len(
                    os.listdir(gz_dir)
                ) != 0, 'cant find gz file or raw-txt file at [%s] and [%s]' % (
                    raw_dir, gz_dir)
        return gz_dir

    def _read_gz_dataset(self,
                         gz_files,
                         shuffle=False,
                         repeat=True,
                         shard=False,
                         **kwargs):
        if len(gz_files) == 0:
            raise ValueError('reading gz from empty file list: %s' % gz_files)
        log.info('reading gz from %s' % '\n'.join(gz_files))
        dataset = Dataset.from_list(gz_files)
        if repeat:
            dataset = dataset.repeat()

        if shard and distribution.status.mode == distribution.DistributionMode.NCCL:
            log.info('Apply dataset sharding in distribution env')
            train_ds = train_ds.shard(distribution.status.num_replica,
                                      distribution.status.replica_id)

        if shuffle:
            dataset = dataset.shuffle(buffer_size=len(gz_files))
        fn = partial(
C
chenxuyi 已提交
272
            _interleave_func,
C
chenxuyi 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
            map_fn=lambda filename: Dataset.from_record_file(filename),
            cycle_length=len(gz_files),
            block_length=1)
        dataset = dataset.apply(fn)
        if shuffle:
            dataset = dataset.shuffle(buffer_size=1000)

        def _parse_gz(record_str):  # function that takes python_str as input
            ex = example_pb2.Example()
            ex.ParseFromString(record_str)
            ret = []
            fea_dict = ex.features.feature
            for c in self._columns:
                ins = c.proto_to_instance(fea_dict[c.name])
                ret.append(ins)
            return ret

        dataset = dataset.map(_parse_gz)
        return dataset

    def _read_txt_dataset(self,
                          data_files,
                          shuffle=False,
                          repeat=True,
                          **kwargs):
        log.info('reading raw files from %s' % '\n'.join(data_files))
        dataset = Dataset.from_list(data_files)
        if repeat:
            dataset = dataset.repeat()
        if shuffle:
            dataset = dataset.shuffle(buffer_size=len(data_files))

        fn = partial(
C
chenxuyi 已提交
306
            _interleave_func,
C
chenxuyi 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
            map_fn=lambda filename: Dataset.from_file(filename),
            cycle_length=len(data_files),
            block_length=1)
        dataset = dataset.apply(fn)
        if shuffle:
            dataset = dataset.shuffle(buffer_size=1000)

        def _parse_txt_file(
                record_str):  # function that takes python_str as input
            features = record_str.strip(b'\n').split(b'\t')
            ret = [
                column.raw_to_instance(feature)
                for feature, column in zip(features, self._columns)
            ]
            return ret

        dataset = dataset.map(_parse_txt_file)
        return dataset

    def _read_stdin_dataset(self, encoding='utf8', shuffle=False, **kwargs):
        log.info('reading raw files stdin')

C
chenxuyi 已提交
329
        def _gen():
C
chenxuyi 已提交
330
            if six.PY3:
C
chenxuyi 已提交
331
                source = sys.stdin.buffer
C
chenxuyi 已提交
332 333 334 335 336 337 338 339
            else:
                source = sys.stdin
            while True:
                line = source.readline()
                if len(line) == 0:
                    break
                yield line,

C
chenxuyi 已提交
340
        dataset = Dataset.from_generator_func(_gen)
C
chenxuyi 已提交
341 342 343 344
        if shuffle:
            dataset = dataset.shuffle(buffer_size=1000)

        def _parse_stdin(record_str):
C
chenxuyi 已提交
345
            """function that takes python_str as input"""
C
chenxuyi 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            features = record_str.strip(b'\n').split(b'\t')
            ret = [
                column.raw_to_instance(feature)
                for feature, column in zip(features, self._columns)
            ]
            return ret

        dataset = dataset.map(_parse_stdin)
        return dataset

    def _prepare_dataset(self,
                         dataset,
                         map_func_before_batch=None,
                         map_func_after_batch=None,
                         shuffle_buffer_size=None,
                         batch_size=1,
                         pad_id=0,
                         prefetch=None,
                         **kwargs):

        if map_func_before_batch is not None:
            dataset = dataset.map(map_func_before_batch)
        if batch_size:
            dataset = dataset.padded_batch(batch_size, pad_id)
        if map_func_after_batch is not None:
            dataset = dataset.map(map_func_after_batch)
        return dataset

    def build_dataset(self,
                      name,
                      use_gz=True,
                      data_dir=None,
                      gz_dir=None,
                      data_file=None,
                      **kwargs):
C
chenxuyi 已提交
381 382 383 384
        """
        build `Dataset` from `data_dir` or `data_file`
        if `use_gz`, will try to convert data_files to gz format and save to `gz_dir`, if `gz_dir` not given, will create one.
        """
C
chenxuyi 已提交
385 386
        if use_gz:
            gz_dir = self._make_gz_dataset(data_dir, gz_dir)
C
chenxuyi 已提交
387
            gz_files = _list_files(gz_dir) if gz_dir is not None else gz_dir
C
chenxuyi 已提交
388 389 390
            ds = self._read_gz_dataset(gz_files, **kwargs)
        else:
            if data_dir is not None:
C
chenxuyi 已提交
391
                data_files = _list_files(data_dir)
C
chenxuyi 已提交
392 393 394 395 396 397 398 399 400
            elif data_file is not None:
                data_files = [data_file]
            else:
                raise ValueError('data_dir or data_files not specified')
            ds = self._read_txt_dataset(data_files, **kwargs)
        ds.name = name
        return ds

    def build_dataset_from_stdin(self, name, **kwargs):
C
chenxuyi 已提交
401
        """doc"""
C
chenxuyi 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        ds = self._read_stdin_dataset(**kwargs)
        ds.name = name
        return ds


def _make_gz(args):
    try:
        from_file, to_file, columns, sep = args
        if os.path.exists(to_file):
            return
        with open(from_file, 'rb') as fin, gzip.open(to_file, 'wb') as fout:
            log.debug('making gz %s => %s' % (from_file, to_file))
            for i, line in enumerate(fin):
                line = line.strip(b'\n').split(sep)
                #if i % 10000 == 0:
                #    log.debug('making gz %s => %s [%d]' % (from_file, to_file, i))
                if len(line) != len(columns):
                    log.error('columns not match at %s, got %d, expect %d' %
                              (from_file, len(line), len(columns)))
                    continue
                features = {}
                for l, c in zip(line, columns):
                    features[c.name] = c.raw_to_proto(l)
                example = example_pb2.Example(features=feature_pb2.Features(
                    feature=features))
                serialized = example.SerializeToString()
                l = len(serialized)
                data = struct.pack('i%ds' % l, l, serialized)
                fout.write(data)
            log.debug('done making gz %s => %s' % (from_file, to_file))
    except Exception as e:
        log.exception(e)
        raise e