def test_max_ventilation_size(self): """Tests that we dont surpass a max ventilation size in each pool type (since it relies on accurate ventilation size reporting)""" max_ventilation_size = 10 for pool in [DummyPool(), ProcessPool(10), ThreadPool(10)]: ventilator = ConcurrentVentilator(ventilate_fn=pool.ventilate, items_to_ventilate=[{'item': i} for i in range(100)], max_ventilation_queue_size=max_ventilation_size) pool.start(IdentityWorker, ventilator=ventilator) # Give time for the thread to fill the ventilation queue while ventilator._ventilated_items_count - ventilator._processed_items_count < max_ventilation_size: time.sleep(.1) # After stopping the ventilator queue, we should only get 10 results ventilator.stop() for _ in range(max_ventilation_size): pool.get_results() with self.assertRaises(EmptyResultError): pool.get_results() pool.stop() pool.join()
def test_exception_in_worker_process(self): """ Test exception handler in process pool """ # NOTE: The process pool has a problem that if the workers are throwing exceptions, their # zmq sockets will be closed and there is some race condition that can cause the ventilate # to raise an exception. Only ventilating a single time guarantees that it will be properly # sent to a worker before it has exited due to an exception self._test_exception_in_worker_impl(ProcessPool(10), 1)
def test_read_with_pyarrow_serialization(synthetic_dataset): with Reader(synthetic_dataset.url, reader_pool=ProcessPool(1, pyarrow_serialize=True)) as reader: for actual in reader: expected = next(d for d in synthetic_dataset.data if d['id'] == actual.id) assert actual.id == expected['id'] assert Decimal(actual.decimal) == expected['decimal'] np.testing.assert_equal(actual.matrix, expected['matrix'])
def _create_worker_pool(pool_type, workers_count, profiling_enabled, pyarrow_serialize): """Different worker pool implementation (in process none or thread-pool, out of process pool)""" if pool_type == WorkerPoolType.THREAD: worker_pool = ThreadPool(workers_count, profiling_enabled=profiling_enabled) elif pool_type == WorkerPoolType.PROCESS: worker_pool = ProcessPool(workers_count, serializer=PyArrowSerializer() if pyarrow_serialize else PickleSerializer()) elif pool_type == WorkerPoolType.NONE: worker_pool = DummyPool() else: raise ValueError('Supported pool types are thread, process or dummy. Got {}.'.format(pool_type)) return worker_pool
def test_exception_in_all_worker_process(self): """ Tests that when all worker processes have exited, zmq will properly throw an exception when trying to ventilate instead of blocking indefinitely""" pool = ProcessPool(5) pool.start(ExceptionGeneratingWorker_5) with self.assertRaises(RuntimeError): for _ in range(10000): pool.ventilate("Datanum") time.sleep(.1)
def test_worker_produces_no_results(self): """Check edge case, when workers consistently does not produce results""" # 10000 is an interesting case as in the original implementation it caused stack overflow for ventilate_count in [10, 10000]: for pool in [DummyPool(), ThreadPool(2), ProcessPool(2)]: pool.start(PreprogrammedReturnValueWorker, ventilate_count * [[]]) for _ in range(ventilate_count): pool.ventilate('not_important') with self.assertRaises(EmptyResultError): pool.get_results() pool.stop() pool.join()
def test_worker_produces_some_results(self): """Check edge case, when workers consistently does not produce results""" # 10000 is an interesting case as in the original implementation it caused stack overflow VENTILATE_COUNT = 4 for pool in [DummyPool(), ThreadPool(1), ProcessPool(1)]: pool.start(PreprogrammedReturnValueWorker, [[], [], [42], []]) for _ in range(VENTILATE_COUNT): pool.ventilate('not_important') self.assertEqual(42, pool.get_results()) with self.assertRaises(EmptyResultError): pool.get_results() pool.stop() pool.join()
def test_passing_args_processes(self): for zmq_copy_buffers in [False, True]: self._passing_args_impl(lambda do_copy=zmq_copy_buffers: ProcessPool(10, zmq_copy_buffers=do_copy))
def run_process_pool(return_list): pool = ProcessPool(1) pool.start(WorkerIdGeneratingWorker) return_list.append(pool._workers[0].pid)
def make_batch_reader(dataset_url, schema_fields=None, reader_pool_type='thread', workers_count=10, shuffle_row_groups=True, shuffle_row_drop_partitions=1, predicate=None, rowgroup_selector=None, num_epochs=1, cur_shard=None, shard_count=None, cache_type='null', cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3'): """ Creates an instance of Reader for reading batches out of a non-Petastorm Parquet store. Currently, only stores having native scalar parquet data types are supported. Use :func:`~petastorm.make_reader` to read Petastorm Parquet stores generated with :func:`~petastorm.etl.dataset_metadata.materialize_dataset`. NOTE: only scalar columns are currently supported. :param dataset_url: an filepath or a url to a parquet directory, e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/parquet8'``, or ``'file:///tmp/mydataset'`` or ``'s3://bucket/mydataset'``. :param schema_fields: A list of regex pattern strings. Only columns matching at least one of the patterns in the list will be loaded. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param shuffle_row_groups: Whether to shuffle row groups (the order in which full row groups are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a row group into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each row group read will drop half of the rows within every row group and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. The predicate will be passed a pandas DataFrame object and must return a pandas Series with boolean values of matching dimensions. :param rowgroup_selector: instance of row group selector object to select row groups to be read :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :return: A :class:`Reader` object """ if dataset_url is None or not isinstance(dataset_url, six.string_types): raise ValueError("""dataset_url must be a string""") dataset_url = dataset_url[:-1] if dataset_url[-1] == '/' else dataset_url logger.debug('dataset_url: %s', dataset_url) resolver = FilesystemResolver(dataset_url, hdfs_driver=hdfs_driver) filesystem = resolver.filesystem() dataset_path = resolver.parsed_dataset_url().path if cache_type is None or cache_type == 'null': cache = NullCache() elif cache_type == 'local-disk': cache = LocalDiskArrowTableCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count) elif reader_pool_type == 'process': serializer = ArrowTableSerializer() reader_pool = ProcessPool(workers_count, serializer) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError( 'Unknown reader_pool_type: {}'.format(reader_pool_type)) return Reader(filesystem, dataset_path, schema_fields=schema_fields, worker_class=ArrowReaderWorker, reader_pool=reader_pool, shuffle_row_groups=shuffle_row_groups, shuffle_row_drop_partitions=shuffle_row_drop_partitions, predicate=predicate, rowgroup_selector=rowgroup_selector, num_epochs=num_epochs, cur_shard=cur_shard, shard_count=shard_count, cache=cache)
def test_passing_args_processes(self): self._passing_args_impl(lambda: ProcessPool(10))
def make_reader(dataset_url, schema_fields=None, reader_pool_type='thread', workers_count=10, pyarrow_serialize=False, shuffle_row_groups=True, shuffle_row_drop_partitions=1, predicate=None, rowgroup_selector=None, num_epochs=1, cur_shard=None, shard_count=None, cache_type='null', cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3', infer_schema=False, reader_engine='reader_v1', reader_engine_params=None): """ Factory convenience method for :class:`Reader`. :param dataset_url: an filepath or a url to a parquet directory, e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/parquet8'``, or ``'file:///tmp/mydataset'`` or ``'s3://bucket/mydataset'``. :param schema_fields: Either list of unischema fields to subset, or ``None`` to read all fields. OR an NGram object, then it will return an NGram of the specified properties. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param pyarrow_serialize: Whether to use pyarrow for serialization. Currently only applicable to process pool. Defaults to False. :param shuffle_row_groups: Whether to shuffle row groups (the order in which full row groups are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a row group into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each row group read will drop half of the rows within every row group and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. :param rowgroup_selector: instance of row group selector object to select row groups to be read :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :param infer_schema: Whether to infer the unischema object from the parquet schema. Only works for schemas containing certain scalar type. This option allows getting around explicitly generating petastorm metadata using :func:`petastorm.etl.dataset_metadata.materialize_dataset` or petastorm-generate-metadata.py :param reader_engine: Multiple engine implementations exist ('reader_v1' and 'experimental_reader_v2'). 'reader_v1' (the default value) selects a stable reader implementation. :param reader_engine_params: For advanced usage: a dictionary with arguments passed directly to a reader implementation constructor chosen by ``reader_engine`` argument. You should not use this parameter, unless you fine-tuning of a reader. :return: A :class:`Reader` object """ if dataset_url is None or not isinstance(dataset_url, six.string_types): raise ValueError("""dataset_url must be a string""") dataset_url = dataset_url[:-1] if dataset_url[-1] == '/' else dataset_url logger.debug('dataset_url: %s', dataset_url) resolver = FilesystemResolver(dataset_url, hdfs_driver=hdfs_driver) filesystem = resolver.filesystem() dataset_path = resolver.get_dataset_path() if cache_type is None or cache_type == 'null': cache = NullCache() elif cache_type == 'local-disk': cache = LocalDiskCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) if reader_engine == 'reader_v1': if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count) elif reader_pool_type == 'process': reader_pool = ProcessPool(workers_count, pyarrow_serialize=pyarrow_serialize) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError('Unknown reader_pool_type: {}'.format(reader_pool_type)) # Create a dictionary with all ReaderV2 parameters, so we can merge with reader_engine_params if specified kwargs = { 'schema_fields': schema_fields, 'reader_pool': reader_pool, 'shuffle_row_groups': shuffle_row_groups, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, 'predicate': predicate, 'rowgroup_selector': rowgroup_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'cache': cache, 'infer_schema': infer_schema, } if reader_engine_params: kwargs.update(reader_engine_params) return Reader(filesystem, dataset_path, **kwargs) elif reader_engine == 'experimental_reader_v2': if reader_pool_type == 'thread': decoder_pool = ThreadPoolExecutor(workers_count) elif reader_pool_type == 'process': decoder_pool = ProcessPoolExecutor(workers_count) elif reader_pool_type == 'dummy': decoder_pool = SameThreadExecutor() else: raise ValueError('Unknown reader_pool_type: {}'.format(reader_pool_type)) # TODO(yevgeni): once ReaderV2 is ready to be out of experimental status, we should extend # the make_reader interfaces to take shuffling buffer parameters explicitly shuffling_queue = RandomShufflingBuffer(1000, 800) if shuffle_row_groups else NoopShufflingBuffer() # Create a dictionary with all ReaderV2 parameters, so we can merge with reader_engine_params if specified kwargs = { 'schema_fields': schema_fields, 'predicate': predicate, 'rowgroup_selector': rowgroup_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'cache': cache, 'decoder_pool': decoder_pool, 'shuffling_queue': shuffling_queue, 'shuffle_row_groups': shuffle_row_groups, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, 'infer_schema': infer_schema, } if reader_engine_params: kwargs.update(reader_engine_params) return ReaderV2(dataset_url, **kwargs) else: raise ValueError('Unexpected value of reader_engine argument \'%s\'. ' 'Supported reader_engine values are \'reader_v1\' and \'experimental_reader_v2\'', reader_engine)
PartitionKeyInSetPredicate, EqualPredicate from petastorm.unischema import UnischemaField, Unischema from petastorm.workers_pool.dummy_pool import DummyPool from petastorm.workers_pool.process_pool import ProcessPool from petastorm.workers_pool.thread_pool import ThreadPool # pylint: disable=unnecessary-lambda MINIMAL_READER_FLAVOR_FACTORIES = [ lambda url, **kwargs: Reader(url, reader_pool=DummyPool(), **kwargs), lambda url, **kwargs: ReaderV2(url, **kwargs) ] # pylint: disable=unnecessary-lambda ALL_READER_FLAVOR_FACTORIES = MINIMAL_READER_FLAVOR_FACTORIES + [ lambda url, **kwargs: Reader(url, reader_pool=ThreadPool(10), **kwargs), lambda url, **kwargs: Reader(url, reader_pool=ProcessPool(10), **kwargs), lambda url, **kwargs: ReaderV2( url, decoder_pool=ProcessPoolExecutor(10), **kwargs) ] def _check_simple_reader(reader, expected_data): # Read a bunch of entries from the dataset and compare the data to reference def _type(v): return v.dtype if isinstance(v, np.ndarray) else type(v) for row in reader: actual = row._asdict() expected = next(d for d in expected_data if d['id'] == actual['id']) np.testing.assert_equal(actual, expected) actual_types = [_type(v) for v in actual.values()]
}, kwargs)), ] ALL_READER_FLAVOR_FACTORIES = MINIMAL_READER_FLAVOR_FACTORIES + [ lambda url, **kwargs: Reader( url, **_merge_params( { 'reader_pool': ThreadPool(1), 'schema_fields': _NOT_NULL_FIELDS }, kwargs)), lambda url, **kwargs: Reader( url, **_merge_params( { 'reader_pool': ProcessPool(1), 'schema_fields': _NOT_NULL_FIELDS }, kwargs)), ] def _merge_params(base, overwrite): """Merges two dictionaries when values from ``overwrite`` takes precedence over values of ``base`` dictionary. Both input parameters are not modified. :param base: A dictionary :param overwrite: A dictionary. If a value with the same key exists in ``base``, it is overwritten by the value from this dictionary. :return: A combined dictionary """
from petastorm.workers_pool.process_pool import ProcessPool from petastorm.workers_pool.thread_pool import ThreadPool _EXCLUDE_FIELDS = set(TestSchema.fields.values()) \ - {TestSchema.matrix_nullable, TestSchema.string_array_nullable, TestSchema.decimal} MINIMAL_READER_FLAVOR_FACTORIES = [ lambda url, **kwargs: Reader(url, **_merge_params({'reader_pool': DummyPool(), 'schema_fields': _EXCLUDE_FIELDS}, kwargs)), ] ALL_READER_FLAVOR_FACTORIES = MINIMAL_READER_FLAVOR_FACTORIES + [ lambda url, **kwargs: Reader(url, **_merge_params({'reader_pool': ThreadPool(1), 'schema_fields': _EXCLUDE_FIELDS}, kwargs)), lambda url, **kwargs: Reader(url, **_merge_params({'reader_pool': ProcessPool(1), 'schema_fields': _EXCLUDE_FIELDS}, kwargs)), ] def _merge_params(base, overwrite): """Merges two dictionaries when values from ``overwrite`` takes precedence over values of ``base`` dictionary. Both input parameters are not modified. :param base: A dictionary :param overwrite: A dictionary. If a value with the same key exists in ``base``, it is overwritten by the value from this dictionary. :return: A combined dictionary """ # Create a shallow copy of base
def make_batch_reader(dataset_url_or_urls, schema_fields=None, reader_pool_type='thread', workers_count=10, shuffle_row_groups=True, shuffle_row_drop_partitions=1, predicate=None, rowgroup_selector=None, num_epochs=1, cur_shard=None, shard_count=None, shard_seed=None, cache_type='null', cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3', transform_spec=None, filters=None, storage_options=None, zmq_copy_buffers=True, filesystem=None): """ Creates an instance of Reader for reading batches out of a non-Petastorm Parquet store. Currently, only stores having native scalar parquet data types are supported. Use :func:`~petastorm.make_reader` to read Petastorm Parquet stores generated with :func:`~petastorm.etl.dataset_metadata.materialize_dataset`. NOTE: only scalar columns or array type (of primitive type element) columns are currently supported. NOTE: If without `schema_fields` specified, the reader schema will be inferred from parquet dataset. then the reader schema fields order will preserve parqeut dataset fields order (partition column come first), but if setting `transform_spec` and specified `TransformSpec.selected_fields`, then the reader schema fields order will be the order of 'selected_fields'. :param dataset_url_or_urls: a url to a parquet directory or a url list (with the same scheme) to parquet files. e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/parquet8'``, or ``'file:///tmp/mydataset'``, or ``'s3://bucket/mydataset'``, or ``'gs://bucket/mydataset'``, or ``[file:///tmp/mydataset/00000.parquet, file:///tmp/mydataset/00001.parquet]``. :param schema_fields: A list of regex pattern strings. Only columns matching at least one of the patterns in the list will be loaded. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param shuffle_row_groups: Whether to shuffle row groups (the order in which full row groups are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a row group into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each row group read will drop half of the rows within every row group and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. The predicate will be passed a pandas DataFrame object and must return a pandas Series with boolean values of matching dimensions. :param rowgroup_selector: instance of row group selector object to select row groups to be read :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None :param shard_seed: Random seed to shuffle row groups for data sharding. Defaults to None :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :param transform_spec: An instance of :class:`~petastorm.transform.TransformSpec` object defining how a record is transformed after it is loaded and decoded. The transformation occurs on a worker thread/process (depends on the ``reader_pool_type`` value). :param filters: (List[Tuple] or List[List[Tuple]]): Standard PyArrow filters. These will be applied when loading the parquet file with PyArrow. More information here: https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetDataset.html :param storage_options: Dict of kwargs forwarded to ``fsspec`` to initialize the filesystem. :param zmq_copy_buffers: A bool indicating whether to use 0mq copy buffers with ProcessPool. :param filesystem: An instance of ``pyarrow.FileSystem`` to use. Will ignore storage_options and other filesystem configs if it's provided. :return: A :class:`Reader` object """ dataset_url_or_urls = normalize_dataset_url_or_urls(dataset_url_or_urls) filesystem, dataset_path_or_paths = get_filesystem_and_path_or_paths( dataset_url_or_urls, hdfs_driver, storage_options=storage_options, filesystem=filesystem) try: dataset_metadata.get_schema_from_dataset_url( dataset_url_or_urls, hdfs_driver=hdfs_driver, storage_options=storage_options, filesystem=filesystem) warnings.warn( 'Please use make_reader (instead of \'make_batch_dataset\' function to read this dataset. ' 'You may get unexpected results. ' 'Currently make_batch_reader supports reading only Parquet stores that contain ' 'standard Parquet data types and do not require petastorm decoding.' ) except PetastormMetadataError: pass if cache_type is None or cache_type == NULL_CACHE: cache = NullCache() elif cache_type == LOCAL_DISK_CACHE: cache = LocalDiskArrowTableCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count) elif reader_pool_type == 'process': serializer = ArrowTableSerializer() reader_pool = ProcessPool(workers_count, serializer, zmq_copy_buffers=zmq_copy_buffers) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError( 'Unknown reader_pool_type: {}'.format(reader_pool_type)) return Reader(filesystem, dataset_path_or_paths, schema_fields=schema_fields, worker_class=ArrowReaderWorker, reader_pool=reader_pool, shuffle_row_groups=shuffle_row_groups, shuffle_row_drop_partitions=shuffle_row_drop_partitions, predicate=predicate, rowgroup_selector=rowgroup_selector, num_epochs=num_epochs, cur_shard=cur_shard, shard_count=shard_count, shard_seed=shard_seed, cache=cache, transform_spec=transform_spec, is_batched_reader=True, filters=filters)
def make_reader(dataset_url, schema_fields=None, reader_pool_type='thread', workers_count=10, pyarrow_serialize=False, results_queue_size=50, shuffle_row_groups=True, shuffle_row_drop_partitions=1, predicate=None, rowgroup_selector=None, num_epochs=1, cur_shard=None, shard_count=None, shard_seed=None, cache_type=NULL_CACHE, cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3', transform_spec=None, filters=None, storage_options=None, zmq_copy_buffers=True, filesystem=None): """ Creates an instance of Reader for reading Petastorm datasets. A Petastorm dataset is a dataset generated using :func:`~petastorm.etl.dataset_metadata.materialize_dataset` context manager as explained `here <https://petastorm.readthedocs.io/en/latest/readme_include.html#generating-a-dataset>`_. See :func:`~petastorm.make_batch_reader` to read from a Parquet store that was not generated using :func:`~petastorm.etl.dataset_metadata.materialize_dataset`. :param dataset_url: an filepath or a url to a parquet directory, e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/parquet8'``, or ``'file:///tmp/mydataset'``, or ``'s3://bucket/mydataset'``, or ``'gs://bucket/mydataset'``. :param schema_fields: Can be: a list of unischema fields and/or regex pattern strings; ``None`` to read all fields; an NGram object, then it will return an NGram of the specified fields. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param pyarrow_serialize: THE ARGUMENT IS DEPRECATED AND WILL BE REMOVED IN FUTURE VERSIONS. :param results_queue_size: Size of the results queue to store prefetched row-groups. Currently only applicable to thread reader pool type. :param shuffle_row_groups: Whether to shuffle row groups (the order in which full row groups are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a row group into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each row group read will drop half of the rows within every row group and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. The predicate will be passed a single row and must return a boolean value indicating whether to include it in the results. :param rowgroup_selector: instance of row group selector object to select row groups to be read :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None :param shard_seed: Random seed to shuffle row groups for data sharding. Defaults to None :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :param transform_spec: An instance of :class:`~petastorm.transform.TransformSpec` object defining how a record is transformed after it is loaded and decoded. The transformation occurs on a worker thread/process (depends on the ``reader_pool_type`` value). :param filters: (List[Tuple] or List[List[Tuple]]): Standard PyArrow filters. These will be applied when loading the parquet file with PyArrow. More information here: https://arrow.apache.org/docs/python/generated/pyarrow.parquet.ParquetDataset.html :param storage_options: Dict of kwargs forwarded to ``fsspec`` to initialize the filesystem. :param zmq_copy_buffers: A bool indicating whether to use 0mq copy buffers with ProcessPool. :param filesystem: An instance of ``pyarrow.FileSystem`` to use. Will ignore storage_options and other filesystem configs if it's provided. :return: A :class:`Reader` object """ dataset_url = normalize_dir_url(dataset_url) filesystem, dataset_path = get_filesystem_and_path_or_paths( dataset_url, hdfs_driver, storage_options=storage_options, filesystem=filesystem) if cache_type is None or cache_type == NULL_CACHE: cache = NullCache() elif cache_type == LOCAL_DISK_CACHE: cache = LocalDiskCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) try: dataset_metadata.get_schema_from_dataset_url( dataset_url, hdfs_driver=hdfs_driver, storage_options=storage_options, filesystem=filesystem) except PetastormMetadataError: warnings.warn( 'Currently make_reader supports reading only Petastorm datasets. ' 'To read from a non-Petastorm Parquet store use make_batch_reader') if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count, results_queue_size) elif reader_pool_type == 'process': if pyarrow_serialize: warnings.warn( "pyarrow_serializer was deprecated and will be removed in future versions. " "The argument no longer has any effect.") serializer = PickleSerializer() reader_pool = ProcessPool(workers_count, serializer, zmq_copy_buffers=zmq_copy_buffers) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError( 'Unknown reader_pool_type: {}'.format(reader_pool_type)) kwargs = { 'schema_fields': schema_fields, 'reader_pool': reader_pool, 'shuffle_row_groups': shuffle_row_groups, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, 'predicate': predicate, 'rowgroup_selector': rowgroup_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'shard_seed': shard_seed, 'cache': cache, 'transform_spec': transform_spec, 'filters': filters } try: return Reader(filesystem, dataset_path, worker_class=PyDictReaderWorker, is_batched_reader=False, **kwargs) except PetastormMetadataError as e: logger.error('Unexpected exception: %s', str(e)) raise RuntimeError( 'make_reader has failed. If you were trying to open a Parquet store that was not ' 'created using Petastorm materialize_dataset and it contains only scalar columns, ' 'you may use make_batch_reader to read it.\n' 'Inner exception: %s', str(e))
def test_all_workers_are_active_processes(self): """Check that the work is distributed among all workers""" WORKERS_COUNT = 10 # Testing only ProcessPool since only it has the mechanism that waits for all workers to come online before # start finishes pool = ProcessPool(WORKERS_COUNT) pool.start(WorkerIdGeneratingWorker) for _ in range(100): pool.ventilate() active_worker_ids = [pool.get_results() for _ in range(100)] self.assertEqual(set(range(WORKERS_COUNT)), set(active_worker_ids)) pool.stop() pool.join()
def test_ventilator_processes(self): self._test_simple_ventilation(lambda: ProcessPool(10))
def make_reader(dataset_url, schema_fields=None, reader_pool_type='thread', workers_count=10, pyarrow_serialize=False, results_queue_size=50, shuffle_row_groups=True, shuffle_row_drop_partitions=1, predicate=None, rowgroup_selector=None, num_epochs=1, cur_shard=None, shard_count=None, cache_type='null', cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3', reader_engine='reader_v1', reader_engine_params=None): """ Creates an instance of Reader for reading Petastorm datasets. A Petastorm dataset is a dataset generated using :func:`~petastorm.etl.dataset_metadata.materialize_dataset` context manager as explained `here <https://petastorm.readthedocs.io/en/latest/readme_include.html#generating-a-dataset>`_. See :func:`~petastorm.make_batch_reader` to read from a Parquet store that was not generated using :func:`~petastorm.etl.dataset_metadata.materialize_dataset`. :param dataset_url: an filepath or a url to a parquet directory, e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/parquet8'``, or ``'file:///tmp/mydataset'`` or ``'s3://bucket/mydataset'``. :param schema_fields: Can be: a list of unischema fields and/or regex pattern strings; ``None`` to read all fields; an NGram object, then it will return an NGram of the specified fields. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param pyarrow_serialize: Whether to use pyarrow for serialization. Currently only applicable to process pool. Defaults to False. :param results_queue_size: Size of the results queue to store prefetched rows. Currently only applicable to thread reader pool type. :param shuffle_row_groups: Whether to shuffle row groups (the order in which full row groups are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a row group into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each row group read will drop half of the rows within every row group and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. The predicate will be passed a single row and must return a boolean value indicating whether to include it in the results. :param rowgroup_selector: instance of row group selector object to select row groups to be read :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :param reader_engine: Multiple engine implementations exist ('reader_v1' and 'experimental_reader_v2'). 'reader_v1' (the default value) selects a stable reader implementation. :param reader_engine_params: For advanced usage: a dictionary with arguments passed directly to a reader implementation constructor chosen by ``reader_engine`` argument. You should not use this parameter, unless you fine-tuning of a reader. :return: A :class:`Reader` object """ if dataset_url is None or not isinstance(dataset_url, six.string_types): raise ValueError("""dataset_url must be a string""") dataset_url = dataset_url[:-1] if dataset_url[-1] == '/' else dataset_url logger.debug('dataset_url: %s', dataset_url) resolver = FilesystemResolver(dataset_url, hdfs_driver=hdfs_driver) filesystem = resolver.filesystem() dataset_path = resolver.get_dataset_path() if cache_type is None or cache_type == 'null': cache = NullCache() elif cache_type == 'local-disk': cache = LocalDiskCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) # Fail if this is a non-petastorm dataset. Typically, a Parquet store will have hundred thousands rows in a single # rowgroup. Using PyDictReaderWorker or ReaderV2 implementation is very inefficient as it processes data on a # row by row basis. ArrowReaderWorker (used by make_batch_reader) is much more efficient in these cases. try: dataset_metadata.get_schema_from_dataset_url(dataset_url) except PetastormMetadataError: raise RuntimeError( 'Currently make_reader supports reading only Petastorm datasets. ' 'To read from a non-Petastorm Parquet store use make_batch_reader') if reader_engine == 'reader_v1': if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count, results_queue_size) elif reader_pool_type == 'process': if pyarrow_serialize: serializer = PyArrowSerializer() else: serializer = PickleSerializer() reader_pool = ProcessPool(workers_count, serializer) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError( 'Unknown reader_pool_type: {}'.format(reader_pool_type)) # Create a dictionary with all ReaderV2 parameters, so we can merge with reader_engine_params if specified kwargs = { 'schema_fields': schema_fields, 'reader_pool': reader_pool, 'shuffle_row_groups': shuffle_row_groups, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, 'predicate': predicate, 'rowgroup_selector': rowgroup_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'cache': cache, } if reader_engine_params: kwargs.update(reader_engine_params) try: return Reader(filesystem, dataset_path, worker_class=PyDictReaderWorker, **kwargs) except PetastormMetadataError as e: logger.error('Unexpected exception: %s', str(e)) raise RuntimeError( 'make_reader has failed. If you were trying to open a Parquet store that was not ' 'created using Petastorm materialize_dataset and it contains only scalar columns, ' 'you may use make_batch_reader to read it.\n' 'Inner exception: %s', str(e)) elif reader_engine == 'experimental_reader_v2': if reader_pool_type == 'thread': decoder_pool = ThreadPoolExecutor(workers_count) elif reader_pool_type == 'process': decoder_pool = ProcessPoolExecutor(workers_count) elif reader_pool_type == 'dummy': decoder_pool = SameThreadExecutor() else: raise ValueError( 'Unknown reader_pool_type: {}'.format(reader_pool_type)) # TODO(yevgeni): once ReaderV2 is ready to be out of experimental status, we should extend # the make_reader interfaces to take shuffling buffer parameters explicitly shuffling_queue = RandomShufflingBuffer( 1000, 800) if shuffle_row_groups else NoopShufflingBuffer() # Create a dictionary with all ReaderV2 parameters, so we can merge with reader_engine_params if specified kwargs = { 'schema_fields': schema_fields, 'predicate': predicate, 'rowgroup_selector': rowgroup_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'cache': cache, 'decoder_pool': decoder_pool, 'shuffling_queue': shuffling_queue, 'shuffle_row_groups': shuffle_row_groups, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, } if reader_engine_params: kwargs.update(reader_engine_params) return ReaderV2(dataset_url, **kwargs) else: raise ValueError( 'Unexpected value of reader_engine argument \'%s\'. ' 'Supported reader_engine values are \'reader_v1\' and \'experimental_reader_v2\'', reader_engine)
def make_carbon_reader(dataset_url, key=None, secret=None, endpoint=None, proxy=None, proxy_port=None, schema_fields=None, reader_pool_type='thread', workers_count=10, pyarrow_serialize=False, results_queue_size=100, shuffle_blocklets=True, shuffle_row_drop_partitions=1, predicate=None, blocklet_selector=None, num_epochs=1, cur_shard=None, shard_count=None, cache_type='null', cache_location=None, cache_size_limit=None, cache_row_size_estimate=None, cache_extra_settings=None, hdfs_driver='libhdfs3', reader_engine='reader_v1', reader_engine_params=None, transform_spec=None): """ Creates an instance of Reader for reading Pycarbon datasets. A Pycarbon dataset is a dataset generated using :func:`~pycarbon.etl.carbon_dataset_metadata.materialize_dataset_carbon` context manager as explained See :func:`~pycarbon.make_batch_carbon_reader` to read from a Carbon store that was not generated using :func:`~pycarbon.etl.carbon_dataset_metadata.materialize_dataset_carbon`. :param dataset_url: an filepath or a url to a carbon directory, e.g. ``'hdfs://some_hdfs_cluster/user/yevgeni/carbon8'``, or ``'file:///tmp/mydataset'`` or ``'s3://bucket/mydataset'``. :param key: access key :param secret: secret key :param endpoint: endpoint_url :param proxy: proxy :param proxy_port: proxy_port :param schema_fields: Can be: a list of unischema fields and/or regex pattern strings; ``None`` to read all fields; an NGram object, then it will return an NGram of the specified fields. :param reader_pool_type: A string denoting the reader pool type. Should be one of ['thread', 'process', 'dummy'] denoting a thread pool, process pool, or running everything in the master thread. Defaults to 'thread' TODO: process support :param workers_count: An int for the number of workers to use in the reader pool. This only is used for the thread or process pool. Defaults to 10 :param pyarrow_serialize: Whether to use pyarrow for serialization. Currently only applicable to process pool. Defaults to False. :param results_queue_size: Size of the results queue to store prefetched rows. Currently only applicable to thread reader pool type. :param shuffle_blocklets: Whether to shuffle blocklets (the order in which full blocklets are read) :param shuffle_row_drop_partitions: This is is a positive integer which determines how many partitions to break up a blocklet into for increased shuffling in exchange for worse performance (extra reads). For example if you specify 2 each blocklet read will drop half of the rows within every blocklet and read the remaining rows in separate reads. It is recommended to keep this number below the regular row group size in order to not waste reads which drop all rows. :param predicate: instance of :class:`.PredicateBase` object to filter rows to be returned by reader. The predicate will be passed a single row and must return a boolean value indicating whether to include it in the results. :param blocklet_selector: instance of blocklet selector object to select blocklet to be read TODO: blocklet_selector :param num_epochs: An epoch is a single pass over all rows in the dataset. Setting ``num_epochs`` to ``None`` will result in an infinite number of epochs. :param cur_shard: An int denoting the current shard number. Each node reading a shard should pass in a unique shard number in the range [0, shard_count). shard_count must be supplied as well. Defaults to None :param shard_count: An int denoting the number of shards to break this dataset into. Defaults to None TODO: cur_shard & shard_count :param cache_type: A string denoting the cache type, if desired. Options are [None, 'null', 'local-disk'] to either have a null/noop cache or a cache implemented using diskcache. Caching is useful when communication to the main data store is either slow or expensive and the local machine has large enough storage to store entire dataset (or a partition of a dataset if shard_count is used). By default will be a null cache. :param cache_location: A string denoting the location or path of the cache. :param cache_size_limit: An int specifying the size limit of the cache in bytes :param cache_row_size_estimate: An int specifying the estimated size of a row in the dataset :param cache_extra_settings: A dictionary of extra settings to pass to the cache implementation, :param hdfs_driver: A string denoting the hdfs driver to use (if using a dataset on hdfs). Current choices are libhdfs (java through JNI) or libhdfs3 (C++) :param reader_engine: Multiple engine implementations exist ('reader_v1' and 'experimental_reader_v2'). 'reader_v1' (the default value) selects a stable reader implementation. TODO: experimental_reader_v2 for carbon :param reader_engine_params: For advanced usage: a dictionary with arguments passed directly to a reader implementation constructor chosen by ``reader_engine`` argument. You should not use this parameter, unless you fine-tuning of a reader. :param transform_spec: An instance of :class:`~petastorm.transform.TransformSpec` object defining how a record is transformed after it is loaded and decoded. The transformation occurs on a worker thread/process (depends on the ``reader_pool_type`` value). :return: A :class:`Reader` object """ if dataset_url is None or not isinstance(dataset_url, six.string_types): raise ValueError("""dataset_url must be a string""") dataset_url = dataset_url[:-1] if dataset_url[-1] == '/' else dataset_url logger.debug('dataset_url: %s', dataset_url) resolver = CarbonFilesystemResolver(dataset_url, key=key, secret=secret, endpoint=endpoint, proxy=proxy, proxy_port=proxy_port, hdfs_driver=hdfs_driver) filesystem = resolver.filesystem() if cache_type is None or cache_type == 'null': cache = NullCache() elif cache_type == 'local-disk': cache = LocalDiskCache(cache_location, cache_size_limit, cache_row_size_estimate, **cache_extra_settings or {}) elif cache_type == 'memory-cache': cache = LocalMemoryCache(cache_size_limit) else: raise ValueError('Unknown cache_type: {}'.format(cache_type)) # Fail if this is a non-pycarbon dataset. Typically, a Carbon store will have hundred thousands rows in a single # blocklet. Using PyDictCarbonReaderWorker or ReaderV2 implementation is very inefficient as it processes data on a # row by row basis. ArrowCarbonReaderWorker (used by make_batch_carbon_reader) is much more efficient in these cases. try: infer_or_load_unischema_carbon(CarbonDataset(dataset_url, key=key, secret=secret, endpoint=endpoint, proxy=proxy, proxy_port=proxy_port, filesystem=filesystem)) except PycarbonMetadataError: raise RuntimeError('Currently make_reader supports reading only Pycarbon datasets. ' 'To read from a non-Pycarbon Carbon store use make_batch_reader') if reader_engine == 'reader_v1': if reader_pool_type == 'thread': reader_pool = ThreadPool(workers_count, results_queue_size) elif reader_pool_type == 'process': if pyarrow_serialize: serializer = PyArrowSerializer() else: serializer = PickleSerializer() reader_pool = ProcessPool(workers_count, serializer) elif reader_pool_type == 'dummy': reader_pool = DummyPool() else: raise ValueError('Unknown reader_pool_type: {}'.format(reader_pool_type)) # Create a dictionary with all ReaderV2 parameters, so we can merge with reader_engine_params if specified kwargs = { 'key': key, 'secret': secret, 'endpoint': endpoint, 'proxy': proxy, 'proxy_port': proxy_port, 'schema_fields': schema_fields, 'reader_pool': reader_pool, 'shuffle_blocklets': shuffle_blocklets, 'shuffle_row_drop_partitions': shuffle_row_drop_partitions, 'predicate': predicate, 'blocklet_selector': blocklet_selector, 'num_epochs': num_epochs, 'cur_shard': cur_shard, 'shard_count': shard_count, 'cache': cache, 'transform_spec': transform_spec, } if reader_engine_params: kwargs.update(reader_engine_params) try: return CarbonDataReader(filesystem, dataset_url, worker_class=PyDictCarbonReaderWorker, **kwargs) except PycarbonMetadataError as e: logger.error('Unexpected exception: %s', str(e)) raise RuntimeError('make_carbon_reader has failed. If you were trying to open a Carbon store that was not ' 'created using Pycarbon materialize_dataset_carbon and it contains only scalar columns, ' 'you may use make_batch_reader to read it.\n' 'Inner exception: %s', str(e)) elif reader_engine == 'experimental_reader_v2': raise NotImplementedError('not support experimental_reader_v2 reader engine now.') else: raise ValueError('Unexpected value of reader_engine argument \'%s\'. ' 'Supported reader_engine values are \'reader_v1\' and \'experimental_reader_v2\'', reader_engine)