2017-03-29 06:44:02 -07:00
|
|
|
## @package data_parallel_model
|
|
|
|
|
# Module caffe2.python.data_parallel_model
|
2016-10-07 13:08:53 -07:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
from __future__ import division
|
|
|
|
|
from __future__ import print_function
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
from collections import OrderedDict
|
2017-06-29 16:52:01 -07:00
|
|
|
from future.utils import viewitems, viewkeys, viewvalues
|
2016-11-14 14:58:04 -08:00
|
|
|
import logging
|
2017-03-09 13:41:36 -08:00
|
|
|
import copy
|
2016-10-07 13:08:53 -07:00
|
|
|
|
2018-09-04 13:09:02 -07:00
|
|
|
from multiprocessing import cpu_count
|
|
|
|
|
|
2018-01-24 13:10:56 -08:00
|
|
|
from caffe2.python import \
|
|
|
|
|
model_helper, dyndep, scope, workspace, core, memonger, utils
|
2016-10-07 13:08:53 -07:00
|
|
|
from caffe2.proto import caffe2_pb2
|
|
|
|
|
|
2017-07-13 13:00:51 -07:00
|
|
|
import numpy as np
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
import warnings
|
2017-07-13 13:00:51 -07:00
|
|
|
|
2017-03-14 22:32:07 -07:00
|
|
|
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops")
|
2019-07-10 11:40:22 -07:00
|
|
|
|
|
|
|
|
# We only import nccl operators when the machine has GPUs
|
|
|
|
|
# Otherwise the binary can be compiled with CPU-only mode, and
|
|
|
|
|
# will not be able to find those modules
|
|
|
|
|
if workspace.NumGpuDevices() > 0:
|
|
|
|
|
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/nccl:nccl_ops")
|
|
|
|
|
dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/gloo:gloo_ops_gpu")
|
2016-10-07 13:08:53 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
log = logging.getLogger("data_parallel_model")
|
|
|
|
|
log.setLevel(logging.INFO)
|
|
|
|
|
|
2017-09-06 13:18:06 -07:00
|
|
|
_DEFAULT_TIMEOUT_SEC = 30
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
_DEFAULT_BARRIER_NET_TIMEOUT_SEC = 300
|
2017-09-06 13:18:06 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
def Parallelize_GPU(*args, **kwargs):
|
|
|
|
|
kwargs['cpu_device'] = False
|
|
|
|
|
Parallelize(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def Parallelize_CPU(*args, **kwargs):
|
|
|
|
|
kwargs['cpu_device'] = True
|
|
|
|
|
Parallelize(*args, **kwargs)
|
|
|
|
|
|
2019-01-15 11:07:55 -08:00
|
|
|
def Parallelize_iDeep(*args, **kwargs):
|
|
|
|
|
kwargs['ideep'] = True
|
|
|
|
|
Parallelize(*args, **kwargs)
|
2017-07-27 13:08:37 -07:00
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
def Parallelize(
|
2016-11-14 14:58:04 -08:00
|
|
|
model_helper_obj,
|
|
|
|
|
input_builder_fun,
|
|
|
|
|
forward_pass_builder_fun,
|
2017-05-30 12:44:50 -07:00
|
|
|
param_update_builder_fun=None,
|
|
|
|
|
optimizer_builder_fun=None,
|
2017-06-01 08:31:33 -07:00
|
|
|
post_sync_builder_fun=None,
|
2018-08-29 12:40:04 -07:00
|
|
|
pre_grad_net_transformer_fun=None,
|
[Caffe2] Changes done inside Facebook (#6378)
* fix unit test for sqrt op
From the error logging:
[idx, grad, grad_estimate] are:
[[ 146. 0.5 0.45776367]
[ 147. 0.5 0.45776367]
The gradient == 0.5 is correct, which means the SqrtOp and its gradient is doing right job. (Because y = sqrt(x), loss = y^2/2 = x/2, and then d(loss)/dx = 1/2 = 0.5; )
The test failed because of numerical problem of grad_estimate (in unit test). It can be because the step_size is small, and float precision is not high (when there are multiple elements in the tensor, we do sum(y^2) to compute loss)
This diff
- increase the step size, and also move the test cases to be further away from 0 (where sqrt(x) is not well defined) to be safe :)
- also clean up, and merge the test case for inplace Vs. non-inplace
Tested with:
`CAFFE2_HYPOTHESIS_PROFILE=debug ai_bt caffe2/caffe2/python/operator_test:elementwise_ops_test -- "test_sqrt"`
* CompositeReader & CompositeReaderBuilder
A new type of reader gluing multiple readers together.
* Back out "Revert D7394363: [GanH]: Log D Trick for Cross Entropy with Sigmoid"
Original commit changeset: 9325a4356dbe
* [dai][WIP] convert params to int8 on ps before sending to trainer
Add float->uint8 conversion in addition to float->fp16 conversion in model_saver.
* [easy] improve unit test for sparse length sum ops
as desc.
#accept2ship
* Update GitHub upstream to 771fcb3455cbfe69c2abcc4cb3bd7ef92d59af24
* move sparse hash unique ops to OOS and add unit tests
- move the SparseHash version to OOS, since 'sparsehash' is already deps of caffe2 OOS: https://fburl.com/arssw4n1
- The 'SparseHash' engine is also being used in OOS, so the SparseHash version shall be in OOS to reduce confusion: https://fburl.com/o5ea7ah2
- fix the CUDA UniqueOp for the case when batch is empty.
- add unit test
* group_norm_op for caffe2
This is the cuda op for Group Normalization (GN): https://arxiv.org/abs/1803.08494
This code implements GN in one op that computes Y=gamma * (X-mu) / sigma + beta and also its gradients. It is expected to have minimal memory consumption (similar to the BN op), without creating new blobs if GN were implemented as several ops (e.g., reshape, norm_mean/std, affine_channel).
* Resubmit D7405233: disappeared in D7464958
OOS publish causes the op missing -- however, test was still there
* [c2] add sparse hash engine for cuda unique op
The SparseHash version of UniqueOp copy input tensor to CPU, and make use of sparse hash map to get unique output, and then copy back to GPU.
* [dper][gpu] enable unit testing gpu trainer for sparse nn
to debug the GPU trainer using mock data in unit test.
make it easier to develop GPU trainer for new models.
* Reuse Gloo context for Synchronize() calls
Previously we were creating (and leaking) the Gloo context on each call to Synchronize(). Now only run the common world op and create the barrier net once, then run the barrier net on each Synchronize() call. Since timeout is associated with the Gloo context, assert that the timeout is fixed instead of trying to handle the complexity of multiple timeouts (and associated contexts).
* [GanH/WGAN][1/n]: add FC param clipping
as titled
* [mobile] minimizing changes between caffe2_benchmark and speed_benchmark
* [GanH]: enable diagnose within model
avoid finding blob names but to directly enable inside the model
* Add `net_transformer_fun` option to DPM
This callback allows for various transformations to be made to the
model after gradient operators have been added. The immediate motivation for
this is to allow transformations such has "checkpoint-and-recompute" which
allow trading off memory for additional compute.
Adding several callbacks like this has made DPM's API less than ideal at this
stage. However, I could not find any reasonable alternative.
* [DT] [33/n] Compile flow task groups
task groups need to compiled in order to pickle the object in fblearner. However I also changed the Job's compile function as creating new object is not necessary.
* Initial commit for sparse_normalize vectorization and benchmark
* [GanH]: LB Calibration for JSD
as titled
* Tracing event in async executor
Adding event tracing through TRACE_EVENT macro in async executor
* [Resubmit] D7409751 Reseting book-keeping blobs when the reservoir is reset
D7409751 got lost in D7464958
* Visualizing realtime weights values
we want to visualize the weights values as optimizer is iterating. This diff supports to visual the weights at an assigned index.
Currently, we assume the blob to be 2 dimensional.
* [GanH][Easy]: Fix Homotopy Weighting
apparantely, there was a bug in homotopy weight (alpha, beta) update
* [c2] move sparse hash unique op out of oss
so that oss do not need to depend on google hash map.
* Get rid of std::round as it's not supported on Android
* Revert changes on setup.py
* Skip shaky test on Dataio
* fix
2018-04-10 21:11:43 -07:00
|
|
|
net_transformer_fun=None,
|
2017-06-06 23:59:46 -07:00
|
|
|
devices=None,
|
2016-11-22 12:40:12 -08:00
|
|
|
rendezvous=None,
|
2016-12-02 10:58:39 -08:00
|
|
|
net_type='dag',
|
2016-12-16 07:51:04 -08:00
|
|
|
broadcast_computed_params=True,
|
2017-01-09 19:39:09 -08:00
|
|
|
optimize_gradient_memory=False,
|
2017-09-20 12:34:25 -07:00
|
|
|
dynamic_memory_management=False,
|
|
|
|
|
blobs_to_keep=None,
|
2017-05-02 16:01:00 -07:00
|
|
|
use_nccl=False,
|
2017-07-05 21:38:39 -07:00
|
|
|
max_concurrent_distributed_ops=16,
|
2017-06-20 23:10:51 -07:00
|
|
|
cpu_device=False,
|
2019-01-15 11:07:55 -08:00
|
|
|
ideep=False,
|
2017-08-08 19:37:51 -07:00
|
|
|
num_threads_per_device=4,
|
2017-09-15 16:05:58 -07:00
|
|
|
shared_model=False,
|
2018-01-24 13:10:56 -08:00
|
|
|
combine_spatial_bn=False,
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
|
2016-11-14 14:58:04 -08:00
|
|
|
):
|
|
|
|
|
'''
|
2017-06-20 23:10:51 -07:00
|
|
|
Function to create a model that can run on many GPUs or CPUs.
|
|
|
|
|
model_helper_obj: an object of ModelHelper
|
2016-11-14 14:58:04 -08:00
|
|
|
input_builder_fun:
|
|
|
|
|
Function that adds the input operators
|
|
|
|
|
Note: Remember to instantiate reader outside of this
|
2017-06-20 23:10:51 -07:00
|
|
|
function so all devices share same reader object.
|
2016-11-14 14:58:04 -08:00
|
|
|
Signature: input_builder_fun(model)
|
|
|
|
|
forward_pass_builder_fun:
|
|
|
|
|
Function to add the operators to the model.
|
|
|
|
|
Must return list of loss-blob references that
|
2017-02-06 12:30:27 -08:00
|
|
|
are used to build the gradient. Loss scale parameter
|
|
|
|
|
is passed, as you should scale the loss of your model
|
2017-06-20 23:10:51 -07:00
|
|
|
by 1.0 / the total number of devices.
|
2017-02-06 12:30:27 -08:00
|
|
|
Signature: forward_pass_builder_fun(model, loss_scale)
|
2016-11-14 14:58:04 -08:00
|
|
|
param_update_builder_fun:
|
|
|
|
|
Function that adds operators that are run after
|
|
|
|
|
gradient update, such as updating the weights and
|
2017-05-30 12:44:50 -07:00
|
|
|
weight decaying. This is called for each GPU separately.
|
2017-02-06 12:30:27 -08:00
|
|
|
Signature: param_update_builder_fun(model)
|
2017-05-30 12:44:50 -07:00
|
|
|
optimizer_builder_fun:
|
|
|
|
|
Alternative to param_update_builder_fun, allows one
|
|
|
|
|
to add an optimizer for the whole model. Called only
|
|
|
|
|
once, without name or devicescope.
|
[Caffe2] Changes done inside Facebook (#6378)
* fix unit test for sqrt op
From the error logging:
[idx, grad, grad_estimate] are:
[[ 146. 0.5 0.45776367]
[ 147. 0.5 0.45776367]
The gradient == 0.5 is correct, which means the SqrtOp and its gradient is doing right job. (Because y = sqrt(x), loss = y^2/2 = x/2, and then d(loss)/dx = 1/2 = 0.5; )
The test failed because of numerical problem of grad_estimate (in unit test). It can be because the step_size is small, and float precision is not high (when there are multiple elements in the tensor, we do sum(y^2) to compute loss)
This diff
- increase the step size, and also move the test cases to be further away from 0 (where sqrt(x) is not well defined) to be safe :)
- also clean up, and merge the test case for inplace Vs. non-inplace
Tested with:
`CAFFE2_HYPOTHESIS_PROFILE=debug ai_bt caffe2/caffe2/python/operator_test:elementwise_ops_test -- "test_sqrt"`
* CompositeReader & CompositeReaderBuilder
A new type of reader gluing multiple readers together.
* Back out "Revert D7394363: [GanH]: Log D Trick for Cross Entropy with Sigmoid"
Original commit changeset: 9325a4356dbe
* [dai][WIP] convert params to int8 on ps before sending to trainer
Add float->uint8 conversion in addition to float->fp16 conversion in model_saver.
* [easy] improve unit test for sparse length sum ops
as desc.
#accept2ship
* Update GitHub upstream to 771fcb3455cbfe69c2abcc4cb3bd7ef92d59af24
* move sparse hash unique ops to OOS and add unit tests
- move the SparseHash version to OOS, since 'sparsehash' is already deps of caffe2 OOS: https://fburl.com/arssw4n1
- The 'SparseHash' engine is also being used in OOS, so the SparseHash version shall be in OOS to reduce confusion: https://fburl.com/o5ea7ah2
- fix the CUDA UniqueOp for the case when batch is empty.
- add unit test
* group_norm_op for caffe2
This is the cuda op for Group Normalization (GN): https://arxiv.org/abs/1803.08494
This code implements GN in one op that computes Y=gamma * (X-mu) / sigma + beta and also its gradients. It is expected to have minimal memory consumption (similar to the BN op), without creating new blobs if GN were implemented as several ops (e.g., reshape, norm_mean/std, affine_channel).
* Resubmit D7405233: disappeared in D7464958
OOS publish causes the op missing -- however, test was still there
* [c2] add sparse hash engine for cuda unique op
The SparseHash version of UniqueOp copy input tensor to CPU, and make use of sparse hash map to get unique output, and then copy back to GPU.
* [dper][gpu] enable unit testing gpu trainer for sparse nn
to debug the GPU trainer using mock data in unit test.
make it easier to develop GPU trainer for new models.
* Reuse Gloo context for Synchronize() calls
Previously we were creating (and leaking) the Gloo context on each call to Synchronize(). Now only run the common world op and create the barrier net once, then run the barrier net on each Synchronize() call. Since timeout is associated with the Gloo context, assert that the timeout is fixed instead of trying to handle the complexity of multiple timeouts (and associated contexts).
* [GanH/WGAN][1/n]: add FC param clipping
as titled
* [mobile] minimizing changes between caffe2_benchmark and speed_benchmark
* [GanH]: enable diagnose within model
avoid finding blob names but to directly enable inside the model
* Add `net_transformer_fun` option to DPM
This callback allows for various transformations to be made to the
model after gradient operators have been added. The immediate motivation for
this is to allow transformations such has "checkpoint-and-recompute" which
allow trading off memory for additional compute.
Adding several callbacks like this has made DPM's API less than ideal at this
stage. However, I could not find any reasonable alternative.
* [DT] [33/n] Compile flow task groups
task groups need to compiled in order to pickle the object in fblearner. However I also changed the Job's compile function as creating new object is not necessary.
* Initial commit for sparse_normalize vectorization and benchmark
* [GanH]: LB Calibration for JSD
as titled
* Tracing event in async executor
Adding event tracing through TRACE_EVENT macro in async executor
* [Resubmit] D7409751 Reseting book-keeping blobs when the reservoir is reset
D7409751 got lost in D7464958
* Visualizing realtime weights values
we want to visualize the weights values as optimizer is iterating. This diff supports to visual the weights at an assigned index.
Currently, we assume the blob to be 2 dimensional.
* [GanH][Easy]: Fix Homotopy Weighting
apparantely, there was a bug in homotopy weight (alpha, beta) update
* [c2] move sparse hash unique op out of oss
so that oss do not need to depend on google hash map.
* Get rid of std::round as it's not supported on Android
* Revert changes on setup.py
* Skip shaky test on Dataio
* fix
2018-04-10 21:11:43 -07:00
|
|
|
net_transformer_fun:
|
|
|
|
|
Optional function to transform the network after the
|
|
|
|
|
network is built. It will be called once (NOT once per
|
|
|
|
|
GPU.)
|
|
|
|
|
Signature:
|
|
|
|
|
net_transformer_fun(
|
|
|
|
|
model, num_devices, device_prefix, device_type)
|
2018-08-29 12:40:04 -07:00
|
|
|
pre_grad_net_transformer_fun:
|
|
|
|
|
Optional function to transform the network similar to
|
|
|
|
|
net_transformer_fun, but happens before gradient ops
|
|
|
|
|
been add.
|
|
|
|
|
Signature: pre_grad_net_transformer_fun(model)
|
2017-06-01 08:31:33 -07:00
|
|
|
post_sync_builder_fun:
|
|
|
|
|
Function applied after initial parameter sync has been
|
|
|
|
|
completed, such as keeping multi-precision parameters
|
|
|
|
|
in sync.
|
|
|
|
|
Signature: post_sync_builder_fun(model)
|
2016-11-22 12:40:12 -08:00
|
|
|
devices: List of GPU ids, such as [0, 1, 2, 3],
|
|
|
|
|
rendezvous: used for rendezvous in distributed computation, if None
|
|
|
|
|
then only one node is used. To create rendezvous,
|
|
|
|
|
use <TBD>.
|
2016-12-02 10:58:39 -08:00
|
|
|
net_type: Network type
|
2017-04-25 14:03:33 -07:00
|
|
|
optimize_gradient_memory: whether to apply 'memonger' to share blobs
|
2017-09-15 16:05:58 -07:00
|
|
|
shared_model (only for CPU) use same parameters on each device
|
2017-09-20 12:34:25 -07:00
|
|
|
in gradient computation to reduce memory footprint.
|
|
|
|
|
dynamic_memory_management: Whether to apply dynamic memory optimization
|
|
|
|
|
by freeing unused blobs. The underlying (de)allocation
|
|
|
|
|
uses cached allocator. For GPU training PLEASE MAKE SURE
|
|
|
|
|
caffe2_cuda_memory_pool is set.
|
|
|
|
|
blobs_to_keep : A list of blob names to keep and don't free during
|
|
|
|
|
dynamic memory optimization (for example loss blob).
|
|
|
|
|
cpu_device Use CPU instead of GPU.
|
2019-01-15 11:07:55 -08:00
|
|
|
ideep Use ideep.
|
2018-01-24 13:10:56 -08:00
|
|
|
combine_spatial_bn:
|
|
|
|
|
When set to True, applies batch normalization across
|
|
|
|
|
all devices within the node. If False, batch
|
|
|
|
|
normalization will be done separately for each device.
|
|
|
|
|
This option is currently only supported on the CPU.
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
barrier_net_timeout_sec:
|
|
|
|
|
The timeout in seconds of the barrier net, which is run
|
|
|
|
|
to synchronize shards before a training epoch starts.
|
|
|
|
|
Defaults to 300 seconds.
|
2016-11-14 14:58:04 -08:00
|
|
|
'''
|
2017-07-18 15:32:36 -07:00
|
|
|
assert scope.CurrentDeviceScope() is None \
|
|
|
|
|
or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
|
2017-07-12 10:38:51 -07:00
|
|
|
"Parallelize must be called without device-scope, \
|
|
|
|
|
device scope was: {}".format(scope.CurrentDeviceScope())
|
|
|
|
|
|
2017-06-06 23:59:46 -07:00
|
|
|
if devices is None:
|
2019-01-15 11:07:55 -08:00
|
|
|
if not (cpu_device or ideep):
|
|
|
|
|
devices = list(range(0, workspace.NumCudaDevices()))
|
2018-09-04 13:09:02 -07:00
|
|
|
else:
|
|
|
|
|
devices = list(range(0, cpu_count()))
|
2017-06-16 06:58:20 -07:00
|
|
|
|
2019-01-15 11:07:55 -08:00
|
|
|
if not (cpu_device or ideep):
|
2017-06-20 23:10:51 -07:00
|
|
|
for gpu in devices:
|
2018-11-29 13:58:11 -08:00
|
|
|
if gpu >= workspace.NumGpuDevices():
|
2017-06-20 23:10:51 -07:00
|
|
|
log.warning("** Only {} GPUs available, GPUs {} requested".format(
|
2018-11-29 13:58:11 -08:00
|
|
|
workspace.NumGpuDevices(), devices))
|
2017-06-20 23:10:51 -07:00
|
|
|
break
|
2018-11-29 13:58:11 -08:00
|
|
|
model_helper_obj._device_type = workspace.GpuDeviceType
|
2017-06-20 23:10:51 -07:00
|
|
|
model_helper_obj._device_prefix = "gpu"
|
2017-09-15 16:05:58 -07:00
|
|
|
model_helper_obj._shared_model = False
|
2017-06-20 23:10:51 -07:00
|
|
|
device_name = "GPU"
|
2017-09-15 16:05:58 -07:00
|
|
|
assert shared_model is False, "Shared model only supported on CPU"
|
2019-01-15 11:07:55 -08:00
|
|
|
elif ideep:
|
|
|
|
|
model_helper_obj._device_type = caffe2_pb2.IDEEP
|
|
|
|
|
model_helper_obj._device_prefix = "ideep"
|
|
|
|
|
device_name = "IDEEP"
|
|
|
|
|
model_helper_obj._shared_model = shared_model
|
|
|
|
|
if shared_model and rendezvous is not None:
|
|
|
|
|
assert "Shared model only supported on single-node currently"
|
2017-06-20 23:10:51 -07:00
|
|
|
else:
|
|
|
|
|
model_helper_obj._device_type = caffe2_pb2.CPU
|
|
|
|
|
model_helper_obj._device_prefix = "cpu"
|
|
|
|
|
device_name = "CPU"
|
2017-09-15 16:05:58 -07:00
|
|
|
model_helper_obj._shared_model = shared_model
|
|
|
|
|
if shared_model and rendezvous is not None:
|
|
|
|
|
assert "Shared model only supported on single-node currently"
|
2017-06-16 06:58:20 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
log.info("Parallelizing model for devices: {}".format(devices))
|
2016-11-22 12:40:12 -08:00
|
|
|
extra_workers = 8 if rendezvous is not None else 0 # best-guess
|
2017-08-08 19:37:51 -07:00
|
|
|
num_workers = len(devices) * num_threads_per_device + extra_workers
|
2017-05-25 13:22:51 -07:00
|
|
|
max_concurrent_distributed_ops =\
|
|
|
|
|
min(max_concurrent_distributed_ops, num_workers - 1)
|
|
|
|
|
model_helper_obj.net.Proto().num_workers = num_workers
|
2016-12-02 10:58:39 -08:00
|
|
|
model_helper_obj.net.Proto().type = net_type
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Store some information in the model -- a bit ugly
|
|
|
|
|
model_helper_obj._devices = devices
|
2016-11-22 12:40:12 -08:00
|
|
|
model_helper_obj._rendezvous = rendezvous
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
model_helper_obj._sync_barrier_net = None
|
|
|
|
|
|
2017-09-12 10:20:22 -07:00
|
|
|
model_helper_obj._broadcast_context = None
|
2016-11-14 14:58:04 -08:00
|
|
|
model_helper_obj._grad_names = []
|
|
|
|
|
|
2017-04-23 03:23:37 -07:00
|
|
|
assert isinstance(model_helper_obj, model_helper.ModelHelper)
|
2017-03-09 13:41:36 -08:00
|
|
|
|
|
|
|
|
# Keep track of params that were in the model before: they are not
|
|
|
|
|
# data parallel, so we need to handle them separately
|
|
|
|
|
non_datapar_params = copy.copy(model_helper_obj.params)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Add input and model
|
|
|
|
|
log.info("Create input and model training operators")
|
|
|
|
|
|
|
|
|
|
losses_by_gpu = {}
|
2017-02-03 07:37:59 -08:00
|
|
|
num_shards = 1 if rendezvous is None else rendezvous['num_shards']
|
|
|
|
|
loss_scale = 1.0 / (len(devices) * num_shards)
|
|
|
|
|
|
2017-05-30 12:44:50 -07:00
|
|
|
has_parameter_updates = param_update_builder_fun is not None or \
|
|
|
|
|
optimizer_builder_fun is not None
|
|
|
|
|
assert not (
|
|
|
|
|
param_update_builder_fun is not None and
|
|
|
|
|
optimizer_builder_fun is not None
|
|
|
|
|
), 'Can only specify one of param_update_builder_fun, optimizer_builder_fun'
|
|
|
|
|
|
2017-07-27 13:08:37 -07:00
|
|
|
# Check that a model that is used for validation/testing has
|
|
|
|
|
# init_params False, otherwise running the param init net will overwrite
|
|
|
|
|
# synchronized values by the training net
|
|
|
|
|
if not has_parameter_updates and model_helper_obj.init_params:
|
|
|
|
|
log.warning('')
|
|
|
|
|
log.warning("############# WARNING #############")
|
|
|
|
|
log.warning("Model {}/{} is used for testing/validation but".format(
|
|
|
|
|
model_helper_obj.name, model_helper_obj))
|
|
|
|
|
log.warning("has init_params=True!")
|
|
|
|
|
log.warning("This can conflict with model training.")
|
|
|
|
|
log.warning("Please ensure model = ModelHelper(init_params=False)")
|
|
|
|
|
log.warning('####################################')
|
|
|
|
|
log.warning('')
|
|
|
|
|
# TODO: make into assert
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
for device in devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
|
2016-11-14 14:58:04 -08:00
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-20 23:10:51 -07:00
|
|
|
with core.NameScope("{}_{}".format(model_helper_obj._device_prefix,
|
|
|
|
|
device)):
|
|
|
|
|
log.info("Model for {} : {}".format(device_name, device))
|
2016-11-14 14:58:04 -08:00
|
|
|
input_builder_fun(model_helper_obj)
|
2017-02-03 07:37:59 -08:00
|
|
|
losses = forward_pass_builder_fun(model_helper_obj, loss_scale)
|
2016-12-14 19:50:59 -08:00
|
|
|
# Losses are not needed for test net
|
2017-05-30 12:44:50 -07:00
|
|
|
if has_parameter_updates:
|
2016-12-14 19:50:59 -08:00
|
|
|
assert isinstance(losses, list), \
|
|
|
|
|
'Model builder function must return list of loss blobs'
|
|
|
|
|
for loss in losses:
|
|
|
|
|
assert isinstance(loss, core.BlobReference), \
|
|
|
|
|
'Model builder func must return list of loss blobs'
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
losses_by_gpu[device] = losses
|
2017-04-12 09:22:23 -07:00
|
|
|
_ValidateParams(model_helper_obj.params)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Create parameter map
|
|
|
|
|
model_helper_obj._device_grouped_blobs =\
|
2017-06-20 23:10:51 -07:00
|
|
|
_GroupByDevice(model_helper_obj, devices,
|
|
|
|
|
model_helper_obj.params, non_datapar_params)
|
2016-12-06 10:08:21 -08:00
|
|
|
|
|
|
|
|
# computed params
|
|
|
|
|
computed_params_grouped =\
|
2017-06-20 23:10:51 -07:00
|
|
|
_GroupByDevice(model_helper_obj, devices,
|
|
|
|
|
model_helper_obj.GetComputedParams(''), [])
|
2016-12-06 10:08:21 -08:00
|
|
|
model_helper_obj._device_grouped_blobs.update(computed_params_grouped)
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
model_helper_obj._param_names =\
|
2017-06-29 16:52:01 -07:00
|
|
|
list(viewkeys(model_helper_obj._device_grouped_blobs))
|
|
|
|
|
model_helper_obj._computed_param_names =\
|
|
|
|
|
list(viewkeys(computed_params_grouped))
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2018-08-29 12:40:04 -07:00
|
|
|
if pre_grad_net_transformer_fun:
|
|
|
|
|
pre_grad_net_transformer_fun(model_helper_obj)
|
|
|
|
|
|
[Caffe2] Changes done inside Facebook (#6378)
* fix unit test for sqrt op
From the error logging:
[idx, grad, grad_estimate] are:
[[ 146. 0.5 0.45776367]
[ 147. 0.5 0.45776367]
The gradient == 0.5 is correct, which means the SqrtOp and its gradient is doing right job. (Because y = sqrt(x), loss = y^2/2 = x/2, and then d(loss)/dx = 1/2 = 0.5; )
The test failed because of numerical problem of grad_estimate (in unit test). It can be because the step_size is small, and float precision is not high (when there are multiple elements in the tensor, we do sum(y^2) to compute loss)
This diff
- increase the step size, and also move the test cases to be further away from 0 (where sqrt(x) is not well defined) to be safe :)
- also clean up, and merge the test case for inplace Vs. non-inplace
Tested with:
`CAFFE2_HYPOTHESIS_PROFILE=debug ai_bt caffe2/caffe2/python/operator_test:elementwise_ops_test -- "test_sqrt"`
* CompositeReader & CompositeReaderBuilder
A new type of reader gluing multiple readers together.
* Back out "Revert D7394363: [GanH]: Log D Trick for Cross Entropy with Sigmoid"
Original commit changeset: 9325a4356dbe
* [dai][WIP] convert params to int8 on ps before sending to trainer
Add float->uint8 conversion in addition to float->fp16 conversion in model_saver.
* [easy] improve unit test for sparse length sum ops
as desc.
#accept2ship
* Update GitHub upstream to 771fcb3455cbfe69c2abcc4cb3bd7ef92d59af24
* move sparse hash unique ops to OOS and add unit tests
- move the SparseHash version to OOS, since 'sparsehash' is already deps of caffe2 OOS: https://fburl.com/arssw4n1
- The 'SparseHash' engine is also being used in OOS, so the SparseHash version shall be in OOS to reduce confusion: https://fburl.com/o5ea7ah2
- fix the CUDA UniqueOp for the case when batch is empty.
- add unit test
* group_norm_op for caffe2
This is the cuda op for Group Normalization (GN): https://arxiv.org/abs/1803.08494
This code implements GN in one op that computes Y=gamma * (X-mu) / sigma + beta and also its gradients. It is expected to have minimal memory consumption (similar to the BN op), without creating new blobs if GN were implemented as several ops (e.g., reshape, norm_mean/std, affine_channel).
* Resubmit D7405233: disappeared in D7464958
OOS publish causes the op missing -- however, test was still there
* [c2] add sparse hash engine for cuda unique op
The SparseHash version of UniqueOp copy input tensor to CPU, and make use of sparse hash map to get unique output, and then copy back to GPU.
* [dper][gpu] enable unit testing gpu trainer for sparse nn
to debug the GPU trainer using mock data in unit test.
make it easier to develop GPU trainer for new models.
* Reuse Gloo context for Synchronize() calls
Previously we were creating (and leaking) the Gloo context on each call to Synchronize(). Now only run the common world op and create the barrier net once, then run the barrier net on each Synchronize() call. Since timeout is associated with the Gloo context, assert that the timeout is fixed instead of trying to handle the complexity of multiple timeouts (and associated contexts).
* [GanH/WGAN][1/n]: add FC param clipping
as titled
* [mobile] minimizing changes between caffe2_benchmark and speed_benchmark
* [GanH]: enable diagnose within model
avoid finding blob names but to directly enable inside the model
* Add `net_transformer_fun` option to DPM
This callback allows for various transformations to be made to the
model after gradient operators have been added. The immediate motivation for
this is to allow transformations such has "checkpoint-and-recompute" which
allow trading off memory for additional compute.
Adding several callbacks like this has made DPM's API less than ideal at this
stage. However, I could not find any reasonable alternative.
* [DT] [33/n] Compile flow task groups
task groups need to compiled in order to pickle the object in fblearner. However I also changed the Job's compile function as creating new object is not necessary.
* Initial commit for sparse_normalize vectorization and benchmark
* [GanH]: LB Calibration for JSD
as titled
* Tracing event in async executor
Adding event tracing through TRACE_EVENT macro in async executor
* [Resubmit] D7409751 Reseting book-keeping blobs when the reservoir is reset
D7409751 got lost in D7464958
* Visualizing realtime weights values
we want to visualize the weights values as optimizer is iterating. This diff supports to visual the weights at an assigned index.
Currently, we assume the blob to be 2 dimensional.
* [GanH][Easy]: Fix Homotopy Weighting
apparantely, there was a bug in homotopy weight (alpha, beta) update
* [c2] move sparse hash unique op out of oss
so that oss do not need to depend on google hash map.
* Get rid of std::round as it's not supported on Android
* Revert changes on setup.py
* Skip shaky test on Dataio
* fix
2018-04-10 21:11:43 -07:00
|
|
|
if has_parameter_updates:
|
|
|
|
|
log.info("Adding gradient operators")
|
|
|
|
|
_AddGradientOperators(devices, model_helper_obj, losses_by_gpu)
|
|
|
|
|
|
|
|
|
|
if net_transformer_fun:
|
|
|
|
|
net_transformer_fun(
|
|
|
|
|
model_helper_obj,
|
|
|
|
|
len(devices),
|
|
|
|
|
model_helper_obj._device_prefix,
|
|
|
|
|
model_helper_obj._device_type)
|
|
|
|
|
|
2017-05-30 12:44:50 -07:00
|
|
|
if not has_parameter_updates:
|
2016-11-14 14:58:04 -08:00
|
|
|
log.info("Parameter update function not defined --> only forward")
|
2017-03-10 17:50:12 -08:00
|
|
|
_InferBlobDevice(model_helper_obj)
|
2016-11-14 14:58:04 -08:00
|
|
|
return
|
|
|
|
|
|
2018-01-24 13:10:56 -08:00
|
|
|
if combine_spatial_bn:
|
|
|
|
|
assert(has_parameter_updates), \
|
|
|
|
|
'combine_spatial_bn should only be used for train model'
|
|
|
|
|
_InterleaveOps(model_helper_obj)
|
2018-10-18 11:19:28 -07:00
|
|
|
if cpu_device:
|
|
|
|
|
_CPUInterDeviceBatchNormalization(model_helper_obj)
|
|
|
|
|
else:
|
|
|
|
|
_GPUInterDeviceBatchNormalization(model_helper_obj)
|
2018-01-24 13:10:56 -08:00
|
|
|
|
2017-04-12 09:22:23 -07:00
|
|
|
_ValidateParams(model_helper_obj.params)
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
# Group gradients by device and register to blob lookup
|
|
|
|
|
param_to_grad = model_helper_obj.param_to_grad
|
|
|
|
|
grads_ordered = [param_to_grad[p] for p in
|
|
|
|
|
model_helper_obj.params if p in param_to_grad]
|
2017-03-09 13:41:36 -08:00
|
|
|
non_datapar_grads = [param_to_grad[p] for p in non_datapar_params]
|
2017-03-17 05:15:38 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
gradients_grouped = _GroupByDevice(
|
2017-06-20 23:10:51 -07:00
|
|
|
model_helper_obj,
|
2016-11-14 14:58:04 -08:00
|
|
|
devices,
|
|
|
|
|
grads_ordered,
|
2017-03-09 13:41:36 -08:00
|
|
|
non_datapar_grads
|
2016-11-14 14:58:04 -08:00
|
|
|
)
|
|
|
|
|
model_helper_obj._device_grouped_blobs.update(gradients_grouped)
|
2017-06-29 16:52:01 -07:00
|
|
|
model_helper_obj._grad_names = list(viewkeys(gradients_grouped))
|
2017-04-25 14:03:33 -07:00
|
|
|
model_helper_obj._losses_by_gpu = losses_by_gpu
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-03-09 13:41:36 -08:00
|
|
|
_InferBlobDevice(model_helper_obj)
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
log.info("Add gradient all-reduces for SyncSGD")
|
2016-12-16 07:51:04 -08:00
|
|
|
if broadcast_computed_params:
|
2017-05-30 16:43:02 -07:00
|
|
|
_BroadcastComputedParams(devices, model_helper_obj, rendezvous, use_nccl)
|
2017-03-09 13:41:36 -08:00
|
|
|
|
2017-04-24 18:33:05 -07:00
|
|
|
if len(model_helper_obj._grad_names) > 0:
|
2017-06-21 16:14:39 -07:00
|
|
|
# Gradients in reverse order
|
|
|
|
|
reverse_ordered_grads = _GetReverseOrderedGrads(model_helper_obj)
|
|
|
|
|
assert(len(reverse_ordered_grads) > 0)
|
|
|
|
|
_AllReduceBlobs(
|
|
|
|
|
reverse_ordered_grads,
|
2017-05-25 13:22:51 -07:00
|
|
|
devices,
|
|
|
|
|
model_helper_obj,
|
2017-06-21 16:14:39 -07:00
|
|
|
model_helper_obj.net,
|
2017-05-25 13:22:51 -07:00
|
|
|
rendezvous,
|
|
|
|
|
use_nccl,
|
|
|
|
|
max_concurrent_distributed_ops,
|
|
|
|
|
)
|
2017-04-24 18:33:05 -07:00
|
|
|
else:
|
|
|
|
|
log.info("NOTE: Param builder function did not create any parameters.")
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
log.info("Post-iteration operators for updating params")
|
2017-02-06 20:11:27 -08:00
|
|
|
num_shards = 1 if rendezvous is None else rendezvous['num_shards']
|
2017-05-30 12:44:50 -07:00
|
|
|
|
2017-09-15 16:05:58 -07:00
|
|
|
all_params = set(model_helper_obj.GetParams(''))
|
|
|
|
|
if shared_model:
|
|
|
|
|
_PruneParametersForSharing(model_helper_obj)
|
|
|
|
|
|
2017-05-30 12:44:50 -07:00
|
|
|
if param_update_builder_fun is not None:
|
|
|
|
|
for device in devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
|
2017-05-30 12:44:50 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-20 23:10:51 -07:00
|
|
|
with core.NameScope(
|
|
|
|
|
"{}_{}".format(model_helper_obj._device_prefix, device)
|
|
|
|
|
):
|
2017-05-30 12:44:50 -07:00
|
|
|
param_update_builder_fun(model_helper_obj)
|
|
|
|
|
else:
|
|
|
|
|
log.info("Calling optimizer builder function")
|
2017-07-21 16:22:21 -07:00
|
|
|
optimizer = optimizer_builder_fun(model_helper_obj)
|
|
|
|
|
model_helper_obj._optimizer = optimizer
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
(sync_blobs, sync_names) = _ComputeBlobsToSync(model_helper_obj)
|
|
|
|
|
sync_blobs_grouped = _GroupByDevice(
|
2017-06-20 23:10:51 -07:00
|
|
|
model_helper_obj,
|
2017-05-19 12:46:18 -07:00
|
|
|
devices,
|
|
|
|
|
sync_blobs,
|
|
|
|
|
[],
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._device_grouped_blobs.update(sync_blobs_grouped)
|
|
|
|
|
|
2017-03-10 17:50:12 -08:00
|
|
|
_InferBlobDevice(model_helper_obj)
|
2016-11-23 21:49:59 -08:00
|
|
|
_AnalyzeOperators(model_helper_obj)
|
|
|
|
|
|
2017-01-09 19:39:09 -08:00
|
|
|
# Configure dagnet to run with only one worker on the first iteration,
|
|
|
|
|
# to prevent concurrency problems with allocs and nccl.
|
|
|
|
|
arg = model_helper_obj.Proto().arg.add()
|
|
|
|
|
arg.name = "first_iter_only_one_worker"
|
|
|
|
|
arg.i = 1
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
# Add initial parameter syncs
|
|
|
|
|
log.info("Add initial parameter sync")
|
2017-06-27 19:32:37 -07:00
|
|
|
_SyncAllParams(
|
|
|
|
|
devices,
|
|
|
|
|
model_helper_obj,
|
|
|
|
|
model_helper_obj.param_init_net,
|
|
|
|
|
model_helper_obj.param_init_net,
|
|
|
|
|
rendezvous,
|
|
|
|
|
sync_names,
|
2017-06-28 12:36:15 -07:00
|
|
|
max_concurrent_distributed_ops=1
|
2017-05-19 12:46:18 -07:00
|
|
|
)
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-06-01 08:31:33 -07:00
|
|
|
# Handle any operations that need to be done after parameter sync
|
|
|
|
|
# i.e. making sure multi-precision copies of parameters are up-to-date
|
|
|
|
|
if post_sync_builder_fun is not None:
|
|
|
|
|
for device in devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
device_opt = core.DeviceOption(model_helper_obj._device_type, device)
|
2017-06-01 08:31:33 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-20 23:10:51 -07:00
|
|
|
with core.NameScope(
|
|
|
|
|
"{}_{}".format(model_helper_obj._device_prefix, device)
|
|
|
|
|
):
|
2017-06-01 08:31:33 -07:00
|
|
|
post_sync_builder_fun(model_helper_obj)
|
|
|
|
|
|
2017-11-13 11:28:53 -08:00
|
|
|
assert not (optimize_gradient_memory and dynamic_memory_management), \
|
|
|
|
|
"""It is not advised to use gradient optimization ('memonger')
|
|
|
|
|
with dynamic memory management."""
|
|
|
|
|
|
2017-01-09 19:39:09 -08:00
|
|
|
if optimize_gradient_memory:
|
2017-05-26 11:25:46 -07:00
|
|
|
_OptimizeGradientMemorySimple(model_helper_obj, losses_by_gpu, devices)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-09-20 12:34:25 -07:00
|
|
|
if dynamic_memory_management:
|
|
|
|
|
_AddDynamicMemoryOptimization(model_helper_obj, blobs_to_keep, devices)
|
|
|
|
|
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj._data_parallel_model_init_nets = [
|
|
|
|
|
model_helper_obj.param_init_net,
|
|
|
|
|
]
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
|
|
|
|
|
model_helper_obj._data_parallel_model_nets = [
|
|
|
|
|
model_helper_obj.net
|
|
|
|
|
]
|
|
|
|
|
_AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-09-15 16:05:58 -07:00
|
|
|
if shared_model:
|
|
|
|
|
_RemapParameterBlobsForSharedModel(model_helper_obj, all_params)
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-11-19 23:28:40 -08:00
|
|
|
def Parallelize_GPU_BMUF(*args, **kwargs):
|
|
|
|
|
kwargs['cpu_device'] = False
|
|
|
|
|
Parallelize_BMUF(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def Parallelize_CPU_BMUF(*args, **kwargs):
|
|
|
|
|
kwargs['cpu_device'] = True
|
|
|
|
|
Parallelize_BMUF(*args, **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def Parallelize_BMUF(
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj,
|
|
|
|
|
input_builder_fun,
|
|
|
|
|
forward_pass_builder_fun,
|
|
|
|
|
param_update_builder_fun,
|
|
|
|
|
block_learning_rate=1.0,
|
|
|
|
|
block_momentum=None,
|
2017-06-06 23:59:46 -07:00
|
|
|
devices=None,
|
2017-06-21 16:14:39 -07:00
|
|
|
rendezvous=None,
|
2017-05-15 18:02:16 -07:00
|
|
|
net_type='dag',
|
2017-11-19 23:28:40 -08:00
|
|
|
master_device=None,
|
2017-06-21 16:14:39 -07:00
|
|
|
use_nccl=False,
|
2017-08-11 13:50:05 -07:00
|
|
|
nesterov=False,
|
2017-05-31 00:17:37 -07:00
|
|
|
optimize_gradient_memory=False,
|
2017-06-21 16:14:39 -07:00
|
|
|
reset_momentum_sgd=False,
|
2017-06-22 14:30:50 -07:00
|
|
|
warmup_iterations=None,
|
2017-06-21 16:14:39 -07:00
|
|
|
max_concurrent_distributed_ops=4,
|
2017-09-12 10:20:22 -07:00
|
|
|
add_blobs_to_sync=None,
|
2017-11-19 23:28:40 -08:00
|
|
|
num_threads_per_device=4,
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
cpu_device=False,
|
|
|
|
|
barrier_net_timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC,
|
2017-05-15 18:02:16 -07:00
|
|
|
):
|
|
|
|
|
'''
|
|
|
|
|
Function to create model that run on many GPUs and creates a net for
|
|
|
|
|
parameter_updates that can be run independently for number of iterations
|
|
|
|
|
then followed by another net that runs once to compute the final parameter
|
|
|
|
|
updates according to block wise model update filtering rule described
|
|
|
|
|
in : Scalable Training of Deep Learning Machines by Incremental Block
|
|
|
|
|
Training with Intra-block Parallel Optimization and Blockwise Model-Update
|
|
|
|
|
Filtering (ICASSP 2016).
|
|
|
|
|
'''
|
2017-11-19 23:28:40 -08:00
|
|
|
assert scope.CurrentDeviceScope() is None \
|
|
|
|
|
or scope.CurrentDeviceScope().device_type == caffe2_pb2.CPU, \
|
|
|
|
|
"Parallelize must be called without device-scope, \
|
|
|
|
|
device scope was: {}".format(scope.CurrentDeviceScope())
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
assert isinstance(model_helper_obj, model_helper.ModelHelper)
|
|
|
|
|
|
2017-06-06 23:59:46 -07:00
|
|
|
if devices is None:
|
2018-11-29 13:58:11 -08:00
|
|
|
devices = list(range(0, workspace.NumGpuDevices()))
|
2017-11-19 23:28:40 -08:00
|
|
|
if master_device is None:
|
|
|
|
|
master_device = devices[0]
|
|
|
|
|
|
|
|
|
|
if not cpu_device:
|
|
|
|
|
for gpu in devices:
|
2018-11-29 13:58:11 -08:00
|
|
|
if gpu >= workspace.NumGpuDevices():
|
2017-11-19 23:28:40 -08:00
|
|
|
log.warning("** Only {} GPUs available, GPUs {} requested".format(
|
2018-11-29 13:58:11 -08:00
|
|
|
workspace.NumGpuDevices(), devices))
|
2017-11-19 23:28:40 -08:00
|
|
|
break
|
2018-11-29 13:58:11 -08:00
|
|
|
model_helper_obj._device_type = workspace.GpuDeviceType
|
2017-11-19 23:28:40 -08:00
|
|
|
model_helper_obj._device_prefix = "gpu"
|
|
|
|
|
else:
|
|
|
|
|
model_helper_obj._device_type = caffe2_pb2.CPU
|
|
|
|
|
model_helper_obj._device_prefix = "cpu"
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
model_helper_obj._devices = devices
|
2017-06-23 17:13:13 -07:00
|
|
|
model_helper_obj._rendezvous = rendezvous
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
model_helper_obj._sync_barrier_net = None
|
2017-09-12 10:20:22 -07:00
|
|
|
model_helper_obj._broadcast_context = None
|
2017-09-15 16:05:58 -07:00
|
|
|
model_helper_obj._shared_model = False
|
2017-11-19 23:28:40 -08:00
|
|
|
master_dev_opt = core.DeviceOption(model_helper_obj._device_type, master_device)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-11-19 23:28:40 -08:00
|
|
|
# question: rendezvous structure
|
2017-06-21 16:14:39 -07:00
|
|
|
num_shards = rendezvous['num_shards'] if rendezvous else 1
|
2017-11-19 23:28:40 -08:00
|
|
|
# num_devices is #devices across all machines
|
|
|
|
|
num_devices = len(devices) * num_shards
|
|
|
|
|
# num_workers is #threads to execute the DAG per shard
|
|
|
|
|
num_workers = num_threads_per_device * len(devices)
|
2017-06-21 16:14:39 -07:00
|
|
|
if rendezvous:
|
2017-11-19 23:28:40 -08:00
|
|
|
num_workers += 8
|
|
|
|
|
|
|
|
|
|
loss_scale = 1.0 / num_devices
|
2017-05-15 18:02:16 -07:00
|
|
|
if block_momentum is None:
|
2017-11-19 23:28:40 -08:00
|
|
|
block_momentum = 1.0 - 1.0 / num_devices
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
max_concurrent_distributed_ops = min(
|
|
|
|
|
max_concurrent_distributed_ops,
|
2017-11-19 23:28:40 -08:00
|
|
|
num_workers - 1
|
2017-06-21 16:14:39 -07:00
|
|
|
)
|
|
|
|
|
|
2017-11-19 23:28:40 -08:00
|
|
|
model_helper_obj.net.Proto().num_workers = num_workers
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj.net.Proto().type = net_type
|
|
|
|
|
|
|
|
|
|
# A net for initializing global model parameters. Its called once in the
|
|
|
|
|
# same step as net parameters initialization.
|
|
|
|
|
model_helper_obj._global_model_init_net = core.Net('global_model_init')
|
|
|
|
|
model_helper_obj._global_model_init_net.Proto().type = net_type
|
2017-05-31 15:07:27 -07:00
|
|
|
model_helper_obj._global_model_init_net.Proto().num_workers = \
|
2017-11-19 23:28:40 -08:00
|
|
|
num_workers
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
# A net for computing final parameter updates. Its will run once after
|
|
|
|
|
# running net (local models updates) for `num_local_iterations` times.
|
|
|
|
|
model_helper_obj._global_model_param_updates_net = core.Net('global_model')
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Proto().type = net_type
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Proto().num_workers = \
|
2017-11-19 23:28:40 -08:00
|
|
|
num_workers
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
def _v(param):
|
|
|
|
|
return "{}_v".format(param)
|
|
|
|
|
|
|
|
|
|
def _g(param):
|
|
|
|
|
return "{}_g".format(param)
|
|
|
|
|
|
2017-08-11 13:50:05 -07:00
|
|
|
def _v_prev(param):
|
|
|
|
|
return "{}_prev".format(param)
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
# Keep track of params that were in the model before: they are not
|
|
|
|
|
# data parallel, so we need to handle them separately
|
|
|
|
|
non_datapar_params = copy.copy(model_helper_obj.params)
|
|
|
|
|
model_helper_obj._losses_by_gpu = {}
|
|
|
|
|
|
|
|
|
|
def _InitializeModels(gpu_id):
|
|
|
|
|
input_builder_fun(model_helper_obj)
|
|
|
|
|
loss = forward_pass_builder_fun(model_helper_obj, loss_scale)
|
|
|
|
|
model_helper_obj._losses_by_gpu[gpu_id] = loss
|
2017-11-19 23:28:40 -08:00
|
|
|
_ForEachDevice(
|
|
|
|
|
devices,
|
|
|
|
|
_InitializeModels,
|
|
|
|
|
device_type=model_helper_obj._device_type,
|
|
|
|
|
device_prefix=model_helper_obj._device_prefix,
|
|
|
|
|
scoped=True
|
|
|
|
|
)
|
|
|
|
|
_ValidateParams(model_helper_obj.params)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
model_helper_obj._device_grouped_blobs =\
|
2017-06-20 23:10:51 -07:00
|
|
|
_GroupByDevice(model_helper_obj, devices,
|
|
|
|
|
model_helper_obj.params, non_datapar_params)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-05-26 11:25:46 -07:00
|
|
|
model_helper_obj._param_names =\
|
2017-11-19 23:28:40 -08:00
|
|
|
list(viewkeys(model_helper_obj._device_grouped_blobs))
|
2017-05-26 11:25:46 -07:00
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
_AddGradientOperators(
|
|
|
|
|
devices, model_helper_obj, model_helper_obj._losses_by_gpu
|
|
|
|
|
)
|
2017-11-19 23:28:40 -08:00
|
|
|
_ValidateParams(model_helper_obj.params)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
_InferBlobDevice(model_helper_obj)
|
|
|
|
|
|
|
|
|
|
def _InitializeParamUpdate(gpu_id):
|
|
|
|
|
param_update_builder_fun(model_helper_obj)
|
2017-11-19 23:28:40 -08:00
|
|
|
_ForEachDevice(
|
|
|
|
|
devices,
|
|
|
|
|
_InitializeParamUpdate,
|
|
|
|
|
device_type=model_helper_obj._device_type,
|
|
|
|
|
device_prefix=model_helper_obj._device_prefix,
|
|
|
|
|
scoped=True
|
|
|
|
|
)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2017-06-29 16:52:01 -07:00
|
|
|
model_parameter_names = list(
|
|
|
|
|
viewkeys(model_helper_obj._device_grouped_blobs)
|
|
|
|
|
)
|
2017-06-22 14:30:50 -07:00
|
|
|
if warmup_iterations is not None:
|
|
|
|
|
model_helper_obj._warmup_iterations = warmup_iterations
|
|
|
|
|
# A net for broadcasting gpu-0 (master shard) parameters after
|
|
|
|
|
# running net for `warmup_iterartions`.
|
|
|
|
|
model_helper_obj._warmup_broadcast = core.Net('warmup-broadcast')
|
|
|
|
|
model_helper_obj._warmup_broadcast.Proto().type = net_type
|
|
|
|
|
model_helper_obj._warmup_broadcast.Proto().num_workers = \
|
2017-11-19 23:28:40 -08:00
|
|
|
num_workers
|
2017-06-28 12:36:15 -07:00
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
_SyncAllParams(
|
2017-06-22 14:30:50 -07:00
|
|
|
devices,
|
|
|
|
|
model_helper_obj,
|
2017-06-27 19:32:37 -07:00
|
|
|
model_helper_obj.param_init_net,
|
2017-06-22 14:30:50 -07:00
|
|
|
model_helper_obj._warmup_broadcast,
|
2017-06-27 19:32:37 -07:00
|
|
|
rendezvous,
|
2017-06-28 12:36:15 -07:00
|
|
|
model_parameter_names,
|
|
|
|
|
max_concurrent_distributed_ops
|
2017-06-22 14:30:50 -07:00
|
|
|
)
|
2017-11-16 15:56:25 -08:00
|
|
|
for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
|
2017-11-19 23:28:40 -08:00
|
|
|
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
|
|
|
|
|
with core.DeviceScope(master_dev_opt):
|
2017-06-28 13:23:01 -07:00
|
|
|
model_helper_obj._warmup_broadcast.Copy(param, _g(param))
|
2017-06-22 14:30:50 -07:00
|
|
|
|
2017-11-19 23:28:40 -08:00
|
|
|
# (Step-0) Initialize momentum parameters on master device.
|
2017-06-29 16:52:01 -07:00
|
|
|
for param_name in viewkeys(model_helper_obj._device_grouped_blobs):
|
2017-11-19 23:28:40 -08:00
|
|
|
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
|
|
|
|
|
with core.DeviceScope(master_dev_opt):
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj._global_model_init_net.ConstantFill(
|
|
|
|
|
param, _v(param), value=0.0
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_init_net.Copy(param, _g(param))
|
2017-08-11 13:50:05 -07:00
|
|
|
if nesterov:
|
|
|
|
|
model_helper_obj._global_model_init_net.ConstantFill(
|
|
|
|
|
param, _v_prev(param), value=0.0
|
|
|
|
|
)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
# (Step-1) Update models for num_local_iterations.
|
|
|
|
|
|
2017-09-12 10:20:22 -07:00
|
|
|
# (Step-2) Compute post-local-updates average of the params.
|
2017-05-15 18:02:16 -07:00
|
|
|
# Sum model params across GPUs and store resutls in param_avg blob.
|
2017-06-21 16:14:39 -07:00
|
|
|
_AllReduceBlobs(
|
|
|
|
|
model_parameter_names,
|
|
|
|
|
devices,
|
|
|
|
|
model_helper_obj,
|
|
|
|
|
model_helper_obj._global_model_param_updates_net,
|
|
|
|
|
rendezvous,
|
|
|
|
|
use_nccl,
|
|
|
|
|
max_concurrent_distributed_ops
|
|
|
|
|
)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
# (Step-3) Update momentum params :
|
|
|
|
|
# param_v = block_momentum * param_v
|
|
|
|
|
# + block_learning_Rate * (param_avg - param)
|
2017-08-11 13:50:05 -07:00
|
|
|
# if nesterov momentum:
|
|
|
|
|
# param = param + param_v
|
|
|
|
|
# - block_momentum * (param_v - param_v_prev)
|
|
|
|
|
# param_v_prev = param_v
|
|
|
|
|
# else:
|
2017-05-15 18:02:16 -07:00
|
|
|
# param = param + param_v
|
2017-06-21 16:14:39 -07:00
|
|
|
for param_name in model_parameter_names:
|
2017-11-19 23:28:40 -08:00
|
|
|
param = model_helper_obj._device_grouped_blobs[param_name][master_device]
|
|
|
|
|
with core.DeviceScope(master_dev_opt):
|
2017-05-15 18:02:16 -07:00
|
|
|
# TODO(ataei) : Stop building the graph here to get model average ?
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Scale(
|
2017-11-19 23:28:40 -08:00
|
|
|
param, param, scale=1.0 / num_devices
|
2017-05-15 18:02:16 -07:00
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Sub(
|
|
|
|
|
[param, _g(param)], param
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Scale(
|
|
|
|
|
param, param, scale=block_learning_rate
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Scale(
|
|
|
|
|
_v(param), _v(param), scale=block_momentum
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Add(
|
|
|
|
|
[_v(param), param], _v(param)
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Add(
|
|
|
|
|
[_g(param), _v(param)], _g(param)
|
|
|
|
|
)
|
2017-08-11 13:50:05 -07:00
|
|
|
if nesterov:
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Sub(
|
|
|
|
|
[_v(param), _v_prev(param)], _v_prev(param)
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Scale(
|
|
|
|
|
_v_prev(param), _v_prev(param), scale=block_momentum
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Sub(
|
|
|
|
|
[_g(param), _v_prev(param)], _g(param)
|
|
|
|
|
)
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.Copy(
|
|
|
|
|
_v(param), _v_prev(param)
|
|
|
|
|
)
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj._global_model_param_updates_net.Copy(
|
|
|
|
|
_g(param), param
|
|
|
|
|
)
|
2017-06-21 16:14:39 -07:00
|
|
|
|
2017-06-28 12:36:15 -07:00
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
_SyncAllParams(
|
2017-06-21 16:14:39 -07:00
|
|
|
devices,
|
|
|
|
|
model_helper_obj,
|
2017-06-27 19:32:37 -07:00
|
|
|
model_helper_obj.param_init_net,
|
2017-06-21 16:14:39 -07:00
|
|
|
model_helper_obj._global_model_param_updates_net,
|
2017-06-27 19:32:37 -07:00
|
|
|
rendezvous,
|
2017-06-28 12:36:15 -07:00
|
|
|
model_parameter_names,
|
|
|
|
|
max_concurrent_distributed_ops
|
2017-06-21 16:14:39 -07:00
|
|
|
)
|
|
|
|
|
|
2017-09-12 10:20:22 -07:00
|
|
|
# Add additional syncs
|
|
|
|
|
if add_blobs_to_sync is not None:
|
|
|
|
|
AddBlobSync(
|
|
|
|
|
model_helper_obj,
|
|
|
|
|
add_blobs_to_sync,
|
|
|
|
|
net=model_helper_obj._global_model_param_updates_net)
|
|
|
|
|
|
2017-05-31 00:17:37 -07:00
|
|
|
# Reset momentum-SGD parameters
|
|
|
|
|
if reset_momentum_sgd:
|
|
|
|
|
momentum_ops = [op for op in model_helper_obj.net.Proto().op
|
|
|
|
|
if op.type == 'MomentumSGDUpdate']
|
|
|
|
|
for op in momentum_ops:
|
|
|
|
|
momentum_blob = op.input[1]
|
|
|
|
|
with core.DeviceScope(op.device_option):
|
|
|
|
|
model_helper_obj._global_model_param_updates_net.ConstantFill(
|
|
|
|
|
[momentum_blob], momentum_blob, value=0.0
|
|
|
|
|
)
|
|
|
|
|
|
2017-05-26 11:25:46 -07:00
|
|
|
if optimize_gradient_memory:
|
|
|
|
|
_OptimizeGradientMemorySimple(
|
|
|
|
|
model_helper_obj, model_helper_obj._losses_by_gpu, devices
|
|
|
|
|
)
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj._data_parallel_model_init_nets = [
|
|
|
|
|
model_helper_obj.param_init_net,
|
|
|
|
|
model_helper_obj._global_model_init_net
|
|
|
|
|
]
|
2017-06-22 14:30:50 -07:00
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
model_helper_obj._data_parallel_model_nets = [
|
|
|
|
|
model_helper_obj.net,
|
|
|
|
|
(model_helper_obj._global_model_param_updates_net, 1)
|
|
|
|
|
]
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
_AddBarrierToModelNets(model_helper_obj, barrier_net_timeout_sec)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
2018-07-22 00:08:34 -07:00
|
|
|
def CreateNet(model, overwrite=False):
|
|
|
|
|
for net_iters in model._data_parallel_model_nets:
|
|
|
|
|
if isinstance(net_iters, tuple):
|
|
|
|
|
workspace.CreateNet(net_iters[0], overwrite=overwrite)
|
|
|
|
|
else:
|
|
|
|
|
workspace.CreateNet(net_iters, overwrite=overwrite)
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
def RunInitNet(model):
|
|
|
|
|
for init_net in model._data_parallel_model_init_nets:
|
|
|
|
|
workspace.RunNetOnce(init_net)
|
2018-07-22 00:08:34 -07:00
|
|
|
CreateNet(model)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
|
2017-06-22 14:30:50 -07:00
|
|
|
def RunWarmup(model):
|
|
|
|
|
workspace.RunNet(model.net, model._warmup_iterations)
|
|
|
|
|
workspace.RunNetOnce(model._warmup_broadcast)
|
|
|
|
|
|
|
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
def RunNet(model, num_iterations):
|
|
|
|
|
for net_iter in model._data_parallel_model_nets:
|
|
|
|
|
if isinstance(net_iter, tuple):
|
|
|
|
|
workspace.RunNet(net_iter[0].Proto().name, net_iter[1])
|
|
|
|
|
else:
|
2017-05-31 00:17:37 -07:00
|
|
|
workspace.RunNet(net_iter, num_iterations)
|
2017-05-15 18:02:16 -07:00
|
|
|
|
|
|
|
|
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
def _AddBarrierToModelNets(model, barrier_net_timeout_sec):
|
|
|
|
|
if model._rendezvous is not None and model._rendezvous['engine'] == 'GLOO':
|
|
|
|
|
# Synchronize DPM at the start of each epoch. This allows shards that
|
|
|
|
|
# starts an epoch sooner to wait for slower shards. Without this,
|
|
|
|
|
# shards that are faster than others will begin training the next epoch
|
|
|
|
|
# while stragglers are blocked on IO, and may timeout after 30 seconds
|
|
|
|
|
# (_DEFAULT_TIMEOUT_SEC).
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
# We pass in model.param_init_net so that the barrier net can be run as
|
|
|
|
|
# part of the param_init_net.
|
2018-07-22 00:08:34 -07:00
|
|
|
|
|
|
|
|
model._barrier_init_net = core.Net("barrier_init_net")
|
|
|
|
|
|
|
|
|
|
model._barrier_net = _CreateBarrierNet(model, model._barrier_init_net,
|
|
|
|
|
"pre_training", barrier_net_timeout_sec)
|
|
|
|
|
|
|
|
|
|
model._data_parallel_model_init_nets.insert(0, model._barrier_init_net)
|
|
|
|
|
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
model._data_parallel_model_nets.insert(0, model._barrier_net)
|
|
|
|
|
|
|
|
|
|
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
def _CreateBarrierNet(model, init_net, name_prefix, timeout_sec):
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
log.info("Creating barrier net")
|
|
|
|
|
assert model._rendezvous['engine'] == 'GLOO', "Engine does not support barrier"
|
|
|
|
|
comm_world = _CreateOrCloneCommonWorld(
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
init_net,
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
name_prefix + "_barrier_cw",
|
|
|
|
|
rendezvous=model._rendezvous,
|
|
|
|
|
timeout_sec=timeout_sec,
|
|
|
|
|
)
|
|
|
|
|
barrier_net = core.Net(name_prefix + "_barrier_net")
|
|
|
|
|
barrier_net.Barrier(
|
|
|
|
|
inputs=[comm_world],
|
|
|
|
|
outputs=[],
|
|
|
|
|
engine=model._rendezvous['engine'],
|
|
|
|
|
)
|
|
|
|
|
return barrier_net
|
|
|
|
|
|
|
|
|
|
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
# DEPRECATED: See warnings below.
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
def Synchronize(model, timeout_sec=_DEFAULT_BARRIER_NET_TIMEOUT_SEC):
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
warnings.warn("The Synchronize API has been deprecated. We now have a "
|
|
|
|
|
"barrier net which runs before training to ensure all hosts wait "
|
|
|
|
|
"before training starts. The default timeout for the barrier is "
|
|
|
|
|
"300s and it can be overridden using the barrier_net_timeout_sec "
|
|
|
|
|
"parameter when calling Parallelize.",
|
|
|
|
|
category=DeprecationWarning, stacklevel=2)
|
2018-03-26 16:00:18 -07:00
|
|
|
if model._rendezvous is None or model._rendezvous['num_shards'] <= 1:
|
|
|
|
|
# Single host case
|
|
|
|
|
return
|
|
|
|
|
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
if model._sync_barrier_net is None:
|
Update from facebook (#7451)
* [bootcamp] Improve "Shape" operator to support axes specification
To improve .shape operator of Caffe2 to support x.shape(tensor, axes), which takes an optional int array "axes" as input. For example, x.shape(tensor, [1, 0]) will return the dimension for axis 1 and 0 following the specified order. For current version, "axes" input allows duplications and can have arbitrary length.
* Back out "Add barrier net that runs before training nets"
Original commit changeset: b373fdc9c30f. Need additional changes to some callers to support barrier failures.
* Change warning to verbose log to reduce log spam
The `LOG(WARNING)` was a bit spammy for regular use so lets just make it a `VLOG`.
* Extract the shared code from different caffe2_benchmark binaries
The OSS benchmark and Internal benchmark will share most functions in the benchmark.
* Support MFR in sequence training
As titled.
* Make knowledge distillation work with using logged prediction feature as teacher label.
1) Add loading raw dense feature as teacher label.
2) Optional calibration function for teacher label
3) Add teacher label into generic unit test
4) Deprecated TTSN workflow version using feature_options to config teacher label
* [C2/CUDA]: unjoined cross entropy sigmoid
as desc
* Add async_scheduling executor into deferrable_net_exec_test
Add async_scheduling into tests and fix some exception cases
* Fix Event disabled error
When disabling event in RNN ops make sure we don't call Finish on disabled
event from op's RunAsync
* cuda ensure cpu output op can handle both TensorCPU and TensorCUDA
as desc.
* [C2 Core] Infer input device option in C2 hypothesis_test checkers
Improve how we default input blob device options.
Previously it defaults as where op lives but it is not necessarily the case.
For example:
CopyCPUToGPU
* [C2 Op]SplitByLengthsOp CPU/GPU implementation
[C2 Op]SplitByLengthsOp CPU/GPU implementation
* fix undefined symbol error
not sure why we're getting undefined symbol even with link_whole = True
Need to figure out why but need this workaround for now
* Add tools in DAIPlayground platform to help debugging models
Add additional tools to allow Plauground override individual method defined in AnyExp. This will allow user to create module that specificly change certain default method behavior. An example included in this diff is deactivating test model and checkpointing. When debugging any model problems, switching off components helps me quickly narrow down the location of the bug. The technique is extensively used in task T27038712 (Steady memory increase in EDPM, eventually resulting in gloo/cuda.cu:34: out of memory)
* add shape and type inference for int8 conversion operator
* Fix flaky test for group_norm
Fix flaky test for group_norm
* Fix group_norm_op_test flaky
Fix group_norm_op_test flaky
* Implementation of composite learning rate policy
In many state-of-the-arts deep learning works, people use a simple trick to
schedule the learning rate: use a fixed learning rate until error plateaus
and then switch to a different fixed learning rate, and so on. In this diff,
we implemented a simple version of the composite learning rate. The user gives
a set of learning rates policies and corresponding iteration nums, and the
optimizer will change the learning rate policy based on the number of iterations so far.
For example, the user give two learning rate policies, one is FixedLearningRate
and PolyLearningRate, with an iteration number of 1k. Then the first 1k iteration,
we use FixedLearningRate. For the following iterations, we use PolyLearningRate.
* Split two use cases of CachedReader into two classes, DBFileReader and CachedReader
# Use Cases:
1). input: DB file -> output: DatasetReader.
Use DBFileReader.
2). input: Reader -> build cache DB file -> output: DatasetReader.
Use CachedReader.
# Changes to CachedReader:
1). Move db_path to the constructor.
Because in mock reader. cache will always be built ahead.
# Changes to tests:
1). Make a separate TestCase class for CachedReader and DBFileReader.
2). Make it possible to add more test functions by adding setUp, tearDown and _make_temp_path.
3). Make delete db_path more general. `db_path` could be a file for `log_file_db`, but could also be a directory for `leveldb`.
* Back out "On Mobile phones, call GlobalInit with no arguments in predictor in case we need to perform initialization"
Original commit changeset: 4489c6133f11
* Fix LARS bug
Fixed a bug in the LARS implementation which caused all subsequent blobs not using LARS to have the LARS learning rate multiplier applied to them.
* [tum] support sparse init & add uniformFill option
as title
* Propagate exception for async nets
Capture the exception when an exception is thrown in async nets and re-throw it after wait(). This allows exceptions to be propagated up to the caller.
This diff was a part of D7752068. We split the diff so that C2 core files changes are in a separate diff.
* Automatic update of fbcode/onnx to 69894f207dfcd72d1e70497d387201cec327efbc
Previous import was 403ccfbd0161c38f0834413d790bad0874afbf9a
Included changes:
- **[69894f2](https://github.com/onnx/onnx/commit/69894f2)**: Use op schema.all tensor types in random like definitions (#865) <Scott McKay>
- **[b9d6b90](https://github.com/onnx/onnx/commit/b9d6b90)**: Clarify random like operators (#846) <Scott McKay>
- **[fc6b5fb](https://github.com/onnx/onnx/commit/fc6b5fb)**: Refactor shape inference implementation (#855) <anderspapitto>
- **[b7d8dc8](https://github.com/onnx/onnx/commit/b7d8dc8)**: fix cmake warning message (#863) <Eric S. Yu>
- **[f585c5d](https://github.com/onnx/onnx/commit/f585c5d)**: add pytorch-operator test for tile (#831) <Wenhao Hu>
- **[993fe70](https://github.com/onnx/onnx/commit/993fe70)**: add install step (#832) <Eric S. Yu>
- **[68bc26c](https://github.com/onnx/onnx/commit/68bc26c)**: add type inference for traditional ml ops except classifier ops. (#857) <Ke Zhang>
- **[9cc0cda](https://github.com/onnx/onnx/commit/9cc0cda)**: fix string representation of scalar types (#858) <G. Ramalingam>
- **[1078925](https://github.com/onnx/onnx/commit/1078925)**: fix y in pow test case to scalar (#852) <Wenhao Hu>
- **[c66fb6f](https://github.com/onnx/onnx/commit/c66fb6f)**: Add some math function shape inference (#845) <anderspapitto>
- **[ff667d1](https://github.com/onnx/onnx/commit/ff667d1)**: Refactor return type and docs for ONNXIFI_BACKEND_DIRECTX_ID (#853) <Marat Dukhan>
- **[11c6876](https://github.com/onnx/onnx/commit/11c6876)**: clear initializer names when clear initializer (#849) <Wenhao Hu>
- **[73c34ae](https://github.com/onnx/onnx/commit/73c34ae)**: Clarify FeatureVectorizer description. (#843) <Scott McKay>
- **[1befb9b](https://github.com/onnx/onnx/commit/1befb9b)**: Remove useless text in docs (#850) <Lu Fang>
- **[e84788f](https://github.com/onnx/onnx/commit/e84788f)**: Fix SELU attributes' default values (#839) <Lu Fang>
- **[ebac046](https://github.com/onnx/onnx/commit/ebac046)**: Add tile test case (#823) <Wenhao Hu>
- **[8b7a925](https://github.com/onnx/onnx/commit/8b7a925)**: a few more shape inference functions (#772) <anderspapitto>
- **[9718f42](https://github.com/onnx/onnx/commit/9718f42)**: Make the coefficient non optional for LinearClassifier (#836) <Jaliya Ekanayake>
- **[ef083d0](https://github.com/onnx/onnx/commit/ef083d0)**: Add save_tensor and load_tensor functions for Protos (#770) <Lu Fang>
- **[45ceb55](https://github.com/onnx/onnx/commit/45ceb55)**: Check if CMAKE_BUILD_TYPE set before project(). (#812) <Sergii Dymchenko>
- **[4b3d2b0](https://github.com/onnx/onnx/commit/4b3d2b0)**: [WIP] reenable shape inference tests (#834) <anderspapitto>
- **[22d17ee](https://github.com/onnx/onnx/commit/22d17ee)**: RNN tests: LSTM, GRU, SimpleRNN (#739) <Peyman Manikashani>
- **[de65b95](https://github.com/onnx/onnx/commit/de65b95)**: dimension denotation (#443) <Tian Jin>
- **[eccc76e](https://github.com/onnx/onnx/commit/eccc76e)**: fix field number issue in onnx operator proto and enable its build (#829) <Ke Zhang>
- **[d582beb](https://github.com/onnx/onnx/commit/d582beb)**: disable shape inference test to unbreak ci (#830) <Lu Fang>
- **[485b787](https://github.com/onnx/onnx/commit/485b787)**: function proto for composite op. (#802) <Ke Zhang>
- **[cd58928](https://github.com/onnx/onnx/commit/cd58928)**: specify defaults for attributes of Affine op (#820) <G. Ramalingam>
- **[7ee2cf9](https://github.com/onnx/onnx/commit/7ee2cf9)**: merge the dummy backend back into the main one (#743) <anderspapitto>
- **[1c03a5a](https://github.com/onnx/onnx/commit/1c03a5a)**: [Proposal] ONNX Interface for Framework Integration (previously ONNX Backend API) header and docs (#551) <Marat Dukhan>
- **[3769a98](https://github.com/onnx/onnx/commit/3769a98)**: Rename real model test case from VGG-16 to ZFNet (#821) <Lu Fang>
* [C2]ReluN Op
relu n op.
tf reference: https://www.tensorflow.org/api_docs/python/tf/nn/relu6
* Call destructor when assigning a blob value
* Add executor overrides
Add executor overrides flag to enable migration to async_scheduling executor
* Add barrier net that runs before training nets - attempt #2
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow.
This change was landed previously but caused errors for some EDPM workflows - See https://fb.facebook.com/groups/1426530000692545/permalink/1906766366002237/ - because EDPM assumes any call to CreateOrCloneCommonWorld and Gloo ops are wrapped in exception handlers but in this case exception thrown in the barrier init net is not handled.
To address this issue, we add _CreateOrCloneCommonWorld to the param_init_net instead of a new barrier init net. Since errors for param_init_net run is handled gracefully and re-rendezvous, it should fixes the problem.
* Handle empty nets in async_scheduling
Make sure we don't get stuck on empty nets
* use CUDA_ARCH for conditional compile
* [C2 fix] infer function for ensure_cpu_output_op
* Update group_norm test to reduce flaky test
* Fix lr_multiplier for GPU
2018-05-10 23:14:27 -07:00
|
|
|
barrier_init_net = core.Net("sync_barrier_init_net")
|
|
|
|
|
model._sync_barrier_net = _CreateBarrierNet(
|
|
|
|
|
model, barrier_init_net, "sync", timeout_sec)
|
|
|
|
|
workspace.RunNetOnce(barrier_init_net)
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
workspace.CreateNet(model._sync_barrier_net)
|
|
|
|
|
model._sync_barrier_net_timeout = timeout_sec
|
|
|
|
|
assert model._sync_barrier_net_timeout == timeout_sec, \
|
[Caffe2] Changes done inside Facebook (#6378)
* fix unit test for sqrt op
From the error logging:
[idx, grad, grad_estimate] are:
[[ 146. 0.5 0.45776367]
[ 147. 0.5 0.45776367]
The gradient == 0.5 is correct, which means the SqrtOp and its gradient is doing right job. (Because y = sqrt(x), loss = y^2/2 = x/2, and then d(loss)/dx = 1/2 = 0.5; )
The test failed because of numerical problem of grad_estimate (in unit test). It can be because the step_size is small, and float precision is not high (when there are multiple elements in the tensor, we do sum(y^2) to compute loss)
This diff
- increase the step size, and also move the test cases to be further away from 0 (where sqrt(x) is not well defined) to be safe :)
- also clean up, and merge the test case for inplace Vs. non-inplace
Tested with:
`CAFFE2_HYPOTHESIS_PROFILE=debug ai_bt caffe2/caffe2/python/operator_test:elementwise_ops_test -- "test_sqrt"`
* CompositeReader & CompositeReaderBuilder
A new type of reader gluing multiple readers together.
* Back out "Revert D7394363: [GanH]: Log D Trick for Cross Entropy with Sigmoid"
Original commit changeset: 9325a4356dbe
* [dai][WIP] convert params to int8 on ps before sending to trainer
Add float->uint8 conversion in addition to float->fp16 conversion in model_saver.
* [easy] improve unit test for sparse length sum ops
as desc.
#accept2ship
* Update GitHub upstream to 771fcb3455cbfe69c2abcc4cb3bd7ef92d59af24
* move sparse hash unique ops to OOS and add unit tests
- move the SparseHash version to OOS, since 'sparsehash' is already deps of caffe2 OOS: https://fburl.com/arssw4n1
- The 'SparseHash' engine is also being used in OOS, so the SparseHash version shall be in OOS to reduce confusion: https://fburl.com/o5ea7ah2
- fix the CUDA UniqueOp for the case when batch is empty.
- add unit test
* group_norm_op for caffe2
This is the cuda op for Group Normalization (GN): https://arxiv.org/abs/1803.08494
This code implements GN in one op that computes Y=gamma * (X-mu) / sigma + beta and also its gradients. It is expected to have minimal memory consumption (similar to the BN op), without creating new blobs if GN were implemented as several ops (e.g., reshape, norm_mean/std, affine_channel).
* Resubmit D7405233: disappeared in D7464958
OOS publish causes the op missing -- however, test was still there
* [c2] add sparse hash engine for cuda unique op
The SparseHash version of UniqueOp copy input tensor to CPU, and make use of sparse hash map to get unique output, and then copy back to GPU.
* [dper][gpu] enable unit testing gpu trainer for sparse nn
to debug the GPU trainer using mock data in unit test.
make it easier to develop GPU trainer for new models.
* Reuse Gloo context for Synchronize() calls
Previously we were creating (and leaking) the Gloo context on each call to Synchronize(). Now only run the common world op and create the barrier net once, then run the barrier net on each Synchronize() call. Since timeout is associated with the Gloo context, assert that the timeout is fixed instead of trying to handle the complexity of multiple timeouts (and associated contexts).
* [GanH/WGAN][1/n]: add FC param clipping
as titled
* [mobile] minimizing changes between caffe2_benchmark and speed_benchmark
* [GanH]: enable diagnose within model
avoid finding blob names but to directly enable inside the model
* Add `net_transformer_fun` option to DPM
This callback allows for various transformations to be made to the
model after gradient operators have been added. The immediate motivation for
this is to allow transformations such has "checkpoint-and-recompute" which
allow trading off memory for additional compute.
Adding several callbacks like this has made DPM's API less than ideal at this
stage. However, I could not find any reasonable alternative.
* [DT] [33/n] Compile flow task groups
task groups need to compiled in order to pickle the object in fblearner. However I also changed the Job's compile function as creating new object is not necessary.
* Initial commit for sparse_normalize vectorization and benchmark
* [GanH]: LB Calibration for JSD
as titled
* Tracing event in async executor
Adding event tracing through TRACE_EVENT macro in async executor
* [Resubmit] D7409751 Reseting book-keeping blobs when the reservoir is reset
D7409751 got lost in D7464958
* Visualizing realtime weights values
we want to visualize the weights values as optimizer is iterating. This diff supports to visual the weights at an assigned index.
Currently, we assume the blob to be 2 dimensional.
* [GanH][Easy]: Fix Homotopy Weighting
apparantely, there was a bug in homotopy weight (alpha, beta) update
* [c2] move sparse hash unique op out of oss
so that oss do not need to depend on google hash map.
* Get rid of std::round as it's not supported on Android
* Revert changes on setup.py
* Skip shaky test on Dataio
* fix
2018-04-10 21:11:43 -07:00
|
|
|
"Must use fixed timeout, {} != {}".format(
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
model._sync_barrier_net_timeout, timeout_sec
|
[Caffe2] Changes done inside Facebook (#6378)
* fix unit test for sqrt op
From the error logging:
[idx, grad, grad_estimate] are:
[[ 146. 0.5 0.45776367]
[ 147. 0.5 0.45776367]
The gradient == 0.5 is correct, which means the SqrtOp and its gradient is doing right job. (Because y = sqrt(x), loss = y^2/2 = x/2, and then d(loss)/dx = 1/2 = 0.5; )
The test failed because of numerical problem of grad_estimate (in unit test). It can be because the step_size is small, and float precision is not high (when there are multiple elements in the tensor, we do sum(y^2) to compute loss)
This diff
- increase the step size, and also move the test cases to be further away from 0 (where sqrt(x) is not well defined) to be safe :)
- also clean up, and merge the test case for inplace Vs. non-inplace
Tested with:
`CAFFE2_HYPOTHESIS_PROFILE=debug ai_bt caffe2/caffe2/python/operator_test:elementwise_ops_test -- "test_sqrt"`
* CompositeReader & CompositeReaderBuilder
A new type of reader gluing multiple readers together.
* Back out "Revert D7394363: [GanH]: Log D Trick for Cross Entropy with Sigmoid"
Original commit changeset: 9325a4356dbe
* [dai][WIP] convert params to int8 on ps before sending to trainer
Add float->uint8 conversion in addition to float->fp16 conversion in model_saver.
* [easy] improve unit test for sparse length sum ops
as desc.
#accept2ship
* Update GitHub upstream to 771fcb3455cbfe69c2abcc4cb3bd7ef92d59af24
* move sparse hash unique ops to OOS and add unit tests
- move the SparseHash version to OOS, since 'sparsehash' is already deps of caffe2 OOS: https://fburl.com/arssw4n1
- The 'SparseHash' engine is also being used in OOS, so the SparseHash version shall be in OOS to reduce confusion: https://fburl.com/o5ea7ah2
- fix the CUDA UniqueOp for the case when batch is empty.
- add unit test
* group_norm_op for caffe2
This is the cuda op for Group Normalization (GN): https://arxiv.org/abs/1803.08494
This code implements GN in one op that computes Y=gamma * (X-mu) / sigma + beta and also its gradients. It is expected to have minimal memory consumption (similar to the BN op), without creating new blobs if GN were implemented as several ops (e.g., reshape, norm_mean/std, affine_channel).
* Resubmit D7405233: disappeared in D7464958
OOS publish causes the op missing -- however, test was still there
* [c2] add sparse hash engine for cuda unique op
The SparseHash version of UniqueOp copy input tensor to CPU, and make use of sparse hash map to get unique output, and then copy back to GPU.
* [dper][gpu] enable unit testing gpu trainer for sparse nn
to debug the GPU trainer using mock data in unit test.
make it easier to develop GPU trainer for new models.
* Reuse Gloo context for Synchronize() calls
Previously we were creating (and leaking) the Gloo context on each call to Synchronize(). Now only run the common world op and create the barrier net once, then run the barrier net on each Synchronize() call. Since timeout is associated with the Gloo context, assert that the timeout is fixed instead of trying to handle the complexity of multiple timeouts (and associated contexts).
* [GanH/WGAN][1/n]: add FC param clipping
as titled
* [mobile] minimizing changes between caffe2_benchmark and speed_benchmark
* [GanH]: enable diagnose within model
avoid finding blob names but to directly enable inside the model
* Add `net_transformer_fun` option to DPM
This callback allows for various transformations to be made to the
model after gradient operators have been added. The immediate motivation for
this is to allow transformations such has "checkpoint-and-recompute" which
allow trading off memory for additional compute.
Adding several callbacks like this has made DPM's API less than ideal at this
stage. However, I could not find any reasonable alternative.
* [DT] [33/n] Compile flow task groups
task groups need to compiled in order to pickle the object in fblearner. However I also changed the Job's compile function as creating new object is not necessary.
* Initial commit for sparse_normalize vectorization and benchmark
* [GanH]: LB Calibration for JSD
as titled
* Tracing event in async executor
Adding event tracing through TRACE_EVENT macro in async executor
* [Resubmit] D7409751 Reseting book-keeping blobs when the reservoir is reset
D7409751 got lost in D7464958
* Visualizing realtime weights values
we want to visualize the weights values as optimizer is iterating. This diff supports to visual the weights at an assigned index.
Currently, we assume the blob to be 2 dimensional.
* [GanH][Easy]: Fix Homotopy Weighting
apparantely, there was a bug in homotopy weight (alpha, beta) update
* [c2] move sparse hash unique op out of oss
so that oss do not need to depend on google hash map.
* Get rid of std::round as it's not supported on Android
* Revert changes on setup.py
* Skip shaky test on Dataio
* fix
2018-04-10 21:11:43 -07:00
|
|
|
)
|
[Caffe2][fbcode=>GH sync] Update from facebook 4323b18ce13c (#7116)
* [fix] Re-enable events in RNN ops
We have earlier added event disabling in RNN ops as back then we didn't use
events, with current use cases this is no longer true
(https://fburl.com/8vd0lp8y)
* use ops with cude impl
* Revert D7729695: [caffe2][fix] Re-enable events in RNN ops
This reverts commit 4b215c7496fb724656ff4c776933a15bdbbcde5e
@bypass-lint
An infra SEV is better than not reverting this diff.
If you copy this password, see you in SEV Review!
@cause_a_sev_many_files
* [observer] Clean up observer_config.h
#accept2ship
* [1/n] Refactor dataio_test.py
Replace code duplication with a common function
* Add barrier net that runs before training nets
Add a synchonize barrier net that is run before training nets. With this net, shards that are faster will wait for other shards before start training. This reduce chances of the faster shards timing out during GLOO AllReduce.
Removed explicit data_parallel_model.py.synchronize call in holmes workflow. Similar change in speech/asr_training workflow will come in another diff.
* Support the dnnlowp backend in caffe2_benchmark
This is for SHARE operator latency evaluation
* Migrate integral_image_op to main caffe2
migrate integral_image_op(GPU version) given by https://fburl.com/yvqezigi
to caffe2/caffe2/operators and implement its CPU version. Write up a test
using the hypothesis_test mechanism
* [pos_disc, fbcode] Implement unjoined lr loss
As explained in https://our.intern.facebook.com/intern/wiki/Model_Based_Calibration/, when the dataset is an joined data set, where labels might change later, we need to use unjoined logloss.
The implementation is almost the same as in Sigrid (https://fburl.com/1trngsls), where
loss = y (log(p) - log(1-p)) + (1-y)(log(1-p)) = xy - (1-y)x - (1-y)log(1+exp(-x))
For x < 0, to ensure stability and avoid overflow, we reformulate the above exp as
loss = xy - (1-y)x - (1-y)x + (1-y)log(1+exp(x)) = xy + (1-y)log(1+exp(x))
Then the final expression becomes
loss = xy + (y - 1) x (x >= 0) - (1 - y) log(1 + exp(x - 2 x (x >= 0)))
where y is the true label, x is the dot product and p = logistic(x).
This kind of implementation is align with the current implementation of the original cross entropy in
https://phabricator.intern.facebook.com/diffusion/FBS/browse/master/fbcode/caffe2/caffe2/operators/cross_entropy_op.cc;0bae3b5d0f825897c5e0dd0ff10f489d7271bf25$7-13
* Keep the array to fix the conflict
* [C2] Compute Adagrad effective LR
The AdagradWithLR op outputs an extra blob which is contains the average effective learning rate across all weights in this blob.
* Open-source extractMetaNetDef & runGlobalInitialization, add new Predictor constructor from db file, and add run_map_outputs
1. Open-source extractMetaNetDef and runGlobalInitialization, for use in
2. new Predictor constructor from db file.
3. Add new run function that returns outputs as TensorMap
* Disable eigen cpu
Disable eigen cpu in transpose and reduce
* Introduce request_only/object_only property of ModelLayer
by default this is False
* A simple TC Caffe2 benchmark
We can run tunner, get MappingOptions and then use them to
compare against cuBLAS
currently broken due to LLVM issues. How to run:
hg checkout eec1ab31b59c03b8deded1c755a9abaf8c45be01
add D7401202
add D7434625
add D7506031
add D7540728
buck run @mode/dev-nosan tc/tc/benchmarks_python:caffe2_benchmark
* Move Caffe2 feature_maps_ops to open source
Need feature maps operators in open source project facebookresearch/BlueWhale
* Manually fix the conflicts in channel shuffle op
* Fix the inconsistency between different gh and fbcode
* Skip Adagrad GPU Test (Because some gpu implementation is missing)
* Fix another test to make sure it won't run on gpu when implementation is not available yet
2018-05-01 20:49:00 -07:00
|
|
|
log.info("Synchronize run barrier net.")
|
|
|
|
|
workspace.RunNet(model._sync_barrier_net)
|
2017-07-06 09:04:29 -07:00
|
|
|
|
|
|
|
|
|
2017-07-27 10:53:51 -07:00
|
|
|
def ConvertNetForDevice(net, device=None):
|
|
|
|
|
'''
|
|
|
|
|
Converts all blobs in the net to have namescope gpu_X, and correct
|
|
|
|
|
device scope. You can use this to enable AppendNet with a
|
|
|
|
|
forward_pass_builder_fun:
|
|
|
|
|
|
|
|
|
|
def builder_fun(model):
|
|
|
|
|
...
|
|
|
|
|
model.net.AppendNet(
|
|
|
|
|
data_parallel_model.ConvertNetForDevice(othermodel.net))
|
|
|
|
|
model.param_init_net.AppendNet(
|
|
|
|
|
data_parallel_model.ConvertNetForDevice(othermodel.param_init_net))
|
|
|
|
|
'''
|
|
|
|
|
mnet = copy.deepcopy(net)
|
|
|
|
|
|
|
|
|
|
if device is None:
|
|
|
|
|
device = scope.CurrentDeviceScope()
|
2019-02-20 16:53:23 -08:00
|
|
|
if core.IsGPUDeviceType(device.device_type):
|
|
|
|
|
device_prefix = "gpu"
|
|
|
|
|
elif device.device_type == caffe2_pb2.IDEEP:
|
|
|
|
|
device_prefix = "ideep"
|
|
|
|
|
else:
|
|
|
|
|
device_prefix = "cpu"
|
2017-07-27 10:53:51 -07:00
|
|
|
|
2018-10-09 15:44:49 -07:00
|
|
|
namescope = "{}_{}/".format(device_prefix, device.device_id)
|
2017-07-27 10:53:51 -07:00
|
|
|
for op in mnet.Proto().op:
|
|
|
|
|
if "RecurrentNetwork" in op.type:
|
|
|
|
|
raise("RecurrentNetwork conversion not yet supported")
|
|
|
|
|
for i, inputb in enumerate(op.input):
|
|
|
|
|
op.input[i] = namescope + inputb
|
|
|
|
|
for i, outputb in enumerate(op.output):
|
|
|
|
|
op.output[i] = namescope + outputb
|
|
|
|
|
for i, blob in enumerate(op.control_input):
|
|
|
|
|
op.control_input[i] = namescope + blob
|
|
|
|
|
op.device_option.CopyFrom(device)
|
|
|
|
|
for i, einp in enumerate(mnet.Proto().external_input):
|
|
|
|
|
mnet.Proto().external_input[i] = namescope + einp
|
|
|
|
|
for i, eoutp in enumerate(mnet.Proto().external_output):
|
|
|
|
|
mnet.Proto().external_output[i] = namescope + eoutp
|
|
|
|
|
return mnet
|
|
|
|
|
|
|
|
|
|
|
2017-11-19 23:28:40 -08:00
|
|
|
def _ForEachDevice(devices, f, device_type, device_prefix, scoped=False,
|
|
|
|
|
*args, **kwargs):
|
|
|
|
|
for device in devices:
|
|
|
|
|
device_opt = core.DeviceOption(device_type, device)
|
2017-05-15 18:02:16 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
|
|
|
|
if scoped:
|
2017-11-19 23:28:40 -08:00
|
|
|
with core.NameScope("{}_{}".format(device_prefix, device)):
|
|
|
|
|
f(device, *args, **kwargs)
|
2017-05-15 18:02:16 -07:00
|
|
|
else:
|
2017-11-19 23:28:40 -08:00
|
|
|
f(device, *args, **kwargs)
|
2016-10-07 13:08:53 -07:00
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
def _AddGradientOperators(devices, model, losses_by_gpu):
|
2017-03-13 16:23:55 -07:00
|
|
|
def create_grad(lossp):
|
|
|
|
|
return model.ConstantFill(lossp, str(lossp) + "_grad", value=1.0)
|
|
|
|
|
|
|
|
|
|
loss_grad = {}
|
|
|
|
|
# Explicitly need to create gradients on each GPU
|
|
|
|
|
for gpu_id in devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
device = core.DeviceOption(model._device_type, gpu_id)
|
2017-03-13 16:23:55 -07:00
|
|
|
with core.DeviceScope(device):
|
|
|
|
|
for l in losses_by_gpu[gpu_id]:
|
|
|
|
|
lg = create_grad(l)
|
|
|
|
|
loss_grad[str(l)] = str(lg)
|
|
|
|
|
|
|
|
|
|
model.AddGradientOperators(loss_grad)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def ExtractPredictorNet(model, inputs, outputs, device):
|
|
|
|
|
'''
|
|
|
|
|
Returns (net, params) that can be exported to be used as a prediction
|
|
|
|
|
net.
|
|
|
|
|
'''
|
|
|
|
|
master_device = model._devices[0]
|
2017-06-20 23:10:51 -07:00
|
|
|
prefix = "{}_{}/".format(model._device_prefix, master_device)
|
2017-03-13 16:23:55 -07:00
|
|
|
prefix_inputs = [prefix + str(b) for b in inputs]
|
|
|
|
|
prefix_outputs = [prefix + str(b) for b in outputs]
|
2017-06-05 15:33:33 -07:00
|
|
|
(predictor_net, export_blobs) = model_helper.ExtractPredictorNet(
|
2017-03-13 16:23:55 -07:00
|
|
|
net_proto=model.net.Proto(),
|
|
|
|
|
input_blobs=prefix_inputs,
|
|
|
|
|
output_blobs=prefix_outputs,
|
|
|
|
|
device=device,
|
|
|
|
|
renames={
|
|
|
|
|
a: b
|
|
|
|
|
for (a, b) in zip(prefix_inputs + prefix_outputs, inputs + outputs)
|
2017-06-05 15:33:33 -07:00
|
|
|
},
|
2017-03-13 16:23:55 -07:00
|
|
|
)
|
|
|
|
|
|
2017-06-05 15:33:33 -07:00
|
|
|
return (predictor_net, export_blobs)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
def GetCheckpointParams(model):
|
|
|
|
|
'''
|
|
|
|
|
Returns a set of blobs that are needed for a complete check point.
|
|
|
|
|
They are blobs for the first gpu and iteration blobs.
|
|
|
|
|
'''
|
|
|
|
|
(all_blobs, _) = _ComputeBlobsToSync(model)
|
2017-05-30 12:44:50 -07:00
|
|
|
first_gpu_blobs = {
|
2017-06-20 23:10:51 -07:00
|
|
|
b
|
|
|
|
|
for b in all_blobs
|
|
|
|
|
if str(b)
|
|
|
|
|
.startswith("{}_{}/".format(model._device_prefix, model._devices[0]))
|
|
|
|
|
}
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2017-05-30 12:44:50 -07:00
|
|
|
# Add iteration blobs that do not have namescope separately, since
|
|
|
|
|
# it is important to checkpoint iteration counter
|
|
|
|
|
iteration_blobs = set()
|
|
|
|
|
for op in model.net.Proto().op:
|
|
|
|
|
if op.type == 'Iter' or op.type == 'AtomicIter':
|
2017-06-20 23:10:51 -07:00
|
|
|
if not op.output[0].startswith("{}_".format(model._device_prefix)):
|
2017-05-30 12:44:50 -07:00
|
|
|
iteration_blobs.add(op.output[0])
|
|
|
|
|
|
|
|
|
|
return first_gpu_blobs.union(iteration_blobs)
|
|
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2018-10-26 20:46:26 -07:00
|
|
|
def FinalizeAfterCheckpoint(model, blobs=None, cpu_mode=False):
|
2017-05-19 12:46:18 -07:00
|
|
|
'''
|
|
|
|
|
This function should be called after loading parameters from a
|
|
|
|
|
checkpoint / initial parameters file.
|
|
|
|
|
'''
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
if not hasattr(model, "_checkpoint_net"):
|
2017-05-19 12:46:18 -07:00
|
|
|
if blobs is None:
|
|
|
|
|
(_, uniq_blob_names) = _ComputeBlobsToSync(model)
|
|
|
|
|
else:
|
2017-11-29 21:13:30 -08:00
|
|
|
uniq_blob_names = [stripBlobName(p) for p in blobs]
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Synchronize to the blob lookup map, as the provided
|
|
|
|
|
# blobs might have non-parameters, such as momemtum blobs.
|
|
|
|
|
log.info("Creating checkpoint synchronization net")
|
|
|
|
|
devices = model.GetDevices()
|
|
|
|
|
for name in uniq_blob_names:
|
|
|
|
|
if name not in model._device_grouped_blobs:
|
|
|
|
|
grouped = {
|
|
|
|
|
d:
|
2017-06-20 23:10:51 -07:00
|
|
|
core.BlobReference("{}_{}{}{}".format(
|
|
|
|
|
model._device_prefix,
|
2016-11-14 14:58:04 -08:00
|
|
|
d,
|
|
|
|
|
scope._NAMESCOPE_SEPARATOR,
|
|
|
|
|
name)
|
|
|
|
|
) for d in devices}
|
|
|
|
|
model._device_grouped_blobs[name] = grouped
|
|
|
|
|
|
|
|
|
|
model._checkpoint_net = core.Net("checkpoint_sync_net")
|
2018-10-26 20:46:26 -07:00
|
|
|
if not cpu_mode:
|
|
|
|
|
model._checkpoint_net.RunAllOnGPU()
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
checkpoint_init_net = None
|
2017-05-31 15:02:29 -07:00
|
|
|
if (model._rendezvous is not None and model._rendezvous['num_shards'] > 1):
|
2016-12-01 15:05:24 -08:00
|
|
|
checkpoint_init_net = core.Net("checkpoint_init_net")
|
2018-10-26 20:46:26 -07:00
|
|
|
if not cpu_mode:
|
|
|
|
|
checkpoint_init_net.RunAllOnGPU()
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
_SyncAllParams(
|
|
|
|
|
devices,
|
|
|
|
|
model,
|
|
|
|
|
checkpoint_init_net,
|
|
|
|
|
model._checkpoint_net,
|
|
|
|
|
model._rendezvous,
|
|
|
|
|
uniq_blob_names,
|
2017-06-28 12:36:15 -07:00
|
|
|
max_concurrent_distributed_ops=1
|
2017-06-27 19:32:37 -07:00
|
|
|
)
|
|
|
|
|
if (checkpoint_init_net):
|
|
|
|
|
workspace.RunNetOnce(checkpoint_init_net)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2016-12-01 15:05:24 -08:00
|
|
|
workspace.CreateNet(model._checkpoint_net)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Run the sync
|
|
|
|
|
log.info("Run checkpoint net")
|
2016-12-01 15:05:24 -08:00
|
|
|
workspace.RunNet(model._checkpoint_net.Proto().name)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
|
2017-07-21 16:22:21 -07:00
|
|
|
def GetLearningRateBlobNames(model):
|
|
|
|
|
'''
|
|
|
|
|
Returns a list of learning rates blob names used in the optimizer.
|
|
|
|
|
'''
|
|
|
|
|
if model._optimizer is not None:
|
2019-01-15 11:07:55 -08:00
|
|
|
if model._device_type == caffe2_pb2.CPU or model._device_type == caffe2_pb2.IDEEP:
|
2017-08-30 12:37:06 -07:00
|
|
|
return [model._optimizer.get_cpu_blob_name('lr')]
|
2018-11-29 13:58:11 -08:00
|
|
|
elif core.IsGPUDeviceType(model._device_type):
|
2017-10-12 17:17:29 -07:00
|
|
|
return [model._optimizer.get_gpu_blob_name('lr', gpu, '')
|
2017-07-21 16:22:21 -07:00
|
|
|
for gpu in model._devices]
|
|
|
|
|
else:
|
|
|
|
|
raise Exception(
|
|
|
|
|
"Unsupported device type : {}".format(model._device_type)
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
lr_blob_names = []
|
|
|
|
|
for op in model.net.Proto().op:
|
|
|
|
|
if op.type == "LearningRate":
|
|
|
|
|
lr_blob_names.append(op.output(0))
|
|
|
|
|
return lr_blob_names
|
|
|
|
|
|
|
|
|
|
|
2017-05-30 16:43:02 -07:00
|
|
|
def _Broadcast(devices, model, net, param, use_nccl=False):
|
2016-11-14 14:58:04 -08:00
|
|
|
# Copy params from gpu_0 to other
|
2017-06-20 23:10:51 -07:00
|
|
|
master_dev = devices[0]
|
2017-05-30 16:43:02 -07:00
|
|
|
|
|
|
|
|
if use_nccl:
|
|
|
|
|
if _IsGPUBlob(model, param):
|
2017-06-20 23:10:51 -07:00
|
|
|
master_device_opt = core.DeviceOption(model._device_type, master_dev)
|
2017-05-30 16:43:02 -07:00
|
|
|
with core.DeviceScope(master_device_opt):
|
2017-06-27 09:36:22 -07:00
|
|
|
# Note that the root is the root _rank_ and not the root
|
|
|
|
|
# _device_. Thus we always use root=0, regardless of the
|
|
|
|
|
# devices used.
|
2017-07-03 16:49:41 -07:00
|
|
|
net.NCCLBroadcast(
|
2017-11-28 10:33:44 -08:00
|
|
|
list(viewvalues(model._device_grouped_blobs[param])),
|
|
|
|
|
list(viewvalues(model._device_grouped_blobs[param])),
|
2017-06-27 09:36:22 -07:00
|
|
|
root=0,
|
2017-05-30 16:43:02 -07:00
|
|
|
)
|
|
|
|
|
return
|
|
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
for dev_idx in devices[1:]:
|
2017-03-09 13:41:36 -08:00
|
|
|
if _IsGPUBlob(model, param):
|
2018-11-29 13:58:11 -08:00
|
|
|
device_opt = core.DeviceOption(workspace.GpuDeviceType, dev_idx)
|
2017-03-09 13:41:36 -08:00
|
|
|
else:
|
2019-02-20 16:53:23 -08:00
|
|
|
device_opt = core.DeviceOption(caffe2_pb2.IDEEP, 0) if _IsIDEEPBlob(model, param) else \
|
|
|
|
|
core.DeviceOption(caffe2_pb2.CPU, 0)
|
2016-11-14 14:58:04 -08:00
|
|
|
with core.DeviceScope(device_opt):
|
|
|
|
|
net.Copy(
|
2017-06-20 23:10:51 -07:00
|
|
|
model._device_grouped_blobs[param][master_dev],
|
|
|
|
|
model._device_grouped_blobs[param][dev_idx]
|
2016-11-14 14:58:04 -08:00
|
|
|
)
|
2016-10-07 13:08:53 -07:00
|
|
|
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-05-15 18:02:16 -07:00
|
|
|
def _AllReduce(devices, model, net, param, use_nccl=False, control_input=None):
|
2017-06-29 16:52:01 -07:00
|
|
|
blobs_group = list(viewvalues(model._device_grouped_blobs[param]))
|
2017-06-20 23:10:51 -07:00
|
|
|
if model._device_type == caffe2_pb2.CUDA and use_nccl:
|
2017-09-15 16:05:58 -07:00
|
|
|
# TODO: for _shared_model, do only NCCLReduce
|
2017-05-15 18:02:16 -07:00
|
|
|
model.NCCLAllreduce(
|
|
|
|
|
blobs_group, blobs_group, control_input=control_input
|
|
|
|
|
)
|
|
|
|
|
return
|
2017-05-02 16:01:00 -07:00
|
|
|
|
2018-11-29 13:58:11 -08:00
|
|
|
if model._device_type == workspace.GpuDeviceType:
|
|
|
|
|
p2p_access_pattern = workspace.GetGpuPeerAccessPattern()
|
2017-06-20 23:10:51 -07:00
|
|
|
else:
|
|
|
|
|
p2p_access_pattern = None
|
2017-05-30 11:51:36 -07:00
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
def sumN(*dev_indices):
|
2017-05-30 11:51:36 -07:00
|
|
|
"""Create a Sum op for 2 or more blobs on different devices.
|
|
|
|
|
Saves the result on the first device.
|
|
|
|
|
|
|
|
|
|
Arguments:
|
2017-06-20 23:10:51 -07:00
|
|
|
dev_indices -- a list of device indices, which can be translated into
|
2017-05-30 11:51:36 -07:00
|
|
|
CUDA identifiers with model._devices
|
|
|
|
|
"""
|
2017-06-20 23:10:51 -07:00
|
|
|
devices = [model._devices[idx] for idx in dev_indices]
|
|
|
|
|
blobs = [blobs_group[idx] for idx in dev_indices]
|
|
|
|
|
device_opt = core.DeviceOption(model._device_type, devices[0])
|
2017-05-02 16:01:00 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
2018-10-12 10:46:01 -07:00
|
|
|
for i, peer in enumerate(devices):
|
|
|
|
|
if i == 0:
|
|
|
|
|
continue # Skip the first device
|
2019-03-18 23:06:03 -07:00
|
|
|
if p2p_access_pattern is not None and p2p_access_pattern.size and not p2p_access_pattern[
|
2018-10-12 10:46:01 -07:00
|
|
|
devices[0], peer
|
|
|
|
|
]:
|
|
|
|
|
# Copy from peer to d0
|
|
|
|
|
blobs[i] = model.Copy(
|
|
|
|
|
blobs[i],
|
|
|
|
|
'gpu_{}/{}_gpu{}_copy'.format(devices[0], param, peer)
|
|
|
|
|
)
|
2017-05-30 11:51:36 -07:00
|
|
|
net.Sum(blobs, [blobs[0]], name='dpm')
|
|
|
|
|
|
2017-09-06 23:54:20 -07:00
|
|
|
if len(devices) == 16:
|
|
|
|
|
# Special tree reduction for 16 gpus, TODO generalize like in muji.py
|
|
|
|
|
for j in range(8):
|
|
|
|
|
sumN(j * 2, j * 2 + 1)
|
|
|
|
|
for j in range(4):
|
|
|
|
|
sumN(j * 4, j * 4 + 2)
|
|
|
|
|
for j in range(2):
|
|
|
|
|
sumN(j * 8, j * 8 + 4)
|
|
|
|
|
sumN(0, 8)
|
|
|
|
|
elif len(devices) == 8:
|
2017-05-02 16:01:00 -07:00
|
|
|
for j in range(4):
|
2017-05-30 11:51:36 -07:00
|
|
|
sumN(j * 2, j * 2 + 1)
|
2017-05-02 16:01:00 -07:00
|
|
|
for j in range(2):
|
2017-05-30 11:51:36 -07:00
|
|
|
sumN(j * 4, j * 4 + 2)
|
2017-05-30 12:44:50 -07:00
|
|
|
sumN(0, 4)
|
2017-05-02 16:01:00 -07:00
|
|
|
elif len(devices) == 4:
|
2017-05-30 11:51:36 -07:00
|
|
|
sumN(0, 1)
|
|
|
|
|
sumN(2, 3)
|
|
|
|
|
sumN(0, 2)
|
2017-05-02 16:01:00 -07:00
|
|
|
else:
|
2017-05-30 11:51:36 -07:00
|
|
|
sumN(*range(len(devices)))
|
2017-09-15 16:05:58 -07:00
|
|
|
# TODO: for _shared_model, no need to broadcast
|
2017-05-30 11:51:36 -07:00
|
|
|
_Broadcast(devices, model, net, param)
|
2017-05-02 16:01:00 -07:00
|
|
|
|
|
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
def _SyncAllParams(
|
|
|
|
|
devices,
|
|
|
|
|
model,
|
|
|
|
|
init_net,
|
|
|
|
|
net,
|
|
|
|
|
rendezvous,
|
|
|
|
|
unique_param_names,
|
2017-06-28 12:36:15 -07:00
|
|
|
max_concurrent_distributed_ops=4
|
2017-06-27 19:32:37 -07:00
|
|
|
):
|
|
|
|
|
if rendezvous is None or rendezvous['num_shards'] <= 1:
|
|
|
|
|
_SyncAllParamsSingleHost(devices, model, net, unique_param_names)
|
|
|
|
|
else:
|
|
|
|
|
_SyncAllParamsDistributed(
|
|
|
|
|
devices,
|
|
|
|
|
model,
|
|
|
|
|
init_net,
|
|
|
|
|
net,
|
|
|
|
|
rendezvous,
|
|
|
|
|
unique_param_names,
|
2017-06-28 12:36:15 -07:00
|
|
|
max_concurrent_distributed_ops
|
2017-06-27 19:32:37 -07:00
|
|
|
)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
|
2017-09-12 10:20:22 -07:00
|
|
|
def AddBlobSync(model, blobs, net=None):
|
2017-10-30 22:21:33 -07:00
|
|
|
'''
|
|
|
|
|
Sync a blob across devices and hosts
|
|
|
|
|
'''
|
2017-09-12 10:20:22 -07:00
|
|
|
if len(blobs) == 0:
|
|
|
|
|
return
|
|
|
|
|
net = model.net if net is None else net
|
|
|
|
|
for b in blobs:
|
|
|
|
|
assert not b.startswith(model._device_prefix), \
|
|
|
|
|
"Provide unprefixed blob name: {}".format(b)
|
|
|
|
|
model._device_grouped_blobs[b] = {
|
|
|
|
|
d: core.BlobReference("{}_{}/{}".format(model._device_prefix, d, b))
|
|
|
|
|
for d in model._devices
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_SyncAllParams(
|
|
|
|
|
model._devices,
|
|
|
|
|
model,
|
|
|
|
|
model.param_init_net,
|
|
|
|
|
net,
|
|
|
|
|
model._rendezvous,
|
|
|
|
|
set(blobs))
|
|
|
|
|
|
|
|
|
|
|
2017-10-30 22:21:33 -07:00
|
|
|
def AddDistributedBlobSync(model, blobs):
|
|
|
|
|
'''
|
|
|
|
|
Sync blobs across machines (but not across devices)
|
|
|
|
|
'''
|
|
|
|
|
if model._rendezvous is None:
|
|
|
|
|
return
|
|
|
|
|
synth_name = "_".join([str(b) for b in blobs])
|
|
|
|
|
comm_world = _CreateOrCloneCommonWorld(
|
|
|
|
|
model.param_init_net,
|
|
|
|
|
"blob_sync_cw_" + synth_name,
|
|
|
|
|
rendezvous=model._rendezvous,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
model.net.Allreduce(
|
|
|
|
|
inputs=[comm_world] + blobs,
|
|
|
|
|
outputs=blobs,
|
|
|
|
|
engine=model._rendezvous['engine'],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
def _SyncAllParamsDistributed(
|
2016-11-22 12:40:12 -08:00
|
|
|
devices,
|
|
|
|
|
model,
|
2016-12-01 15:05:24 -08:00
|
|
|
init_net,
|
2016-11-22 12:40:12 -08:00
|
|
|
net,
|
|
|
|
|
rendezvous,
|
2017-06-27 19:32:37 -07:00
|
|
|
unique_param_names,
|
2017-06-28 12:36:15 -07:00
|
|
|
max_concurrent_distributed_ops
|
2016-11-22 12:40:12 -08:00
|
|
|
):
|
2017-05-31 15:02:29 -07:00
|
|
|
assert rendezvous['num_shards'] > 1
|
|
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
gpu_device_opt = core.DeviceOption(model._device_type, devices[0])
|
2017-05-19 12:46:18 -07:00
|
|
|
cpu_device_opt = core.DeviceOption(caffe2_pb2.CPU)
|
2019-01-15 11:07:55 -08:00
|
|
|
ideep_device_opt = core.DeviceOption(caffe2_pb2.IDEEP)
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2017-09-12 10:20:22 -07:00
|
|
|
if model._broadcast_context is None:
|
|
|
|
|
model._broadcast_context = CollectivesConcurrencyControl(
|
|
|
|
|
"broadcast",
|
|
|
|
|
max_concurrent_distributed_ops,
|
|
|
|
|
init_net,
|
|
|
|
|
rendezvous
|
|
|
|
|
)
|
|
|
|
|
context = model._broadcast_context
|
2017-06-28 12:36:15 -07:00
|
|
|
|
2017-06-27 19:32:37 -07:00
|
|
|
for param_name in sorted(unique_param_names):
|
|
|
|
|
master_param = model._device_grouped_blobs[param_name][devices[0]]
|
2017-08-07 14:17:07 -07:00
|
|
|
params_group = list(viewvalues(model._device_grouped_blobs[param_name]))
|
2016-11-22 12:40:12 -08:00
|
|
|
|
2017-06-28 12:36:15 -07:00
|
|
|
def broadcast(params):
|
|
|
|
|
comm_world, control_input = context.get_control_and_context(params)
|
2016-11-14 14:58:04 -08:00
|
|
|
net.Broadcast(
|
2017-06-27 19:32:37 -07:00
|
|
|
inputs=[comm_world] + params,
|
|
|
|
|
outputs=params,
|
|
|
|
|
name=param_name,
|
2016-11-22 12:40:12 -08:00
|
|
|
engine=rendezvous['engine'],
|
2017-06-28 12:36:15 -07:00
|
|
|
control_input=control_input
|
2016-10-11 22:45:06 -07:00
|
|
|
)
|
2017-03-14 22:32:07 -07:00
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
device_opt = gpu_device_opt if _IsGPUBlob(
|
|
|
|
|
model, param_name
|
2019-01-15 11:07:55 -08:00
|
|
|
) else ideep_device_opt if _IsIDEEPBlob(model, param_name) else cpu_device_opt
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2017-03-14 22:32:07 -07:00
|
|
|
if rendezvous['engine'] == 'GLOO':
|
|
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-28 12:36:15 -07:00
|
|
|
broadcast(params_group)
|
2017-03-14 22:32:07 -07:00
|
|
|
else:
|
|
|
|
|
# Copy between GPU and CPU
|
|
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-27 19:32:37 -07:00
|
|
|
param_cpu = net.CopyGPUToCPU(
|
|
|
|
|
master_param,
|
|
|
|
|
str(master_param) + "cpu"
|
|
|
|
|
)
|
2017-05-19 18:14:50 -07:00
|
|
|
with core.DeviceScope(cpu_device_opt):
|
2017-06-28 12:36:15 -07:00
|
|
|
broadcast([param_cpu])
|
2017-03-14 22:32:07 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
2017-06-27 19:32:37 -07:00
|
|
|
net.CopyCPUToGPU(param_cpu, master_param)
|
|
|
|
|
|
|
|
|
|
# Broadcast locally
|
|
|
|
|
_Broadcast(devices, model, net, param_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _SyncAllParamsSingleHost(devices, model, net, unique_param_names):
|
|
|
|
|
for param in unique_param_names:
|
|
|
|
|
_Broadcast(devices, model, net, param)
|
2016-10-07 13:08:53 -07:00
|
|
|
|
|
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
def _AllReduceBlobs(blob_names, devices, model, net, rendezvous, use_nccl,
|
|
|
|
|
max_concurrent_distributed_ops):
|
2017-05-31 15:02:29 -07:00
|
|
|
if rendezvous is None or rendezvous['num_shards'] <= 1:
|
2017-06-21 16:14:39 -07:00
|
|
|
_AllReduceBlobsSingleHost(
|
|
|
|
|
blob_names,
|
|
|
|
|
devices,
|
|
|
|
|
model,
|
|
|
|
|
net,
|
|
|
|
|
use_nccl
|
|
|
|
|
)
|
2016-11-14 14:58:04 -08:00
|
|
|
else:
|
2017-06-21 16:14:39 -07:00
|
|
|
_AllReduceBlobsDistributed(
|
|
|
|
|
blob_names,
|
2017-05-25 13:22:51 -07:00
|
|
|
devices,
|
|
|
|
|
model,
|
2017-06-21 16:14:39 -07:00
|
|
|
net,
|
2017-05-25 13:22:51 -07:00
|
|
|
rendezvous,
|
|
|
|
|
max_concurrent_distributed_ops,
|
|
|
|
|
)
|
2016-10-11 22:45:06 -07:00
|
|
|
|
|
|
|
|
|
2017-09-15 16:05:58 -07:00
|
|
|
def _PruneParametersForSharing(model):
|
|
|
|
|
assert model._shared_model
|
|
|
|
|
master_prefix = "{}_{}/".format(model._device_prefix, model._devices[0])
|
|
|
|
|
|
|
|
|
|
# Remove non-master parameters so that they will not receive parameter
|
|
|
|
|
# update operators.
|
|
|
|
|
model.params = model.GetParams(master_prefix)
|
|
|
|
|
paramset = set(model.params)
|
|
|
|
|
|
|
|
|
|
model.param_to_grad = {
|
|
|
|
|
p: model.param_to_grad[p]
|
|
|
|
|
for p in model.param_to_grad if p in paramset
|
|
|
|
|
}
|
|
|
|
|
model.weights = [w for w in model.weights if w in paramset]
|
|
|
|
|
model.biases = [w for w in model.biases if w in paramset]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _RemapParameterBlobsForSharedModel(model, all_params):
|
|
|
|
|
assert model._shared_model
|
|
|
|
|
master_prefix = "{}_{}/".format(
|
|
|
|
|
model._device_prefix, model._devices[0])
|
|
|
|
|
log.info("Remapping param blobs to master -> {}".format(master_prefix))
|
|
|
|
|
master_params = set(model.GetParams())
|
|
|
|
|
|
|
|
|
|
# Remove all but master params
|
|
|
|
|
def modify_ops(net):
|
|
|
|
|
ops = []
|
|
|
|
|
for op in net.Proto().op:
|
|
|
|
|
delete_op = False
|
|
|
|
|
# Delete ops that output non-master version of parameter
|
|
|
|
|
for outp in op.output:
|
|
|
|
|
if outp in all_params and outp not in master_params:
|
|
|
|
|
delete_op = True
|
|
|
|
|
log.debug("Delete b/c {}: {}".format(outp, str(op)))
|
|
|
|
|
break
|
|
|
|
|
if delete_op:
|
|
|
|
|
continue
|
|
|
|
|
# Remap inputs to point to the master param
|
|
|
|
|
for j, inp in enumerate(op.input):
|
|
|
|
|
if inp in all_params and inp not in master_params:
|
2017-11-29 21:13:30 -08:00
|
|
|
op.input[j] = master_prefix + stripBlobName(inp)
|
2017-09-15 16:05:58 -07:00
|
|
|
ops.append(op)
|
|
|
|
|
del net.Proto().op[:]
|
|
|
|
|
net.Proto().op.extend(ops)
|
|
|
|
|
|
|
|
|
|
modify_ops(model.param_init_net)
|
|
|
|
|
modify_ops(model.net)
|
|
|
|
|
|
|
|
|
|
|
2017-06-28 12:36:15 -07:00
|
|
|
class CollectivesConcurrencyControl(object):
|
|
|
|
|
"""
|
|
|
|
|
Creates common worlds (up to max_concurrent_context) and manage the
|
|
|
|
|
sequential execution of collectives that shares the same context with
|
|
|
|
|
cyclic control inputs.
|
|
|
|
|
"""
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
name,
|
|
|
|
|
max_concurrent_context,
|
|
|
|
|
param_init_net,
|
|
|
|
|
rendezvous
|
|
|
|
|
):
|
|
|
|
|
self.name = name
|
|
|
|
|
self.param_init_net = param_init_net
|
|
|
|
|
self.max_concurrent_context = max_concurrent_context
|
|
|
|
|
self.counter = 0
|
|
|
|
|
self.common_worlds = []
|
|
|
|
|
self.control_inputs = []
|
|
|
|
|
self.rendezvous = rendezvous
|
|
|
|
|
|
|
|
|
|
def get_control_and_context(self, control_output_blob):
|
|
|
|
|
common_world, control_input = [None, None]
|
|
|
|
|
current_slot = self.counter % self.max_concurrent_context
|
|
|
|
|
if len(self.common_worlds) < self.max_concurrent_context:
|
2017-09-06 13:18:06 -07:00
|
|
|
common_world = _CreateOrCloneCommonWorld(
|
|
|
|
|
self.param_init_net,
|
2017-06-28 12:36:15 -07:00
|
|
|
"{}_{}_cw".format(self.name, current_slot),
|
2017-09-06 13:18:06 -07:00
|
|
|
rendezvous=self.rendezvous,
|
2017-06-28 12:36:15 -07:00
|
|
|
)
|
|
|
|
|
self.common_worlds.append(common_world)
|
|
|
|
|
self.control_inputs.append(control_output_blob)
|
|
|
|
|
else:
|
|
|
|
|
common_world = self.common_worlds[current_slot]
|
|
|
|
|
control_input = self.control_inputs[current_slot]
|
|
|
|
|
self.control_inputs[current_slot] = control_output_blob
|
|
|
|
|
self.counter += 1
|
|
|
|
|
return common_world, control_input
|
|
|
|
|
|
|
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
def _AllReduceBlobsDistributed(
|
|
|
|
|
blob_names,
|
2016-11-22 12:40:12 -08:00
|
|
|
devices,
|
|
|
|
|
model,
|
2017-06-21 16:14:39 -07:00
|
|
|
net,
|
2016-11-22 12:40:12 -08:00
|
|
|
rendezvous,
|
2017-05-25 13:22:51 -07:00
|
|
|
max_concurrent_distributed_ops,
|
2016-11-22 12:40:12 -08:00
|
|
|
):
|
2016-11-14 14:58:04 -08:00
|
|
|
num_workers = model.net.Proto().num_workers
|
|
|
|
|
assert num_workers > 1, "Please specify more than 1 worker"
|
2016-11-22 12:40:12 -08:00
|
|
|
all_reduce_engine = rendezvous['engine']
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-06-30 09:05:07 -07:00
|
|
|
master_device_opt = core.DeviceOption(model._device_type, devices[0])
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
reducing_device_opt = master_device_opt
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-06-28 12:36:15 -07:00
|
|
|
context = CollectivesConcurrencyControl(
|
|
|
|
|
"allreduce",
|
|
|
|
|
max_concurrent_distributed_ops,
|
|
|
|
|
model.param_init_net,
|
|
|
|
|
rendezvous
|
|
|
|
|
)
|
2017-04-17 23:17:49 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
nccl_control_blob = None
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
for blob_name in blob_names:
|
|
|
|
|
master_blob = model._device_grouped_blobs[blob_name][devices[0]]
|
2017-06-29 16:52:01 -07:00
|
|
|
blobs_group = list(viewvalues(model._device_grouped_blobs[blob_name]))
|
2016-10-07 13:08:53 -07:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
assert master_blob in blobs_group
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
# Remark: NCCLReduce does not support in-place modifications
|
2017-06-21 16:14:39 -07:00
|
|
|
# so we need a temporary blob
|
|
|
|
|
reduced_blob = str(master_blob) + "_red"
|
2016-10-11 22:45:06 -07:00
|
|
|
|
2017-09-11 12:51:25 -07:00
|
|
|
def allreduce(blobs, **kwargs):
|
2016-11-14 14:58:04 -08:00
|
|
|
with core.DeviceScope(reducing_device_opt):
|
2017-06-28 12:36:15 -07:00
|
|
|
comm_world, control_input = \
|
|
|
|
|
context.get_control_and_context(blobs[0])
|
2017-06-21 16:14:39 -07:00
|
|
|
net.Allreduce(
|
|
|
|
|
inputs=[comm_world] + blobs,
|
|
|
|
|
outputs=blobs,
|
|
|
|
|
name=blob_name,
|
2017-03-14 22:32:07 -07:00
|
|
|
engine=all_reduce_engine,
|
|
|
|
|
control_input=control_input,
|
2017-09-11 12:51:25 -07:00
|
|
|
**kwargs
|
2016-11-14 14:58:04 -08:00
|
|
|
)
|
|
|
|
|
|
2017-03-14 22:32:07 -07:00
|
|
|
if rendezvous['engine'] == 'GLOO':
|
|
|
|
|
# With Gloo cross GPU and cross machine allreduce
|
2017-09-11 12:51:25 -07:00
|
|
|
# can be executed in a single operation.
|
|
|
|
|
# Try to use GPUDirect if transport == ibverbs.
|
|
|
|
|
allreduce(
|
|
|
|
|
blobs_group,
|
|
|
|
|
gpu_direct=(rendezvous.get("transport", None) == "ibverbs"),
|
|
|
|
|
)
|
2017-03-14 22:32:07 -07:00
|
|
|
else:
|
2017-06-21 16:14:39 -07:00
|
|
|
# Step 1: sum blobs from local GPUs to master GPU
|
2017-03-14 22:32:07 -07:00
|
|
|
with core.DeviceScope(master_device_opt):
|
2017-06-21 16:14:39 -07:00
|
|
|
model.ConstantFill(master_blob, reduced_blob, value=0.0)
|
2017-03-14 22:32:07 -07:00
|
|
|
|
|
|
|
|
# Temp fix since NCCLReduce does not work
|
2017-06-21 16:14:39 -07:00
|
|
|
net.NCCLAllreduce(
|
|
|
|
|
blobs_group,
|
|
|
|
|
blobs_group,
|
2017-03-14 22:32:07 -07:00
|
|
|
control_input=nccl_control_blob,
|
|
|
|
|
)
|
2017-06-21 16:14:39 -07:00
|
|
|
nccl_control_blob = blobs_group[0]
|
|
|
|
|
net.Copy(master_blob, reduced_blob)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2016-11-22 12:40:12 -08:00
|
|
|
# Step 2: allreduce between all hosts, between master GPUs
|
2017-06-28 12:36:15 -07:00
|
|
|
allreduce([reduced_blob])
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
with core.DeviceScope(master_device_opt):
|
2017-06-21 16:14:39 -07:00
|
|
|
net.Copy(reduced_blob, master_blob)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-03-14 22:32:07 -07:00
|
|
|
# Step 3: broadcast locally
|
2017-06-21 16:14:39 -07:00
|
|
|
_Broadcast(devices, model, net, blob_name)
|
2017-03-14 22:32:07 -07:00
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
def _AllReduceBlobsSingleHost(blob_names, devices, model, net, use_nccl):
|
|
|
|
|
"""Performs NCCL AllReduce to distribute blobs to all the GPUs."""
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
if len(devices) == 1:
|
|
|
|
|
return
|
|
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
# Now we need to Allreduce blobs on all the GPUs.
|
2016-11-14 14:58:04 -08:00
|
|
|
# Pick GPU #0 as a master GPU.
|
2017-06-20 23:10:51 -07:00
|
|
|
master_device_opt = core.DeviceOption(model._device_type, devices[0])
|
2016-11-14 14:58:04 -08:00
|
|
|
last_out = None
|
2017-05-24 22:10:04 -07:00
|
|
|
concatenated_idx = set()
|
2016-11-30 15:06:32 -08:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
for blob_name in blob_names:
|
|
|
|
|
# Group by blob_name for reduce.
|
2017-06-29 16:52:01 -07:00
|
|
|
blobs_group = list(viewvalues(model._device_grouped_blobs[blob_name]))
|
2018-01-24 13:10:56 -08:00
|
|
|
if len(blobs_group) == 1:
|
|
|
|
|
# Non-reducible
|
|
|
|
|
continue
|
2017-06-21 16:14:39 -07:00
|
|
|
assert len(blobs_group) == len(devices), \
|
2017-03-09 13:41:36 -08:00
|
|
|
"Each GPU from {}, should have a copy of {}.".format(
|
2017-06-21 16:14:39 -07:00
|
|
|
devices, blob_name)
|
2017-03-09 13:41:36 -08:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
if _IsGPUBlob(model, blob_name):
|
2017-03-09 13:41:36 -08:00
|
|
|
with core.DeviceScope(master_device_opt):
|
2017-06-21 16:14:39 -07:00
|
|
|
if not isinstance(blobs_group[0], core.GradientSlice):
|
2017-05-15 18:02:16 -07:00
|
|
|
_AllReduce(
|
2017-06-21 16:14:39 -07:00
|
|
|
devices, model, net, blob_name, use_nccl, last_out
|
2017-05-15 18:02:16 -07:00
|
|
|
)
|
|
|
|
|
# last_out is used to serialize the execution of nccls
|
2017-06-21 16:14:39 -07:00
|
|
|
last_out = blobs_group[0]
|
2017-04-13 17:15:51 -07:00
|
|
|
|
|
|
|
|
else:
|
|
|
|
|
# Sparse gradients: all-gather for indices and values
|
2017-06-20 23:10:51 -07:00
|
|
|
master_ns = "{}_{}".format(model._device_prefix, devices[0])
|
2017-05-24 22:10:04 -07:00
|
|
|
'''
|
|
|
|
|
Skip if we have already copied concatenated indices
|
|
|
|
|
to the indices of GradientSlice. This happens when two
|
|
|
|
|
or more grad blobs are gathered with the same indices
|
|
|
|
|
blob
|
|
|
|
|
'''
|
|
|
|
|
skip_idx_concat = False
|
2017-06-21 16:14:39 -07:00
|
|
|
for g in blobs_group:
|
2017-05-24 22:10:04 -07:00
|
|
|
if g.indices in concatenated_idx:
|
|
|
|
|
skip_idx_concat = True
|
|
|
|
|
|
|
|
|
|
if not skip_idx_concat:
|
2017-06-21 16:14:39 -07:00
|
|
|
grad_idx_concat, _ = net.Concat(
|
|
|
|
|
[g.indices for g in blobs_group],
|
|
|
|
|
["{}/{}_index_concat".format(master_ns, blob_name),
|
|
|
|
|
"{}/{}_index_splitinfo".format(master_ns, blob_name)],
|
2017-05-24 22:10:04 -07:00
|
|
|
axis=0,
|
|
|
|
|
name="note:data_parallel_model")
|
2017-06-21 16:14:39 -07:00
|
|
|
|
2017-06-29 16:52:01 -07:00
|
|
|
for gpu, g in viewitems(model._device_grouped_blobs[blob_name]):
|
2017-06-20 23:10:51 -07:00
|
|
|
device_opt = core.DeviceOption(model._device_type, gpu)
|
2017-05-24 22:10:04 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
|
|
|
|
model.Copy(grad_idx_concat, g.indices)
|
|
|
|
|
concatenated_idx.add(g.indices)
|
2017-04-13 17:15:51 -07:00
|
|
|
|
2017-06-21 16:14:39 -07:00
|
|
|
grad_val_concat, _ = net.Concat(
|
|
|
|
|
[g.values for g in blobs_group],
|
|
|
|
|
["{}/{}_val_concat".format(master_ns, blob_name),
|
|
|
|
|
"{}/{}_val_splitinfo".format(master_ns, blob_name)],
|
2017-04-13 17:15:51 -07:00
|
|
|
axis=0, name="note:data_parallel_model")
|
2017-06-21 16:14:39 -07:00
|
|
|
|
2017-06-29 16:52:01 -07:00
|
|
|
for gpu, g in viewitems(model._device_grouped_blobs[blob_name]):
|
2017-06-20 23:10:51 -07:00
|
|
|
device_opt = core.DeviceOption(model._device_type, gpu)
|
2017-04-13 17:15:51 -07:00
|
|
|
with core.DeviceScope(device_opt):
|
|
|
|
|
model.Copy(grad_val_concat, g.values)
|
|
|
|
|
|
2019-02-20 16:53:23 -08:00
|
|
|
elif _IsIDEEPBlob(model, blob_name):
|
|
|
|
|
assert not isinstance(blobs_group[0], core.GradientSlice), \
|
|
|
|
|
"Synchronizing gradient slices not supported"
|
|
|
|
|
with core.DeviceScope(core.DeviceOption(caffe2_pb2.IDEEP)):
|
|
|
|
|
net.Sum(blobs_group, [blobs_group[0]])
|
|
|
|
|
if not model._shared_model:
|
|
|
|
|
_Broadcast(devices, model, net, blob_name)
|
|
|
|
|
|
2017-03-09 13:41:36 -08:00
|
|
|
else:
|
2017-06-21 16:14:39 -07:00
|
|
|
assert not isinstance(blobs_group[0], core.GradientSlice), \
|
2017-03-09 13:41:36 -08:00
|
|
|
"Synchronizing gradient slices not supported"
|
|
|
|
|
with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)):
|
|
|
|
|
# Poor man's allreduce
|
2017-11-19 23:28:40 -08:00
|
|
|
net.Sum(blobs_group, [blobs_group[0]])
|
2017-09-15 16:05:58 -07:00
|
|
|
if not model._shared_model:
|
2017-11-19 23:28:40 -08:00
|
|
|
_Broadcast(devices, model, net, blob_name)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
|
2017-05-30 16:43:02 -07:00
|
|
|
def _BroadcastComputedParams(devices, model, rendezvous, use_nccl=False):
|
2016-12-06 10:08:21 -08:00
|
|
|
if rendezvous is None:
|
2017-05-30 16:43:02 -07:00
|
|
|
_BroadcastComputedParamsSingleHost(devices, model, use_nccl)
|
2016-12-06 10:08:21 -08:00
|
|
|
else:
|
2017-05-30 16:43:02 -07:00
|
|
|
_BroadcastComputedParamsDistributed(devices, model, rendezvous, use_nccl)
|
2016-12-06 10:08:21 -08:00
|
|
|
|
|
|
|
|
|
2016-12-16 07:51:04 -08:00
|
|
|
def _BroadcastComputedParamsDistributed(
|
2016-12-06 10:08:21 -08:00
|
|
|
devices,
|
|
|
|
|
model,
|
|
|
|
|
rendezvous,
|
2017-05-30 16:43:02 -07:00
|
|
|
use_nccl=False
|
2016-12-06 10:08:21 -08:00
|
|
|
):
|
2017-05-30 16:43:02 -07:00
|
|
|
_BroadcastComputedParamsSingleHost(devices, model, use_nccl)
|
2017-09-22 22:50:14 -07:00
|
|
|
log.warn("Distributed broadcast of computed params is not implemented yet")
|
2016-12-06 10:08:21 -08:00
|
|
|
|
|
|
|
|
|
2017-05-30 16:43:02 -07:00
|
|
|
def _BroadcastComputedParamsSingleHost(devices, model, use_nccl=False):
|
2016-12-06 10:08:21 -08:00
|
|
|
'''
|
|
|
|
|
Average computed params over all devices
|
|
|
|
|
'''
|
|
|
|
|
if len(devices) == 1:
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
for param_name in model._computed_param_names:
|
|
|
|
|
# Copy from master to others -- averaging would be perhaps better,
|
|
|
|
|
# but currently NCCLAllReduce is too prone to deadlock
|
2017-05-30 16:43:02 -07:00
|
|
|
_Broadcast(devices, model, model.net, param_name, use_nccl)
|
2016-12-06 10:08:21 -08:00
|
|
|
|
|
|
|
|
|
2016-11-14 14:58:04 -08:00
|
|
|
def _GetReverseOrderedGrads(model):
|
|
|
|
|
'''
|
|
|
|
|
Returns the gradients in reverse order (namespace stripped),
|
|
|
|
|
for the optimal synchronization order.
|
|
|
|
|
'''
|
|
|
|
|
return list(reversed(model._grad_names))
|
2016-10-07 13:08:53 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# A helper function to extract a parameter's name
|
2017-11-29 21:13:30 -08:00
|
|
|
def stripBlobName(param):
|
2017-03-17 05:15:38 -07:00
|
|
|
# Format is "a/b/c/d" -> "b/c/d"
|
2017-03-10 13:13:26 -08:00
|
|
|
if isinstance(param, core.GradientSlice):
|
2017-11-29 21:13:30 -08:00
|
|
|
return stripBlobName(param.indices) + ":" + stripBlobName(param.values)
|
2017-03-09 13:41:36 -08:00
|
|
|
else:
|
2017-03-10 13:13:26 -08:00
|
|
|
name = str(param)
|
2017-03-09 13:41:36 -08:00
|
|
|
return name[name.index(scope._NAMESCOPE_SEPARATOR) + 1:]
|
2016-10-11 22:45:06 -07:00
|
|
|
|
|
|
|
|
|
2016-11-23 21:49:59 -08:00
|
|
|
def _AnalyzeOperators(model):
|
|
|
|
|
'''
|
|
|
|
|
Look at all the operators and check that they do not cross device scopes
|
|
|
|
|
'''
|
|
|
|
|
for op in model.Proto().op:
|
2017-04-13 17:15:51 -07:00
|
|
|
if "NCCL" in op.type or "Copy" in op.type or "Concat" in op.type:
|
2016-11-23 21:49:59 -08:00
|
|
|
continue
|
2017-05-02 16:01:00 -07:00
|
|
|
if "Sum" == op.type and op.name == "dpm":
|
|
|
|
|
continue
|
2017-03-14 22:32:07 -07:00
|
|
|
if "Allreduce" in op.type and "GLOO" in op.engine:
|
|
|
|
|
continue
|
|
|
|
|
|
2016-11-23 21:49:59 -08:00
|
|
|
op_dev = op.device_option
|
2018-10-09 15:44:49 -07:00
|
|
|
op_gpu = op_dev.device_id
|
2017-01-13 18:51:14 -08:00
|
|
|
|
|
|
|
|
# This avoids failing on operators that are only for CPU
|
2018-11-29 13:58:11 -08:00
|
|
|
if not core.IsGPUDeviceType(op_dev.device_type):
|
2017-01-13 18:51:14 -08:00
|
|
|
continue
|
|
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
namescope = "{}_{}/".format(model._device_prefix, op_gpu)
|
2016-11-23 21:49:59 -08:00
|
|
|
for inp in list(op.input) + list(op.output):
|
2017-06-20 23:10:51 -07:00
|
|
|
if inp.startswith("{}_".format(model._device_prefix)
|
|
|
|
|
) and not inp.startswith(namescope):
|
2016-11-23 21:49:59 -08:00
|
|
|
raise Exception(
|
|
|
|
|
"Blob {} of op {}, should have namescope {}. Op: {}".format(
|
2017-06-20 23:10:51 -07:00
|
|
|
inp,
|
|
|
|
|
op.type,
|
|
|
|
|
"{}_{}/".format(model._device_prefix, op_gpu),
|
|
|
|
|
str(op),
|
|
|
|
|
)
|
|
|
|
|
)
|
2016-11-23 21:49:59 -08:00
|
|
|
|
|
|
|
|
|
2017-03-09 13:41:36 -08:00
|
|
|
def _InferBlobDevice(model):
|
|
|
|
|
'''
|
|
|
|
|
Assign blob to device option based on the operator outputing it
|
|
|
|
|
'''
|
|
|
|
|
mapping = {}
|
2017-03-14 15:43:42 -07:00
|
|
|
|
|
|
|
|
def map_ops(proto):
|
|
|
|
|
for op in proto.op:
|
2017-05-19 12:46:18 -07:00
|
|
|
device_option = op.device_option
|
|
|
|
|
if op.type == "Iter":
|
|
|
|
|
# Hack for Iters which have blob in CPU context
|
|
|
|
|
device_option = caffe2_pb2.DeviceOption()
|
|
|
|
|
device_option.device_type = caffe2_pb2.CPU
|
2017-03-14 15:43:42 -07:00
|
|
|
for b in list(op.input) + list(op.output):
|
2017-05-19 12:46:18 -07:00
|
|
|
if b not in mapping:
|
|
|
|
|
mapping[b] = device_option
|
2017-03-14 15:43:42 -07:00
|
|
|
if op.type.startswith('RecurrentNetwork'):
|
|
|
|
|
step_args = [a for a in op.arg if a.name.endswith("step_net")]
|
|
|
|
|
for step_arg in step_args:
|
2017-10-10 21:53:49 -07:00
|
|
|
map_ops(step_arg.n)
|
2017-08-15 11:54:43 -07:00
|
|
|
map_ops(model.param_init_net.Proto())
|
2017-03-14 15:43:42 -07:00
|
|
|
map_ops(model.net.Proto())
|
2017-03-09 13:41:36 -08:00
|
|
|
model._blob_to_device = mapping
|
|
|
|
|
|
2019-01-15 11:07:55 -08:00
|
|
|
def _IsIDEEPBlob(model, blob_name):
|
|
|
|
|
if blob_name in model._blob_to_device:
|
|
|
|
|
return model._blob_to_device[blob_name].device_type == caffe2_pb2.IDEEP
|
|
|
|
|
else:
|
|
|
|
|
blob_name = "{}_{}/{}".format(
|
|
|
|
|
model._device_prefix, model._devices[0], blob_name
|
|
|
|
|
)
|
|
|
|
|
if blob_name not in model._blob_to_device:
|
|
|
|
|
return model._device_type == caffe2_pb2.IDEEP
|
|
|
|
|
return model._blob_to_device[blob_name].device_type == caffe2_pb2.IDEEP
|
|
|
|
|
|
2017-03-09 13:41:36 -08:00
|
|
|
def _IsGPUBlob(model, blob_name):
|
|
|
|
|
if blob_name in model._blob_to_device:
|
2018-11-29 13:58:11 -08:00
|
|
|
return core.IsGPUDeviceType(model._blob_to_device[blob_name].device_type)
|
2017-03-09 13:41:36 -08:00
|
|
|
else:
|
2017-06-20 23:10:51 -07:00
|
|
|
blob_name = "{}_{}/{}".format(
|
|
|
|
|
model._device_prefix, model._devices[0], blob_name
|
|
|
|
|
)
|
2017-03-17 05:15:38 -07:00
|
|
|
if blob_name not in model._blob_to_device:
|
2018-11-29 13:58:11 -08:00
|
|
|
return core.IsGPUDeviceType(model._device_type)
|
|
|
|
|
return core.IsGPUDeviceType(model._blob_to_device[blob_name].device_type)
|
2017-03-09 13:41:36 -08:00
|
|
|
|
|
|
|
|
|
2017-06-20 23:10:51 -07:00
|
|
|
def _GroupByDevice(model, devices, params, non_data_params):
|
2016-11-14 14:58:04 -08:00
|
|
|
'''
|
|
|
|
|
Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}.
|
|
|
|
|
Returns ordered dictionary, ensuring the original order.
|
|
|
|
|
'''
|
|
|
|
|
grouped = OrderedDict()
|
2017-03-09 13:41:36 -08:00
|
|
|
# Only consider params that were created to be "data parallel"
|
|
|
|
|
params = params[len(non_data_params):]
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2018-01-24 13:10:56 -08:00
|
|
|
for _i, p in enumerate(params):
|
2017-03-09 13:41:36 -08:00
|
|
|
assert isinstance(p, core.BlobReference) or \
|
|
|
|
|
isinstance(p, core.GradientSlice), \
|
|
|
|
|
"Param {} is not BlobReference or GradientSlice".format(p)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
2017-11-29 21:13:30 -08:00
|
|
|
name = stripBlobName(p)
|
2018-01-24 13:10:56 -08:00
|
|
|
gpuid = None
|
2017-03-09 13:41:36 -08:00
|
|
|
|
|
|
|
|
if isinstance(p, core.BlobReference):
|
2018-01-24 13:10:56 -08:00
|
|
|
gpuid = int(p.GetNameScope().split("_")[1].split("/")[0])
|
2017-06-20 23:10:51 -07:00
|
|
|
assert "{}_{}/".format(model._device_prefix, gpuid) in p.GetNameScope(),\
|
|
|
|
|
"Param {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
|
2017-03-09 13:41:36 -08:00
|
|
|
else:
|
2018-01-24 13:10:56 -08:00
|
|
|
gpuid = int(p.indices.GetNameScope().split("_")[1].split("/")[0])
|
2017-06-20 23:10:51 -07:00
|
|
|
assert "{}_{}/".format(model._device_prefix, gpuid) in p.indices.GetNameScope(),\
|
|
|
|
|
"Indices {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
|
|
|
|
|
assert "{}_{}/".format(model._device_prefix, gpuid) in p.values.GetNameScope(),\
|
|
|
|
|
"Values {} expected to have namescope '{}_{}'".format(str(p), model._device_prefix, gpuid)
|
2016-11-14 14:58:04 -08:00
|
|
|
|
|
|
|
|
if name not in grouped:
|
|
|
|
|
grouped[name] = {}
|
|
|
|
|
grouped[name][gpuid] = p
|
|
|
|
|
|
|
|
|
|
return grouped
|
2017-01-09 19:39:09 -08:00
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2017-04-12 09:22:23 -07:00
|
|
|
def _ValidateParams(params):
|
|
|
|
|
set_params = set(params)
|
|
|
|
|
if len(params) > len(set_params):
|
|
|
|
|
dupes = []
|
|
|
|
|
sp = sorted(params)
|
|
|
|
|
for j, p in enumerate(sp):
|
2017-07-07 12:58:49 -07:00
|
|
|
if j > 0 and sp[j - 1] == p:
|
2017-04-12 09:22:23 -07:00
|
|
|
dupes.append(p)
|
|
|
|
|
|
|
|
|
|
assert len(params) == len(set_params), \
|
|
|
|
|
"Duplicate entries in params: {}".format(dupes)
|
|
|
|
|
|
|
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
def _ComputeBlobsToSync(model):
|
|
|
|
|
'''
|
|
|
|
|
We sync all blobs that are generated by param init net and
|
2017-09-15 16:05:58 -07:00
|
|
|
are 'data parallel', i.e assigned to a device
|
2017-05-19 12:46:18 -07:00
|
|
|
'''
|
|
|
|
|
sync_names = set()
|
2017-09-15 16:05:58 -07:00
|
|
|
|
|
|
|
|
# We don't sync params if the model is shared
|
|
|
|
|
if model._shared_model:
|
|
|
|
|
blobs_to_sync = [str(p) for p in model.GetComputedParams('')]
|
2017-11-29 21:13:30 -08:00
|
|
|
sync_names = [stripBlobName(p) for p in blobs_to_sync]
|
2017-09-15 16:05:58 -07:00
|
|
|
else:
|
|
|
|
|
blobs_to_sync = []
|
|
|
|
|
|
|
|
|
|
for op in model.param_init_net.Proto().op:
|
|
|
|
|
dp_outputs = [
|
|
|
|
|
o for o in op.output
|
|
|
|
|
if o.startswith("{}_".format(model._device_prefix))
|
|
|
|
|
]
|
2017-11-29 21:13:30 -08:00
|
|
|
sync_names.update([stripBlobName(o) for o in dp_outputs])
|
2017-09-15 16:05:58 -07:00
|
|
|
blobs_to_sync.extend(dp_outputs)
|
|
|
|
|
|
|
|
|
|
# Sanity check
|
|
|
|
|
diff = set(model._param_names) - sync_names
|
|
|
|
|
assert diff == set(), \
|
|
|
|
|
"Some params not instantiated in param init net: {}".format(diff)
|
2017-05-19 12:46:18 -07:00
|
|
|
|
2017-05-20 09:04:37 -07:00
|
|
|
# Remove duplicates and sort
|
2017-09-06 23:54:20 -07:00
|
|
|
prefixlen = len(model._device_prefix) + 1
|
|
|
|
|
|
|
|
|
|
def extract_sort_key(b):
|
|
|
|
|
# Sort first based on device id, and then by whole string
|
|
|
|
|
deviceid = int(b[prefixlen:b.index(scope._NAMESCOPE_SEPARATOR)])
|
|
|
|
|
return (deviceid, b)
|
|
|
|
|
|
|
|
|
|
blobs_to_sync = sorted(
|
|
|
|
|
list(set(blobs_to_sync)),
|
|
|
|
|
key=extract_sort_key)
|
2017-05-20 09:04:37 -07:00
|
|
|
|
2017-05-19 12:46:18 -07:00
|
|
|
blobs_to_sync = [core.BlobReference(b) for b in blobs_to_sync]
|
|
|
|
|
return (blobs_to_sync, sync_names)
|
|
|
|
|
|
|
|
|
|
|
2017-05-26 11:25:46 -07:00
|
|
|
def _OptimizeGradientMemorySimple(model, losses_by_gpu, devices):
|
2017-04-25 14:03:33 -07:00
|
|
|
log.warning("------- DEPRECATED API, please use " +
|
|
|
|
|
"data_parallel_model.OptimizeGradientMemory() ----- ")
|
2017-01-09 19:39:09 -08:00
|
|
|
for device in devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
namescope = "{}_{}/".format(model._device_prefix, device)
|
2017-01-09 19:39:09 -08:00
|
|
|
model.net._net = memonger.share_grad_blobs(
|
|
|
|
|
model.net,
|
|
|
|
|
losses_by_gpu[device],
|
2017-06-29 16:52:01 -07:00
|
|
|
set(viewvalues(model.param_to_grad)),
|
2017-01-09 19:39:09 -08:00
|
|
|
namescope,
|
2017-04-25 14:03:33 -07:00
|
|
|
share_activations=False,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2017-09-20 12:34:25 -07:00
|
|
|
def _AddDynamicMemoryOptimization(model, blobs_to_keep, devices):
|
|
|
|
|
blobs_to_keep_all_devices = set()
|
|
|
|
|
if blobs_to_keep is not None:
|
|
|
|
|
for device in devices:
|
|
|
|
|
for blob_name in blobs_to_keep:
|
|
|
|
|
blobs_to_keep_all_devices.add(
|
|
|
|
|
"{}_{}/{}".format(model._device_prefix, device, blob_name)
|
|
|
|
|
)
|
2017-11-13 11:28:53 -08:00
|
|
|
|
|
|
|
|
if model._rendezvous is not None:
|
|
|
|
|
# GLOO operators expect the tensor addresses to remain same over
|
|
|
|
|
# iterations so we need to remove param grads from the dynamic memory
|
|
|
|
|
# management.
|
|
|
|
|
blobs_to_keep_all_devices.update(
|
|
|
|
|
[str(b) for b in viewvalues(model.param_to_grad)]
|
|
|
|
|
)
|
|
|
|
|
|
2017-09-20 12:34:25 -07:00
|
|
|
model.net._net = memonger.release_blobs_when_used(
|
|
|
|
|
model.net.Proto(),
|
|
|
|
|
blobs_to_keep_all_devices
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2017-04-25 14:03:33 -07:00
|
|
|
def OptimizeGradientMemory(model,
|
|
|
|
|
input_shapes,
|
|
|
|
|
excluded_blobs,
|
|
|
|
|
recycle_activations):
|
|
|
|
|
"""
|
|
|
|
|
Optimize memory usage of the backward pass by recycling blobs for gradient
|
|
|
|
|
inputs that have been 'used'.
|
|
|
|
|
input_shapes: dict of blob name to shape for the inputs of the model.
|
|
|
|
|
Pass empty dictionary if not known.
|
|
|
|
|
excluded_blobs: list of blobs that cannot be recycled. These are blobs
|
|
|
|
|
that you will access externally.
|
|
|
|
|
recycle_activations: whether to also recycle forward pass activations
|
|
|
|
|
"""
|
2017-08-17 13:27:49 -07:00
|
|
|
if input_shapes is not None:
|
|
|
|
|
input_shapes_all_devices = {}
|
|
|
|
|
for b, shp in viewitems(input_shapes):
|
|
|
|
|
for d in model._devices:
|
|
|
|
|
input_shapes_all_devices["{}_{}/{}".
|
|
|
|
|
format(model._device_prefix, d, b)] = shp
|
|
|
|
|
|
|
|
|
|
(shapes, types) = workspace.InferShapesAndTypes(
|
|
|
|
|
[model.param_init_net, model.net],
|
|
|
|
|
input_shapes_all_devices,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
shapes = None
|
2017-04-25 14:03:33 -07:00
|
|
|
|
|
|
|
|
for device in model._devices:
|
2017-06-20 23:10:51 -07:00
|
|
|
namescope = "{}_{}/".format(model._device_prefix, device)
|
2017-06-29 16:52:01 -07:00
|
|
|
excluded_blobs_by_device = set(namescope + b for b in excluded_blobs)
|
2017-04-25 14:03:33 -07:00
|
|
|
model.net._net = memonger.share_grad_blobs(
|
|
|
|
|
model.net,
|
|
|
|
|
model._losses_by_gpu[device],
|
2017-06-29 16:52:01 -07:00
|
|
|
set(viewvalues(model.param_to_grad)),
|
2017-04-25 14:03:33 -07:00
|
|
|
namescope,
|
|
|
|
|
dont_share_blobs=excluded_blobs_by_device,
|
|
|
|
|
share_activations=recycle_activations,
|
|
|
|
|
blob_shapes=shapes,
|
2017-01-09 19:39:09 -08:00
|
|
|
)
|
2017-07-06 09:04:29 -07:00
|
|
|
|
|
|
|
|
|
2017-09-06 13:18:06 -07:00
|
|
|
def _CreateOrCloneCommonWorld(
|
|
|
|
|
net,
|
|
|
|
|
common_world_blob,
|
|
|
|
|
rendezvous,
|
|
|
|
|
name=None,
|
2017-09-12 12:59:34 -07:00
|
|
|
timeout_sec=None):
|
|
|
|
|
|
|
|
|
|
if timeout_sec is None:
|
|
|
|
|
timeout_sec = _DEFAULT_TIMEOUT_SEC
|
|
|
|
|
|
2017-09-06 13:18:06 -07:00
|
|
|
timeout_ms = timeout_sec * 1000
|
|
|
|
|
|
|
|
|
|
# Check if there is an existing CreateCommonWorld
|
|
|
|
|
# with the same timeout we're looking for. If so,
|
|
|
|
|
# we can clone it instead of creating a new one.
|
|
|
|
|
existing = None
|
|
|
|
|
for op in net.Proto().op:
|
|
|
|
|
if op.type != "CreateCommonWorld":
|
|
|
|
|
continue
|
2017-07-26 22:21:35 -07:00
|
|
|
|
2017-09-06 13:18:06 -07:00
|
|
|
# Find common world timeout
|
|
|
|
|
op_timeout_ms = -1
|
|
|
|
|
for arg in op.arg:
|
|
|
|
|
if arg.name == 'timeout_ms':
|
|
|
|
|
op_timeout_ms = arg.i
|
|
|
|
|
break
|
|
|
|
|
if op_timeout_ms != timeout_ms:
|
|
|
|
|
continue
|
2017-07-26 22:21:35 -07:00
|
|
|
|
2017-09-06 13:18:06 -07:00
|
|
|
# This common world was created with the same timeout we're
|
|
|
|
|
# looking for, so we can clone it
|
|
|
|
|
existing = op.output[0]
|
|
|
|
|
break
|
|
|
|
|
|
|
|
|
|
if name is None:
|
|
|
|
|
name = "{}_op".format(common_world_blob)
|
|
|
|
|
|
|
|
|
|
if existing is not None:
|
|
|
|
|
comm_world = net.CloneCommonWorld(
|
|
|
|
|
[existing],
|
|
|
|
|
common_world_blob,
|
|
|
|
|
name=name,
|
|
|
|
|
engine=rendezvous['engine'],
|
|
|
|
|
)
|
|
|
|
|
else:
|
2017-09-08 10:42:08 -07:00
|
|
|
kwargs=dict()
|
|
|
|
|
if 'transport' in rendezvous:
|
|
|
|
|
kwargs['transport'] = rendezvous['transport']
|
|
|
|
|
if 'interface' in rendezvous:
|
|
|
|
|
kwargs['interface'] = rendezvous['interface']
|
2017-09-08 17:13:38 -07:00
|
|
|
if 'mpi_rendezvous' in rendezvous:
|
|
|
|
|
kwargs['mpi_rendezvous'] = rendezvous['mpi_rendezvous']
|
2017-09-06 13:18:06 -07:00
|
|
|
comm_world = net.CreateCommonWorld(
|
2017-09-08 17:13:38 -07:00
|
|
|
rendezvous['kv_handler'] or [],
|
2017-09-06 13:18:06 -07:00
|
|
|
common_world_blob,
|
|
|
|
|
name=name,
|
|
|
|
|
size=rendezvous['num_shards'],
|
|
|
|
|
rank=rendezvous['shard_id'],
|
|
|
|
|
engine=rendezvous['engine'],
|
|
|
|
|
timeout_ms=timeout_ms,
|
2017-09-08 10:42:08 -07:00
|
|
|
**kwargs
|
2017-09-06 13:18:06 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return comm_world
|
2017-07-13 13:00:51 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _RunComparison(model, blob_name, device=None):
|
|
|
|
|
if device is None:
|
|
|
|
|
device = model._blob_to_device[blob_name]
|
|
|
|
|
with core.DeviceScope(device):
|
|
|
|
|
rendezvous = model._rendezvous
|
|
|
|
|
if rendezvous is None or rendezvous['num_shards'] == 1:
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
test_data_arr = np.zeros(rendezvous['num_shards']).astype(np.float32)
|
|
|
|
|
test_data_arr[rendezvous['shard_id']] = 1
|
|
|
|
|
workspace.FeedBlob("compare_arr", test_data_arr)
|
|
|
|
|
|
|
|
|
|
comparison_net = core.Net("allcompare_net")
|
|
|
|
|
|
2017-09-08 17:13:38 -07:00
|
|
|
kwargs=dict()
|
|
|
|
|
if 'mpi_rendezvous' in rendezvous:
|
|
|
|
|
kwargs['mpi_rendezvous'] = rendezvous['mpi_rendezvous']
|
2017-07-13 13:00:51 -07:00
|
|
|
comm_world = comparison_net.CreateCommonWorld(
|
2017-09-08 17:13:38 -07:00
|
|
|
rendezvous['kv_handler'] or [],
|
2017-07-13 13:00:51 -07:00
|
|
|
"initial_sync",
|
|
|
|
|
name=model.net.Proto().name + ".cw_master_select",
|
|
|
|
|
size=rendezvous['num_shards'],
|
|
|
|
|
rank=rendezvous['shard_id'],
|
|
|
|
|
engine=rendezvous['engine'],
|
2017-09-08 17:13:38 -07:00
|
|
|
**kwargs
|
2017-07-13 13:00:51 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
blob_name_checksum = blob_name + "_checksum"
|
|
|
|
|
comparison_net.SumSqrElements(
|
|
|
|
|
[blob_name], [blob_name_checksum], average=False
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
blob_name_gather = blob_name + "_gather"
|
|
|
|
|
comparison_net.Mul(
|
|
|
|
|
inputs=["compare_arr", blob_name_checksum],
|
|
|
|
|
outputs=blob_name_gather,
|
|
|
|
|
broadcast=1
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
comparison_net.Allreduce(
|
|
|
|
|
inputs=[comm_world, blob_name_gather],
|
|
|
|
|
outputs=[blob_name_gather],
|
|
|
|
|
engine=rendezvous['engine'],
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
workspace.RunNetOnce(comparison_net)
|
|
|
|
|
gather_arr = workspace.FetchBlob(blob_name_gather)
|
|
|
|
|
|
|
|
|
|
baseline = gather_arr[0]
|
|
|
|
|
for i in range(rendezvous['num_shards']):
|
|
|
|
|
assert gather_arr[i] == baseline, \
|
|
|
|
|
"allcompare failed on shard {}.".format(rendezvous['shard_id'])
|
|
|
|
|
|
|
|
|
|
return True
|
2018-01-24 13:10:56 -08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _InterleaveOps(model):
|
|
|
|
|
'''
|
|
|
|
|
Data Parallel Model creates a net with ops in one device grouped together.
|
|
|
|
|
This will interleave the ops so that each op for each device is next
|
|
|
|
|
to each other in the net. Kind of like combining decks of cards. This
|
|
|
|
|
ensures that progress is made along the critical path roughly concurrently
|
|
|
|
|
for each device, which is important due to the extra intra-node
|
|
|
|
|
synchronization required for multi-device batch normalization.
|
|
|
|
|
'''
|
|
|
|
|
orig_ops = list(model.net.Proto().op)
|
|
|
|
|
num_devices = len(model._devices)
|
|
|
|
|
num_ops_per_dev = len(orig_ops) // num_devices
|
|
|
|
|
assert num_devices * num_ops_per_dev == len(orig_ops), \
|
|
|
|
|
'Number of ops per device in original net is not uniform'
|
|
|
|
|
new_ops = []
|
|
|
|
|
ops = {d: [] for d in range(num_devices)}
|
|
|
|
|
for op in orig_ops:
|
2018-10-09 15:44:49 -07:00
|
|
|
ops[op.device_option.device_id].append(op)
|
2018-01-24 13:10:56 -08:00
|
|
|
|
|
|
|
|
for j in range(num_ops_per_dev):
|
|
|
|
|
tp = None
|
|
|
|
|
for d in model._devices:
|
|
|
|
|
if tp is None:
|
|
|
|
|
tp = ops[d][j].type
|
|
|
|
|
new_ops.append(ops[d][j])
|
|
|
|
|
# Sanity
|
|
|
|
|
assert ops[d][j].type == tp, \
|
|
|
|
|
"Type mismatch {} / {}".format(tp, ops[d][j].type)
|
|
|
|
|
|
|
|
|
|
del model.net.Proto().op[:]
|
|
|
|
|
model.net.Proto().op.extend(new_ops)
|
|
|
|
|
|
|
|
|
|
|
2018-10-18 11:19:28 -07:00
|
|
|
def _CPUInterDeviceBatchNormalization(model):
|
2018-01-24 13:10:56 -08:00
|
|
|
orig_ops = list(model.net.Proto().op)
|
|
|
|
|
new_ops = []
|
|
|
|
|
num_devices = len(model._devices)
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
injected_ops = []
|
|
|
|
|
|
|
|
|
|
spatial_bn_phase = False
|
|
|
|
|
sums_blobs = []
|
|
|
|
|
sumsq_blobs = []
|
|
|
|
|
name = []
|
|
|
|
|
input_blob_name = None
|
|
|
|
|
|
|
|
|
|
spatial_bn_gradient_phase = False
|
|
|
|
|
scale_grad_blobs = []
|
|
|
|
|
bias_grad_blobs = []
|
|
|
|
|
|
2018-10-18 11:19:28 -07:00
|
|
|
def _cpuReduce(param, input_blobs, destination_blobs):
|
|
|
|
|
"""
|
|
|
|
|
Reduce results from multiple cpus and distributes the results back
|
|
|
|
|
to each device. This is done by copying values to cpu_0 and summing
|
|
|
|
|
them. The cpu_0 result is then copied back to each of the devices.
|
|
|
|
|
|
|
|
|
|
param: the name of the data (blobs) to reduce
|
|
|
|
|
input_blobs: the list of blobs to reduce
|
|
|
|
|
destination_blobs: list of blobs to copy the result to
|
|
|
|
|
"""
|
|
|
|
|
added_ops = []
|
|
|
|
|
result_blob = "cpu_0/" + param + "_combined"
|
|
|
|
|
added_ops.append(core.CreateOperator("Sum", input_blobs, result_blob))
|
|
|
|
|
for blob in destination_blobs:
|
|
|
|
|
added_ops.append(core.CreateOperator("Copy", result_blob, blob))
|
|
|
|
|
return added_ops
|
|
|
|
|
|
2018-01-24 13:10:56 -08:00
|
|
|
for op in orig_ops:
|
|
|
|
|
if op.type != 'SpatialBN' and op.type != 'SpatialBNGradient':
|
|
|
|
|
if spatial_bn_phase:
|
|
|
|
|
new_ops.extend(injected_ops)
|
|
|
|
|
new_ops.append(
|
|
|
|
|
core.CreateOperator("Sum",
|
|
|
|
|
sums_blobs,
|
|
|
|
|
input_blob_name + "_sums_combined"))
|
|
|
|
|
new_ops.append(
|
|
|
|
|
core.CreateOperator("Sum",
|
|
|
|
|
sumsq_blobs,
|
|
|
|
|
input_blob_name + "_sumsq_combined"))
|
|
|
|
|
new_ops.extend(batch_norm_ops)
|
|
|
|
|
injected_ops = []
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
sums_blobs = []
|
|
|
|
|
sumsq_blobs = []
|
|
|
|
|
spatial_bn_phase = False
|
|
|
|
|
input_blob_name = None
|
|
|
|
|
elif spatial_bn_gradient_phase:
|
|
|
|
|
new_ops.extend(injected_ops)
|
2018-10-18 11:19:28 -07:00
|
|
|
new_ops.extend(_cpuReduce(
|
|
|
|
|
stripBlobName(scale_grad_blobs[0]),
|
|
|
|
|
scale_grad_blobs,
|
|
|
|
|
scale_grad_blobs))
|
|
|
|
|
new_ops.extend(_cpuReduce(
|
|
|
|
|
stripBlobName(bias_grad_blobs[0]),
|
|
|
|
|
bias_grad_blobs,
|
|
|
|
|
bias_grad_blobs))
|
2018-01-24 13:10:56 -08:00
|
|
|
new_ops.extend(batch_norm_ops)
|
|
|
|
|
injected_ops = []
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
scale_grad_blobs = []
|
|
|
|
|
bias_grad_blobs = []
|
|
|
|
|
spatial_bn_gradient_phase = False
|
|
|
|
|
new_ops.append(op)
|
|
|
|
|
elif op.type == 'SpatialBN':
|
|
|
|
|
spatial_bn_phase = True
|
|
|
|
|
if input_blob_name is None:
|
|
|
|
|
input_blob_name = op.input[0]
|
|
|
|
|
name = op.input[0]
|
|
|
|
|
injected_ops.append(
|
|
|
|
|
core.CreateOperator(
|
|
|
|
|
"ChannelStats",
|
|
|
|
|
name,
|
|
|
|
|
[name + "_sums", name + "_sumsq"]))
|
|
|
|
|
sums_blobs.append(name + "_sums")
|
|
|
|
|
sumsq_blobs.append(name + "_sumsq")
|
|
|
|
|
op.input.append(input_blob_name + "_sums_combined")
|
|
|
|
|
op.input.append(input_blob_name + "_sumsq_combined")
|
|
|
|
|
op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
|
|
|
|
|
batch_norm_ops.append(op)
|
|
|
|
|
elif op.type == 'SpatialBNGradient':
|
|
|
|
|
spatial_bn_gradient_phase = True
|
|
|
|
|
injected_ops.append(
|
|
|
|
|
core.CreateOperator("ChannelBackpropStats",
|
|
|
|
|
[op.input[0], op.input[3], op.input[4],
|
|
|
|
|
op.input[2]],
|
|
|
|
|
[op.output[1], op.output[2]]))
|
|
|
|
|
scale_grad_blobs.append(op.output[1])
|
|
|
|
|
bias_grad_blobs.append(op.output[2])
|
|
|
|
|
op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
|
|
|
|
|
op.input.extend([op.output[1], op.output[2]])
|
|
|
|
|
batch_norm_ops.append(op)
|
|
|
|
|
|
|
|
|
|
assert not spatial_bn_phase, \
|
2018-10-18 11:19:28 -07:00
|
|
|
"Net modification for cpu inter-device batch normalization failed"
|
|
|
|
|
del model.net.Proto().op[:]
|
|
|
|
|
model.net.Proto().op.extend(new_ops)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _GPUInterDeviceBatchNormalization(model):
|
|
|
|
|
orig_ops = list(model.net.Proto().op)
|
|
|
|
|
new_ops = []
|
|
|
|
|
num_devices = len(model._devices)
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
injected_ops = []
|
|
|
|
|
|
|
|
|
|
spatial_bn_phase = False
|
|
|
|
|
sums_blobs = []
|
|
|
|
|
sumsq_blobs = []
|
|
|
|
|
name = []
|
|
|
|
|
input_blob_name = None
|
|
|
|
|
|
|
|
|
|
spatial_bn_gradient_phase = False
|
|
|
|
|
scale_grad_blobs = []
|
|
|
|
|
bias_grad_blobs = []
|
|
|
|
|
master_device = "cpu_0"
|
|
|
|
|
master_device_option = core.DeviceOption(caffe2_pb2.CPU)
|
|
|
|
|
|
|
|
|
|
def _gpuReduce(param, num_devices, master_device, result_blobs=None):
|
|
|
|
|
"""
|
|
|
|
|
Reduces results from multiple gpus and distributes the results back
|
|
|
|
|
to each device. This is done by copying values to the master device
|
|
|
|
|
and summing them. The master device result is then copied back to
|
|
|
|
|
each of the devices.
|
|
|
|
|
|
|
|
|
|
param: the name of the data (blobs) to reduce
|
|
|
|
|
num_devices: the number of devices
|
|
|
|
|
master_device: the device to copy/compute values on
|
|
|
|
|
result_blobs: optional list of result blobs to copy to
|
|
|
|
|
"""
|
|
|
|
|
added_ops = []
|
|
|
|
|
source_blobs = []
|
|
|
|
|
destination_blobs = []
|
|
|
|
|
if result_blobs is None:
|
|
|
|
|
result_blobs = [
|
|
|
|
|
"gpu_{}/{}_combined".format(i, param) for i in range(num_devices)
|
|
|
|
|
]
|
|
|
|
|
for i in range(num_devices):
|
|
|
|
|
device_option = core.DeviceOption(model._device_type, i)
|
|
|
|
|
source_blobs.append("gpu_{}/{}".format(i, param))
|
|
|
|
|
destination_blobs.append(
|
|
|
|
|
"{}/{}_gpu_{}_copy".format(master_device, param, i))
|
|
|
|
|
added_ops.append(
|
|
|
|
|
core.CreateOperator(
|
|
|
|
|
"CopyGPUToCPU",
|
|
|
|
|
source_blobs[i],
|
|
|
|
|
destination_blobs[i],
|
|
|
|
|
device_option=device_option))
|
|
|
|
|
added_ops.append(
|
|
|
|
|
core.CreateOperator(
|
|
|
|
|
"Sum",
|
|
|
|
|
destination_blobs,
|
|
|
|
|
"{}/{}_combined".format(master_device, param),
|
|
|
|
|
device_option=master_device_option))
|
|
|
|
|
for i in range(num_devices):
|
|
|
|
|
device_option = core.DeviceOption(model._device_type, i)
|
|
|
|
|
added_ops.append(
|
|
|
|
|
core.CreateOperator(
|
|
|
|
|
"CopyCPUToGPU",
|
|
|
|
|
"{}/{}_combined".format(master_device, param),
|
|
|
|
|
result_blobs[i],
|
|
|
|
|
device_option=device_option))
|
|
|
|
|
return added_ops
|
|
|
|
|
|
|
|
|
|
for op in orig_ops:
|
|
|
|
|
if op.type != 'SpatialBN' and op.type != 'SpatialBNGradient':
|
|
|
|
|
if spatial_bn_phase:
|
|
|
|
|
new_ops.extend(injected_ops)
|
|
|
|
|
new_ops.extend(_gpuReduce(
|
|
|
|
|
stripBlobName(input_blob_name) + "_sums",
|
|
|
|
|
num_devices,
|
|
|
|
|
master_device,
|
|
|
|
|
))
|
|
|
|
|
new_ops.extend(_gpuReduce(
|
|
|
|
|
stripBlobName(input_blob_name) + "_sumsq",
|
|
|
|
|
num_devices,
|
|
|
|
|
master_device,
|
|
|
|
|
))
|
|
|
|
|
new_ops.extend(batch_norm_ops)
|
|
|
|
|
injected_ops = []
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
sums_blobs = []
|
|
|
|
|
sumsq_blobs = []
|
|
|
|
|
spatial_bn_phase = False
|
|
|
|
|
input_blob_name = None
|
|
|
|
|
elif spatial_bn_gradient_phase:
|
|
|
|
|
new_ops.extend(injected_ops)
|
|
|
|
|
new_ops.extend(_gpuReduce(
|
|
|
|
|
stripBlobName(scale_grad_blobs[0]),
|
|
|
|
|
num_devices,
|
|
|
|
|
master_device,
|
|
|
|
|
scale_grad_blobs,
|
|
|
|
|
))
|
|
|
|
|
new_ops.extend(_gpuReduce(
|
|
|
|
|
stripBlobName(bias_grad_blobs[0]),
|
|
|
|
|
num_devices,
|
|
|
|
|
master_device,
|
|
|
|
|
bias_grad_blobs,
|
|
|
|
|
))
|
|
|
|
|
new_ops.extend(batch_norm_ops)
|
|
|
|
|
injected_ops = []
|
|
|
|
|
batch_norm_ops = []
|
|
|
|
|
scale_grad_blobs = []
|
|
|
|
|
bias_grad_blobs = []
|
|
|
|
|
spatial_bn_gradient_phase = False
|
|
|
|
|
new_ops.append(op)
|
|
|
|
|
elif op.type == 'SpatialBN':
|
|
|
|
|
spatial_bn_phase = True
|
|
|
|
|
if input_blob_name is None:
|
|
|
|
|
input_blob_name = op.input[0]
|
|
|
|
|
name = op.input[0]
|
|
|
|
|
device_option = core.DeviceOption(
|
|
|
|
|
model._device_type,
|
|
|
|
|
op.device_option.device_id,
|
|
|
|
|
)
|
|
|
|
|
injected_ops.append(
|
|
|
|
|
core.CreateOperator(
|
|
|
|
|
"ChannelStats",
|
|
|
|
|
name,
|
|
|
|
|
[name + "_sums", name + "_sumsq"],
|
|
|
|
|
device_option=device_option))
|
|
|
|
|
sums_blobs.append(name + "_sums")
|
|
|
|
|
sumsq_blobs.append(name + "_sumsq")
|
|
|
|
|
op.input.append(name + "_sums_combined")
|
|
|
|
|
op.input.append(name + "_sumsq_combined")
|
|
|
|
|
op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
|
|
|
|
|
batch_norm_ops.append(op)
|
|
|
|
|
elif op.type == 'SpatialBNGradient':
|
|
|
|
|
spatial_bn_gradient_phase = True
|
|
|
|
|
device_option = core.DeviceOption(
|
|
|
|
|
model._device_type,
|
|
|
|
|
op.device_option.device_id,
|
|
|
|
|
)
|
|
|
|
|
injected_ops.append(
|
|
|
|
|
core.CreateOperator("ChannelBackpropStats",
|
|
|
|
|
[op.input[0], op.input[3], op.input[4],
|
|
|
|
|
op.input[2]],
|
|
|
|
|
[op.output[1], op.output[2]],
|
|
|
|
|
device_option=device_option))
|
|
|
|
|
scale_grad_blobs.append(op.output[1])
|
|
|
|
|
bias_grad_blobs.append(op.output[2])
|
|
|
|
|
op.arg.extend([utils.MakeArgument("num_batches", num_devices)])
|
|
|
|
|
op.input.extend([op.output[1], op.output[2]])
|
|
|
|
|
batch_norm_ops.append(op)
|
|
|
|
|
|
|
|
|
|
assert not spatial_bn_phase, \
|
|
|
|
|
"Net modification for gpu inter-device batch normalization failed"
|
2018-01-24 13:10:56 -08:00
|
|
|
del model.net.Proto().op[:]
|
|
|
|
|
model.net.Proto().op.extend(new_ops)
|