eric-haibin-lin commented on a change in pull request #11502: [MXNET-614] 
Adding Synchronized Batch Normalization
URL: https://github.com/apache/incubator-mxnet/pull/11502#discussion_r200207758
 
 

 ##########
 File path: src/operator/contrib/sync_batch_norm-inl.h
 ##########
 @@ -0,0 +1,574 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+/*!
+ * Copyright (c) 2018 by Contributors
+ * \file sync_batch_norm-inl.h
+ * \brief Synchronized BatchNorm modified from BatchNormV1
+ * \author Hang Zhang
+*/
+#ifndef MXNET_OPERATOR_CONTRIB_SYNC_BATCH_NORM_INL_H_
+#define MXNET_OPERATOR_CONTRIB_SYNC_BATCH_NORM_INL_H_
+
+#include <dmlc/logging.h>
+#include <dmlc/parameter.h>
+#include <mxnet/operator.h>
+#include <condition_variable>
+#include <map>
+#include <vector>
+#include <string>
+#include <utility>
+#include "../operator_common.h"
+#include "../mshadow_op.h"
+
+namespace mxnet {
+namespace op {
+
+namespace syncbatchnorm {
+enum BatchNormOpInputs {kData, kGamma, kBeta};
+enum BatchNormOpOutputs {kOut, kMean, kVar};
+enum BatchNormOpAuxiliary {kMovingMean, kMovingVar};
+enum BatchNormBackResource {kTempSpace};
+}  // namespace syncbatchnorm
+
+struct SyncBatchNormParam : public dmlc::Parameter<SyncBatchNormParam> {
+  float eps;
+  float momentum;
+  bool fix_gamma;
+  bool use_global_stats;
+  bool output_mean_var;
+  int ndev;
+  std::string key;
+  DMLC_DECLARE_PARAMETER(SyncBatchNormParam) {
+    DMLC_DECLARE_FIELD(eps).set_default(1e-3f)
+    .describe("Epsilon to prevent div 0");
+    DMLC_DECLARE_FIELD(momentum).set_default(0.9f)
+    .describe("Momentum for moving average");
+    DMLC_DECLARE_FIELD(fix_gamma).set_default(true)
+    .describe("Fix gamma while training");
+    DMLC_DECLARE_FIELD(use_global_stats).set_default(false)
+    .describe("Whether use global moving statistics instead of local 
batch-norm. "
+              "This will force change batch-norm into a scale shift 
operator.");
+    DMLC_DECLARE_FIELD(output_mean_var).set_default(false)
+    .describe("Output All,normal mean and var");
+    DMLC_DECLARE_FIELD(ndev).set_default(1)
+      .describe("The count of GPU devices");
+    DMLC_DECLARE_FIELD(key)
+      .set_default("")
+      .describe("Hash key for synchronization");
+  }
+};
+
+// Modified from https://github.com/brucechin/SharedTensor
+template<class T>
+class SharedND {
+ private:
+  int num_devices_;
+  T mean_;
+  T *data_;
+  bool *flag_;
+  bool mean_ready_ = false;
+  bool mean_inited_ = false;
+  std::mutex mutex_;
+
+ public:
+  explicit SharedND(int ndev) :num_devices_(ndev) {
+      flag_ = new bool[ndev];
+      data_ = new T[ndev];
+      memset(flag_, false, ndev * sizeof(bool));
+  }
+
+  ~SharedND() {
+    delete [] flag_;
+    delete [] data_;
+  }
+
+  bool Push(T input, int index) {
+    if (flag_[index] == false) {
+      data_[index] = input;
+      flag_[index] = true;
+      return true;
+    } else {
+      return false;
+    }
+  }
+
+  T Pop(int index) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    while (!MeanReady()) {}
+    flag_[index] = false;
+    T tmp = mean_;
+    ResetMean();
+    return tmp;
+  }
+
+  bool MeanReady() {
+    if (mean_ready_) {
+      return true;
+    }
+    for (int i = 0; i < num_devices_; i++) {
+      if (!flag_[i]) {
+        return false;
+      }
+    }
+    for (int i = 1; i < num_devices_; i++) {
+      data_[0] += data_[i];
+    }
+    if (!mean_inited_) {
+      mean_ = mshadow::NewTensor<cpu, real_t>(data_[0].shape_, 0.0f);
+      mean_inited_ = true;
+    }
+    mean_ = data_[0] * 1.0f /  num_devices_;
+    mean_ready_ = true;
+    return true;
+  }
+
+  void ResetMean() {
+    for (int i = 0; i < num_devices_; i++) {
+      if (flag_[i]) return;
+    }
+    mean_ready_ = false;
+  }
+};
+
+template<class T>
+class GlobalShared {
+ public:
+  T* Register(const std::string &key, int ndev) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    auto it = registry_.find(key);
+    if (it != registry_.end()) return it->second;
+    T *newT = new T(ndev);
+    registry_[key] = newT;
+    return newT;
+  }
+  ~GlobalShared() {
+    for (auto it = registry_.begin(); it != registry_.end(); it++) {
+      T *ptr = it->second;
+      delete [] ptr;
+    }
+  }
+ private:
+  std::mutex mutex_;
+  std::map<std::string, T*> registry_;
+};
+
+template<class T>
+class GlobalSharedRank {
+ public:
+  T Register(const std::string &key, int ndev) {
+    std::lock_guard<std::mutex> lock(mutex_);
+    auto it = registry_.find(key);
+    if (it != registry_.end()) {
+      T* tmpT = it->second;
+      *tmpT = (*tmpT == ndev - 1) ? 0 : *tmpT + 1;
+      return *tmpT;
+    }
+    T *newT = new T(0);
+    registry_[key] = newT;
+    return *newT;
+  }
+  ~GlobalSharedRank() {
+    for (auto it = registry_.begin(); it != registry_.end(); it++) {
+      T *ptr = it->second;
+      delete [] ptr;
+    }
+  }
+ private:
+  std::mutex mutex_;
+  std::map<std::string, T*> registry_;
+};
+
+class Barrier {
+ private:
+  std::mutex mutex_;
+  std::condition_variable cv_;
+  std::size_t count_;
+  std::size_t total_count_;
+ public:
+  explicit Barrier(std::size_t count) : count_{count}, total_count_{count} { }
+  void Wait() {
+    std::unique_lock<std::mutex> lock{mutex_};
+    if (--count_ == 0) {
+      count_ = total_count_;
+      cv_.notify_all();
+    } else {
+      cv_.wait(lock, [this] { return count_ == total_count_; });
+    }
+  }
+};
+
+// Global variables for Synchronizations
+static GlobalSharedRank<int> globalSharedRank;
 
 Review comment:
   static GlobalSharedRank<int> global_shared_rank;
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to