mirror of
https://github.com/pytorch/pytorch.git
synced 2025-10-21 05:34:18 +08:00
* Fix handling of empty batches in SumReduceDimsOp As titled * Deferrable async_scheduling finishRun fix Proper order of finishing run operations in deferrable_async_scheduling net * Simplify exception handling in async_scheduling Simplify exception handling, no need to busy wait, thread that processes the last task can finish the run * [C2]worker_coordinator_memorize_worker_ids As titled. This is related to T28689868, where the number of blobs we want to create is equal to the number of worker ids * Add unit test for nets with no type set * Ignore total length argument in sympolic_pad_packed_sequence 1- There was a mistake in the code that total_length was added to the wrong symbolic function (pack_padded_sequence) instead of (pad_packed_sequence) 2- No need to throw an exception if total_length is given since it is only used to enable data_parallel training on multi-gpus and doesn't have anything to do with onnx export, so just ignore it. https://fburl.com/tk4gciqp * Add support for MKLDNN to async_scheduling Just add MKLDNN as a possible CPU option to async_scheduling's pool function * [AuFL][ensemble] support branch output for prediction This diff supports using predictions from different branches and thus enables model ensembling (not fully independent). * Fix a bug in add_loss in layer_model_helper As titled. * Support lradaption for adam 1.lr adaption operator 2.apply to dense adam * Perf tweaks for async_scheduling Restore single pool option + remove unnecessary (no-ops) calls * add quantization to SparseSimdAdagradOp add a bunch of quantization signatures to SparseSimdAdagradOp, implementations to come next * [sr] [codemod] Change all SR callsites to use new API @allow-large-files This diff refactors all callsites of SR to use the slightly changed API introduced in the diff below. Really what this means is that you need to include the correct header. Also if you were using `ClientFactory::newFactory` you need to not prefix it with `ClientFactory::`. ``` cd ~/fbsource/fbcode find ./ -type f -exec sed -i -e 's:#include "servicerouter/client/cpp2/ClientFactory.h":#include "servicerouter/client/cpp2/ServiceRouter.h":' -e 's:#include <servicerouter/client/cpp2/ClientFactory.h>:#include <servicerouter/client/cpp2/ServiceRouter.h>:' -e 's/ClientFactory::newFactory(/newFactory(/g' {} \; ``` Also manually fixed spots that couldn't be done automatically (or broke because they depended on transitive includes). * Back out "Fix handling of empty batches in SumReduceDimsOp" Original commit changeset: 282da1730cc2 This commit is blocking the Github->fbcode sync, which really needs to get merged ASAP. D7881937 which this diff depends on will be reverted in the sync D7990948 which causes this to break. The sync diff cannot be patched with this reversion because it must be landed against base revision 5c8c099 , and D7881937 must not be included in the sync diff because it is breaking GPU tests that are not available in sandcastle : https://ci.pytorch.org/jenkins/job/caffe2-builds/job/py2-cuda8.0-cudnn6-ubuntu16.04-test/3638/console for one example. * Add the flow to support operator benchmark 1) generate model with the operator 2) upload to everstore 3) generate model spec into json file 4) start running the benchmark * [tum][gpu] Connect DPM trainer with flow and unit tests This diff: - Fix some small bugs for Yiming's recent changes to parallelizer, so it suits real use cases. - Add correct tags to the TUM code, so we can do data parallel transform - pass extra info when instantiation. - add unit test for using DPM in TUM model After this diff, we can do simple box, multi-gpu fully-sync trainer for TUM in Fblearner workflow, but may still need to do speed benchmarking. * w/o normalized lradaption for adam dense only The previous lr adaption includes a normalization step when performing the dot product operation. This is not exactly same as what is proposed in the paper. I add normalization as an option. Without it, the operator performs exactly what the paper proposed. With the option, we add the normalization step * [fb] Use SharedPromise in DeferrableAsyncSchedulingNet This code is to simplify DeferrableAsyncSchedulingNet by removing condition variable + small fixes * [tum] implement cuda sparseLengthsMean and LengthsMean as title * Adding an optional parameter to allow use of protobufs in InferShapesAndTypes function. Adding an optional parameter to allow use of protobufs in InferShapesAndTypes function. * Move feature_to_index to FeatureSpec.feature_to_index move feature_to_index to FeatureSpec.feature_to_index to avoid override other fields * [Caffe2] Rename bytes_moved to bytes_written Just a rename in preparation for supporting bytes_read. * [c2] fix ReduceFrontSumOp for empty case by setting 0 otherwise, it may use the results from last iteration when it's empty batch. * [Caffe2] [Int8] Improve Intel CPU performance * [Easy] Improve PrependDim op logging as titled * DBFileReader expand db_path using os.path.expanduser(..) Since there are a lot of possible use cases of `DBFileReader` to read from user home path, like `~/local/sample.db`, I want to save people's trouble of calling `os.path.expanduser(db_path)` themselves. * [Caffe2] Add bytes_read to cost structure We're adding analytical read bytes to cost functions. This extends the structure accordingly for all CostInference defined operators. Additionally, some small bug fixes were performed: 1) Cost functions now extract type information of operands instead of assuming float * Fix sleef on aarch64 for hhvm @bypass-lint Rename flag * Remove duplicated part in caffe2/ideep/operators/conv_op.cc should be sync error * Rename test helper function test_adagrad_sparse_helper to adagrad_sparse_test_helper to avoid confusing pytest
296 lines
7.7 KiB
Python
296 lines
7.7 KiB
Python
# @package parallel_workers
|
|
# Module caffe2.python.parallel_workers
|
|
from __future__ import absolute_import
|
|
from __future__ import division
|
|
from __future__ import print_function
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
'''
|
|
This module provides a python-land multithreaded mechanism for executing work.
|
|
|
|
Basic usage is as follows:
|
|
coordinator = parallel_workers.init_workers(
|
|
my_worker_fun,
|
|
worker_name="train"
|
|
)
|
|
...
|
|
coordinator.start()
|
|
|
|
First argument is the function to run in a loop on potentially multiple threads.
|
|
It has the call signature
|
|
worker_fun(worker_id)
|
|
|
|
Argument 'worker_name' is used to distinguish different workers,
|
|
such as workers processing train data or workers processing test data.
|
|
|
|
Optionally, one can define an "init function" that is called once before
|
|
threads start, and has call signature:
|
|
my_init_fun(worker_coordinator, global_coordinator)
|
|
|
|
Note that for data_parallel_models, init_workers will be called
|
|
for each GPU. Note that the 'coordinator' returned by the function is same
|
|
each time.
|
|
'''
|
|
|
|
import logging
|
|
import threading
|
|
import atexit
|
|
import time
|
|
import collections
|
|
import six
|
|
import traceback
|
|
|
|
from abc import ABCMeta, abstractmethod
|
|
|
|
log = logging.getLogger("parallel_workers")
|
|
log.setLevel(logging.INFO)
|
|
LOG_INT_SECS = 60
|
|
|
|
|
|
def init_workers(
|
|
worker_fun,
|
|
num_worker_threads=2,
|
|
worker_name="train",
|
|
init_fun=None,
|
|
external_loggers=None,
|
|
shutdown_fun=None,
|
|
):
|
|
global global_coordinator
|
|
|
|
metrics = Metrics(external_loggers)
|
|
|
|
worker_ids = [
|
|
global_coordinator.get_new_worker_id()
|
|
for i in range(num_worker_threads)
|
|
]
|
|
|
|
# Create coordinator object
|
|
coordinator = WorkerCoordinator(
|
|
worker_name, worker_ids, init_fun, shutdown_fun=shutdown_fun)
|
|
|
|
# Launch fetch worker threads
|
|
workers = [
|
|
threading.Thread(
|
|
target=run_worker,
|
|
name="parallel_workers worker id {}".format(worker_id),
|
|
args=[coordinator,
|
|
Worker(coordinator, worker_id, worker_fun, metrics)],
|
|
) for worker_id in worker_ids
|
|
]
|
|
|
|
coordinator._workers = workers
|
|
global_coordinator.add(coordinator)
|
|
|
|
return global_coordinator
|
|
|
|
|
|
class Metrics(object):
|
|
def __init__(self, external_loggers):
|
|
self._metrics = collections.defaultdict(lambda: 0)
|
|
self._external_loggers = external_loggers
|
|
|
|
def reset_metrics(self):
|
|
self._metrics = collections.defaultdict(lambda: 0)
|
|
|
|
def log_metrics(self):
|
|
if not self._external_loggers:
|
|
return
|
|
for logger in self._external_loggers:
|
|
try:
|
|
logger.log(self._metrics)
|
|
except Exception as e:
|
|
print("Failed to call ExternalLogger: {}".format(e))
|
|
|
|
def put_metric(self, key, value, count=True):
|
|
self._metrics[key] += value
|
|
if count:
|
|
count_key = '{}_count'.format(key)
|
|
self._metrics[count_key] += 1
|
|
|
|
|
|
class State():
|
|
six.add_metaclass(ABCMeta)
|
|
|
|
@abstractmethod
|
|
def start(self):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def stop(self):
|
|
pass
|
|
|
|
@abstractmethod
|
|
def cleanup(self):
|
|
pass
|
|
|
|
|
|
class WorkerCoordinator(object):
|
|
def __init__(
|
|
self, worker_name, worker_ids, init_fun,
|
|
state=None, shutdown_fun=None
|
|
):
|
|
self._active = True
|
|
self._started = False
|
|
self._workers = []
|
|
self._worker_name = worker_name
|
|
self._worker_ids = worker_ids
|
|
self._init_fun = init_fun
|
|
self._state = state
|
|
self._shutdown_fun = shutdown_fun
|
|
|
|
def is_active(self):
|
|
return self._active
|
|
|
|
def init(self, global_coordinator):
|
|
if self._init_fun and not self._started:
|
|
data_coordinator = self
|
|
self._init_fun(data_coordinator, global_coordinator)
|
|
|
|
def _start(self):
|
|
if self._started:
|
|
return
|
|
self._active = True
|
|
self._started = True
|
|
if self._state:
|
|
self._state.start()
|
|
|
|
for w in self._workers:
|
|
w.daemon = True
|
|
w.start()
|
|
|
|
def _stop(self, reason=None):
|
|
self._active = False
|
|
if reason is not None:
|
|
log.error("Data input failed due to an error: {}".format(reason))
|
|
if self._shutdown_fun and self._started:
|
|
self._shutdown_fun()
|
|
if self._state:
|
|
self._state.stop()
|
|
|
|
self._started = False
|
|
|
|
def _wait_finish(self, cleanup=None):
|
|
print("Wait for workers to die: {}".format(self._worker_name))
|
|
for w in self._workers:
|
|
if w != threading.current_thread():
|
|
w.join(5.0) # don't wait forever, thread may be blocked in i/o
|
|
success = True
|
|
for w in self._workers:
|
|
if w.isAlive():
|
|
print("Worker {} failed to close while waiting".format(w))
|
|
success = False
|
|
|
|
# Release memory for the scratch blobs
|
|
if success and self._state:
|
|
self._state.cleanup()
|
|
|
|
print("All workers terminated: {}".format(success))
|
|
return success
|
|
|
|
def get_worker_ids(self):
|
|
return self._worker_ids
|
|
|
|
|
|
class GlobalWorkerCoordinator(object):
|
|
def __init__(self):
|
|
self._coordinators = []
|
|
self._fetcher_id_seq = 0
|
|
self._worker_ids = []
|
|
self.register_shutdown_handler()
|
|
|
|
def add(self, coordinator):
|
|
self._coordinators.append(coordinator)
|
|
|
|
def get_new_worker_id(self):
|
|
worker_id = self._fetcher_id_seq
|
|
self._worker_ids.append(worker_id)
|
|
self._fetcher_id_seq += 1
|
|
return worker_id
|
|
|
|
def get_worker_ids(self):
|
|
return self._worker_ids
|
|
|
|
def start(self):
|
|
# run init and start in separate for loop to
|
|
# ensure init happens serially before threads are spawn.
|
|
for c in self._coordinators:
|
|
c.init(self)
|
|
for c in self._coordinators:
|
|
c._start()
|
|
|
|
def stop(self):
|
|
all_success = True
|
|
for c in self._coordinators:
|
|
c._stop()
|
|
for c in self._coordinators:
|
|
success = c._wait_finish()
|
|
all_success = all_success and success
|
|
self._coordinators = []
|
|
return all_success
|
|
|
|
def stop_coordinator(self, worker_name):
|
|
'''
|
|
Stop a specific coordinator
|
|
'''
|
|
for c in self._coordinators:
|
|
if c._worker_name == worker_name:
|
|
c._stop()
|
|
c._wait_finish()
|
|
self._coordinators = [
|
|
c for c in self._coordinators
|
|
if c._worker_name != worker_name
|
|
]
|
|
|
|
def register_shutdown_handler(self):
|
|
def cleanup():
|
|
self.stop()
|
|
|
|
atexit.register(cleanup)
|
|
|
|
|
|
class Worker(object):
|
|
def __init__(
|
|
self,
|
|
coordinator,
|
|
worker_id,
|
|
worker_fun=None,
|
|
metrics=None
|
|
):
|
|
self._coordinator = coordinator
|
|
self._worker_id = worker_id
|
|
self._worker_fun = worker_fun
|
|
self._metrics = metrics
|
|
|
|
def start(self):
|
|
self._start_time = time.time()
|
|
|
|
def run(self):
|
|
self._worker_fun(self._worker_id)
|
|
|
|
def handle_exception(self, e):
|
|
traceback.print_exc()
|
|
logging.exception("Exception in worker", e)
|
|
self._coordinator._stop("Exception in worker {}: {}".format(
|
|
self._worker_id, e
|
|
))
|
|
|
|
def finish(self):
|
|
self._metrics.put_metric(
|
|
'worker_time', time.time() - self._start_time)
|
|
self._metrics.log_metrics()
|
|
|
|
|
|
global_coordinator = GlobalWorkerCoordinator()
|
|
|
|
|
|
def run_worker(coordinator, worker):
|
|
while coordinator.is_active():
|
|
worker.start()
|
|
try:
|
|
worker.run()
|
|
except Exception as e:
|
|
worker.handle_exception(e)
|
|
finally:
|
|
worker.finish()
|