Skip to content

Commit ba258d5

Browse files
author
Andy Feng
committed
LMDB partitions and thread safety enhancement
1 parent 1566f47 commit ba258d5

4 files changed

Lines changed: 81 additions & 62 deletions

File tree

‎caffe-grid/src/main/scala/com/yahoo/ml/caffe/CaffeOnSpark.scala‎

Lines changed: 45 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ object CaffeOnSpark {
3232

3333
//Caffe-on-Spark configuration
3434
var conf = new Config(sc, args)
35-
35+
3636
//training if specified
3737
val caffeSpark = new CaffeOnSpark(sc)
3838
if (conf.isTraining) {
@@ -43,12 +43,14 @@ object CaffeOnSpark {
4343
//feature extraction
4444
if (conf.isFeature || conf.isTest) {
4545
val source = DataSource.getSource(conf, false)
46-
if (conf.isFeature) { //feature extraction
46+
if (conf.isFeature) {
47+
//feature extraction
4748
val featureDF = caffeSpark.features(source)
48-
49+
4950
//save extracted features into the specified file
5051
val rdf = featureDF.write.format(source.conf.outputFormat).save(source.conf.outputPath)
51-
}else { //test
52+
} else {
53+
//test
5254
val result = caffeSpark.test(source)
5355

5456
//save test results into a local file
@@ -59,9 +61,9 @@ object CaffeOnSpark {
5961
else
6062
localFilePath = System.getProperty("user.dir") + "/test_result.tmp"
6163
val out: PrintWriter = new PrintWriter(localFilePath)
62-
result.map{
64+
result.map {
6365
case (name, r) => {
64-
out.println(name + ": "+r.mkString(","))
66+
out.println(name + ": " + r.mkString(","))
6567
}
6668
}
6769
out.close
@@ -76,7 +78,6 @@ object CaffeOnSpark {
7678
}
7779

7880

79-
8081
/**
8182
* CaffeOnSpark is the main class for distributed deep learning.
8283
* It will launch multiple Caffe cores within Spark executors, and conduct coordinated learning from HDFS datasets.
@@ -98,8 +99,8 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
9899
* Training with a specific data source
99100
* @param source input data source
100101
*/
101-
def train[T1,T2](source:DataSource[T1,T2]): Unit = {
102-
var trainDataRDD : RDD[T1] = source.makeRDD(sc)
102+
def train[T1, T2](source: DataSource[T1, T2]): Unit = {
103+
var trainDataRDD: RDD[T1] = source.makeRDD(sc)
103104
if (trainDataRDD == null) {
104105
log.info("No training data is given")
105106
return
@@ -126,19 +127,19 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
126127
}.collect()
127128

128129
for (i <- rank_2_addresses_n_host)
129-
log.info("rank = " + i._1 + ", RDMAaddress = " + i._2.mkString(",") + ", hostname = " + i._3)
130+
log.info("rank = " + i._1 + ", address = " + i._2.mkString(",") + ", hostname = " + i._3)
130131
var numExecutors: Int = sc.getExecutorMemoryStatus.size
131132
val numDriver: Int = if (sc.isLocal) 0 else 1
132133
if (conf.clusterSize + numDriver != numExecutors) {
133134
log.error("Requested # of executors: " + conf.clusterSize + " actual # of executors:" + (numExecutors - numDriver) +
134-
". Please try to set --conf spark.scheduler.maxRegisteredResourcesWaitingTime with a large value (default 30s)")
135+
". Please try to set --conf spark.scheduler.maxRegisteredResourcesWaitingTime with a large value (default 30s)")
135136
throw new IllegalStateException("actual number of executors is not as expected")
136137
}
137138

138139
//Phase 2: bcast RDMA addresses
139140
val rank_2_addresses = rank_2_addresses_n_host.map {
140141
case (rank, rdma_addr, host) => {
141-
if (rank==0) log.info("rank 0:"+host)
142+
if (rank == 0) log.info("rank 0:" + host)
142143
(rank, rdma_addr)
143144
}
144145
}
@@ -147,7 +148,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
147148
//Phase 3: set up the processors
148149
sc.parallelize(0 until conf.clusterSize, conf.clusterSize).map {
149150
case rank: Int => {
150-
val processor = CaffeProcessor.instance[T1,T2]()
151+
val processor = CaffeProcessor.instance[T1, T2]()
151152
//start processor w/ the given addresses
152153
processor.start(bcast_addresses.value)
153154
}
@@ -158,7 +159,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
158159
val desired_part_count = (origin_part_count / conf.clusterSize) * conf.clusterSize
159160
if (origin_part_count != desired_part_count) {
160161
trainDataRDD = trainDataRDD.coalesce(desired_part_count, true)
161-
log.info("Training dataset partition count: "+origin_part_count+" -> "+desired_part_count)
162+
log.info("Training dataset partition count: " + origin_part_count + " -> " + desired_part_count)
162163
}
163164
if (conf.isRddPersistent) {
164165
trainDataRDD = trainDataRDD.persist(StorageLevel.DISK_ONLY)
@@ -170,26 +171,27 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
170171
val sizeRDD = trainDataRDD.mapPartitions {
171172
iter => {
172173
val partSize = iter.size
174+
// Spark decides how data partitions are distributed among executors in this step.
173175
// synchronize among the executors,
174176
// to achieve same number of partitions.
175-
val processor = CaffeProcessor.instance[T1,T2]()
177+
val processor = CaffeProcessor.instance[T1, T2]()
176178
processor.sync()
177179
Iterator(partSize)
178180
}
179181
}.persist()
180182
minPartSize = sizeRDD.min()
181-
log.info("Partition size: min=" + minPartSize + " max="+sizeRDD.max())
183+
log.info("Partition size: min=" + minPartSize + " max=" + sizeRDD.max())
182184
}
183185

184186
//Phase 6: feed the processor
185187
var continue: Boolean = true
186188
while (continue) {
187189
//conduct training with dataRDD
188-
continue = trainDataRDD.mapPartitions{
190+
continue = trainDataRDD.mapPartitions {
189191
iter => {
190192
var res = false
191193
//feed training data from iterator
192-
val processor = CaffeProcessor.instance[T1,T2]()
194+
val processor = CaffeProcessor.instance[T1, T2]()
193195
if (!processor.solversFinished) {
194196
if (minPartSize > 0) {
195197
res = iter.take(minPartSize).map { sample => processor.feedQueue(sample) }.reduce(_ && _)
@@ -210,7 +212,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
210212
/**
211213
* a utility function for shutting processor thread pool
212214
*/
213-
private def shutdownProcessors[T1,T2](conf: Config): Unit = {
215+
private def shutdownProcessors[T1, T2](conf: Config): Unit = {
214216
sc.parallelize(0 until conf.clusterSize, conf.clusterSize).map {
215217
_ => {
216218
val processor = CaffeProcessor.instance[T1, T2]()
@@ -226,15 +228,16 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
226228
* @param source input data source
227229
* @return key/value map for mean values of output layers
228230
*/
229-
def test[T1,T2](source:DataSource[T1,T2]) : Map[String, Seq[Double]] = {
231+
def test[T1, T2](source: DataSource[T1, T2]): Map[String, Seq[Double]] = {
230232
source.conf.isTest = true
231233
val testDF = features2(source)
232234

233235
var result = new mutable.HashMap[String, Seq[Double]]
234236
// compute the mean of the columns
235237
testDF.columns.zipWithIndex.map {
236238
case (name, index) => {
237-
if (index > 0) { // first column is SampleId, ignored.
239+
if (index > 0) {
240+
// first column is SampleId, ignored.
238241
val n: Int = testDF.take(1)(0).getSeq[Double](index).size
239242
val ndf = testDF.agg(new VectorMean(n)(testDF(name)))
240243
val r: Seq[Double] = ndf.take(1)(0).getSeq[Double](0)
@@ -256,7 +259,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
256259
* @param source input data source
257260
* @return Feature data frame
258261
*/
259-
def features[T1,T2](source:DataSource[T1,T2]) : DataFrame = {
262+
def features[T1, T2](source: DataSource[T1, T2]): DataFrame = {
260263
source.conf.isTest = false
261264
var featureDF = features2(source)
262265

@@ -274,7 +277,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
274277
* @param source input data source
275278
* @return a data frame
276279
*/
277-
private def features2[T1,T2](source:DataSource[T1,T2]) : DataFrame = {
280+
private def features2[T1, T2](source: DataSource[T1, T2]): DataFrame = {
278281
val srcDataRDD = source.makeRDD(sc)
279282
val conf = source.conf
280283
val clusterSize: Int = conf.clusterSize
@@ -283,19 +286,19 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
283286
val size = sc.parallelize(0 until clusterSize, clusterSize).map {
284287
case rank: Int => {
285288
// each processor has clusterSize 1 and rank 0
286-
val processor = CaffeProcessor.instance[T1,T2](source, rank)
289+
val processor = CaffeProcessor.instance[T1, T2](source, rank)
287290
}
288291
}.count()
289292
if (size < clusterSize) {
290-
log.error((clusterSize-size) + "executors have failed. Please check Spark executor logs")
293+
log.error((clusterSize - size) + "executors have failed. Please check Spark executor logs")
291294
throw new IllegalStateException("Executor failed at CaffeProcessor startup for test/feature extraction")
292295
}
293296

294297
// Sanity check
295298
val numExecutors: Int = sc.getExecutorMemoryStatus.size
296299
val numDriver: Int = if (sc.isLocal) 0 else 1
297300
if ((size + numDriver) != sc.getExecutorMemoryStatus.size) {
298-
log.error("Requested # of executors: " + clusterSize + " actual # of executors:" + (numExecutors-numDriver) +
301+
log.error("Requested # of executors: " + clusterSize + " actual # of executors:" + (numExecutors - numDriver) +
299302
". Please try to set --conf spark.scheduler.maxRegisteredResourcesWaitingTime with a large value (default 30s)")
300303
throw new IllegalStateException("actual number of executors is not as expected")
301304
}
@@ -314,17 +317,22 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
314317
//Phase 3: feed the processors
315318
val featureRDD = srcDataRDD.mapPartitions {
316319
iter => {
317-
val processor = CaffeProcessor.instance[T1,T2]()
318-
if (!processor.solversFinished) {
319-
processor.start(null)
320-
val res = iter.map { sample => processor.feedQueue(sample) }.reduce(_ && _)
321-
processor.solversFinished = !res
322-
processor.stopThreads()
323-
import scala.collection.JavaConversions._
324-
processor.results.iterator
325-
} else {
326-
Iterator()
327-
}
320+
val processor: CaffeProcessor[T1, T2] = CaffeProcessor.instance[T1, T2]()
321+
val feature_iter: Iterator[Row] =
322+
if (processor.solversFinished)
323+
Iterator()
324+
else {
325+
processor.synchronized {
326+
processor.start(null)
327+
val res = iter.map { sample => processor.feedQueue(sample) }.reduce(_ && _)
328+
processor.solversFinished = !res
329+
processor.stopThreads()
330+
331+
import scala.collection.JavaConversions._
332+
processor.results.iterator
333+
}
334+
}
335+
feature_iter
328336
}
329337
}
330338

‎caffe-grid/src/main/scala/com/yahoo/ml/caffe/CaffeProcessor.scala‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,14 @@ private[caffe] class CaffeProcessor[T1, T2](val source: DataSource[T1, T2],
152152

153153
// sync the executors
154154
def sync(): Unit = {
155-
if (source.isTrain)
156-
caffeNetList(0).sync
155+
/**
156+
* Multiple tasks may invoke sync() concurrently.
157+
* To sure that all executors are synchronized, we will execute those invocation in sequence.
158+
*/
159+
synchronized {
160+
if (source.isTrain)
161+
caffeNetList(0).sync
162+
}
157163
}
158164

159165
//feed data to train queue

‎caffe-grid/src/main/scala/com/yahoo/ml/caffe/Config.scala‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class Config(sc: SparkContext) extends Serializable {
5858
def protoFile_=(value: String): Unit = {
5959
_protoFile = value
6060
if (value == null || value.length() == 0) {
61-
log.error("Error: need protofile path")
61+
log.warn("solver protofile isn't given")
6262
} else {
6363
//solver parameter
6464
_solverParameter = Utils.GetSolverParam(value)
@@ -152,7 +152,7 @@ class Config(sc: SparkContext) extends Serializable {
152152
*/
153153
def modelPath_=(value: String): Unit = {
154154
if (value == null || value.length() == 0) {
155-
log.error("modelPath is required")
155+
log.warn("modelPath is not specified")
156156
}
157157
_modelPath = value
158158
}

‎caffe-grid/src/main/scala/com/yahoo/ml/caffe/LmdbRDD.scala‎

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,52 +43,56 @@ class LmdbRDD(@transient val sc: SparkContext, val lmdb_path: String, val numPar
4343
if (!lmdb_path.startsWith(FSUtils.localfsPrefix))
4444
sc.addFile(lmdb_path, true)
4545

46-
var part_index: Int = 0
47-
var pos: Int = 0
48-
4946
openDB()
47+
48+
//part_size: # of keys to be included in each partitions
5049
val size: Long = db.stat().ms_entries
5150
val part_size: Int = Math.ceil(size.toDouble / numPartitions.toDouble).toInt
5251

53-
var failed = false
52+
var is_done = false
5453
var next: Entry = null
55-
var start_key: Array[Byte] = null
5654
val partitions = new Array[Partition](numPartitions)
57-
while (failed == false && part_index < numPartitions) {
55+
//last key in previous partition
56+
var start_key: Array[Byte] = null
57+
58+
var part_index: Int = 0
59+
partitions(part_index) = new LmdbPartition(part_index, null, part_size)
60+
61+
while (is_done == false && (part_index+1) < numPartitions) {
5862
val txn = env.createReadTransaction()
5963

6064
try {
6165
val it = if (part_index == 0) db.iterate(txn)
6266
else db.seek(txn, start_key)
6367

64-
while (it.hasNext && (pos - 1) % part_size != 0) {
68+
//skip (part_size) entries
69+
var pos_in_partition: Int = 0
70+
while (it.hasNext && (pos_in_partition < part_size)) {
6571
next = it.next()
66-
pos = pos + 1
72+
pos_in_partition = pos_in_partition + 1
6773
}
6874

69-
if ((pos - 1) % part_size == 0) {
70-
start_key = next.getKey()
75+
//start key for next partition
76+
if (it.hasNext) {
77+
start_key = it.next().getKey()
78+
part_index = part_index + 1
7179
partitions(part_index) = new LmdbPartition(part_index, start_key, part_size)
80+
} else {
81+
is_done = true
7282
}
73-
74-
part_index = part_index + 1
7583
} catch {
7684
case e: Exception => {
7785
logWarning(e.toString, e)
78-
failed = true
86+
is_done = true
7987
}
8088
} finally {
8189
commit(txn)
8290
}
8391
}
8492
closeDB()
8593

86-
if (failed) {
87-
null
88-
} else {
89-
logInfo(partitions.length + " LMDB RDD partitions")
90-
partitions
91-
}
94+
logInfo((part_index+1) + " LMDB RDD partitions")
95+
partitions
9296
}
9397

9498
override def compute(thePart: Partition, context: TaskContext):
@@ -100,8 +104,9 @@ class LmdbRDD(@transient val sc: SparkContext, val lmdb_path: String, val numPar
100104
val part = thePart.asInstanceOf[LmdbPartition]
101105
val txn: Transaction = env.createReadTransaction()
102106
var pos_in_partition: Int = 0
103-
var it = if (txn != null)
104-
db.seek(txn, part.startKey)
107+
var it = if (part != null && txn != null) {
108+
if (part.startKey == null) db.iterate(txn) else db.seek(txn, part.startKey)
109+
}
105110
else {
106111
closeDB()
107112
null

0 commit comments

Comments
 (0)