feature_column.py 14.2 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
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 six
import logging

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

C
chenxuyi 已提交
33
from propeller.data.functional import _interleave_func
C
chenxuyi 已提交
34 35
from propeller.paddle.data.functional import Dataset
from propeller.paddle.data import example_pb2, feature_pb2
M
Meiyim 已提交
36
import multiprocessing
C
chenxuyi 已提交
37 38 39 40 41

log = logging.getLogger(__name__)

__all__ = [
    'FeatureColumns', 'TextColumn', 'TextIDColumn', 'LabelColumn',
M
Meiyim 已提交
42
    'RawBytesColumn', 'basic_tokenizer', 'Column'
C
chenxuyi 已提交
43 44 45 46
]


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
        if self.vocab is None:
            ids = int(raw)
        else:
            ids = self.vocab[raw]
M
Meiyim 已提交
128
        return np.array(ids, dtype=np.int64)
C
chenxuyi 已提交
129 130 131


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"""
M
Meiyim 已提交
165 166 167 168
        ids = [
            s if isinstance(s, int) else self.vocab.get(s, self.unk_id)
            for s in self.tokenizer(raw)
        ]
C
chenxuyi 已提交
169 170 171 172
        fe = feature_pb2.Feature(int64_list=feature_pb2.Int64List(value=ids))
        return fe

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

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
178
        """doc"""
M
Meiyim 已提交
179 180 181 182
        ids = [
            s if isinstance(s, int) else self.vocab.get(s, self.unk_id)
            for s in self.tokenizer(raw)
        ]
C
chenxuyi 已提交
183 184 185
        return np.array(ids, dtype=np.int64)


M
Meiyim 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
class RawBytesColumn(Column):
    def __init__(self, name):
        self.name = name

    @property
    def output_shapes(self):
        """doc"""
        return [-1]

    @property
    def output_types(self):
        """doc"""
        return 'bytes'

    def raw_to_proto(self, raw):
        """doc"""
        fe = feature_pb2.Feature(bytes_list=BytesList(value=[raw]))
        return fe

    def proto_to_instance(self, feature):
        """doc"""
        ret = feature.bytes_list.value[
            0]  #np.array(feature.int64_list.value, dtype=np.int64)
        return ret

    def raw_to_instance(self, raw):
        """doc"""
        return raw


C
chenxuyi 已提交
216
class TextIDColumn(Column):
C
chenxuyi 已提交
217 218
    """doc"""

C
chenxuyi 已提交
219
    def __init__(self, name):
C
chenxuyi 已提交
220
        """doc"""
C
chenxuyi 已提交
221 222 223 224
        self.name = name

    @property
    def output_shapes(self):
C
chenxuyi 已提交
225
        """doc"""
C
chenxuyi 已提交
226 227 228 229
        return [-1]

    @property
    def output_types(self):
C
chenxuyi 已提交
230
        """doc"""
C
chenxuyi 已提交
231 232 233
        return 'int64'

    def raw_to_proto(self, raw):
C
chenxuyi 已提交
234
        """doc"""
C
chenxuyi 已提交
235 236 237 238 239
        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 已提交
240
        """doc"""
C
chenxuyi 已提交
241 242 243 244
        ret = np.array(feature.int64_list.value, dtype=np.int64)
        return ret

    def raw_to_instance(self, raw):
C
chenxuyi 已提交
245
        """doc"""
C
chenxuyi 已提交
246 247 248 249
        ret = np.array([int(i) for i in raw.split(b' ')], dtype=np.int64)
        return ret


C
chenxuyi 已提交
250 251 252
def _list_files(raw_dir):
    return [os.path.join(raw_dir, p) for p in os.listdir(raw_dir)]

C
chenxuyi 已提交
253

M
Meiyim 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266
_columns = None


def _init_worker(col):
    global _columns
    _columns = col


def _worker_entrence(args):
    args = (_columns, ) + args
    return _make_gz(args)


C
chenxuyi 已提交
267 268
class FeatureColumns(object):
    """A Dataset Factory object"""
C
chenxuyi 已提交
269

C
chenxuyi 已提交
270 271 272
    def __init__(self, columns):
        """doc"""
        self._columns = columns
C
chenxuyi 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

    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')
M
Meiyim 已提交
288 289 290
                pool = multiprocessing.Pool(
                        initializer=_init_worker,
                        initargs=(self._columns, )) 
C
chenxuyi 已提交
291
                args = [(os.path.join(raw_dir, f), os.path.join(gz_dir, f),
M
Meiyim 已提交
292 293 294 295
                         b'\t') for f in raw_file]
                pool.map(_worker_entrence, args)
                pool.close()
                pool.join()
C
chenxuyi 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
            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 已提交
324
            _interleave_func,
C
chenxuyi 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
            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 已提交
358
            _interleave_func,
C
chenxuyi 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
            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 已提交
381
        def _gen():
C
chenxuyi 已提交
382
            if six.PY3:
C
chenxuyi 已提交
383
                source = sys.stdin.buffer
C
chenxuyi 已提交
384 385 386 387 388 389 390 391
            else:
                source = sys.stdin
            while True:
                line = source.readline()
                if len(line) == 0:
                    break
                yield line,

C
chenxuyi 已提交
392
        dataset = Dataset.from_generator_func(_gen)
C
chenxuyi 已提交
393 394 395 396
        if shuffle:
            dataset = dataset.shuffle(buffer_size=1000)

        def _parse_stdin(record_str):
C
chenxuyi 已提交
397
            """function that takes python_str as input"""
C
chenxuyi 已提交
398 399 400 401 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
            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 已提交
433 434 435 436
        """
        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 已提交
437 438
        if use_gz:
            gz_dir = self._make_gz_dataset(data_dir, gz_dir)
C
chenxuyi 已提交
439
            gz_files = _list_files(gz_dir) if gz_dir is not None else gz_dir
C
chenxuyi 已提交
440 441 442
            ds = self._read_gz_dataset(gz_files, **kwargs)
        else:
            if data_dir is not None:
C
chenxuyi 已提交
443
                data_files = _list_files(data_dir)
C
chenxuyi 已提交
444 445 446 447 448 449 450 451 452
            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 已提交
453
        """doc"""
C
chenxuyi 已提交
454 455 456 457 458 459 460
        ds = self._read_stdin_dataset(**kwargs)
        ds.name = name
        return ds


def _make_gz(args):
    try:
M
Meiyim 已提交
461
        columns, from_file, to_file, sep = args
C
chenxuyi 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
        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