Skip to content

Commit 4ba283f

Browse files
author
Andy Feng
committed
Input datasource improved: LMDB and ImageDataSource
1 parent 719b835 commit 4ba283f

17 files changed

Lines changed: 873 additions & 141 deletions

‎caffe-distri/src/main/cpp/jni/JniMat.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@
1111
/*
1212
* Class: com_yahoo_ml_jcaffe_Mat
1313
* Method: allocate
14-
* Signature: (III[B)Z
14+
* Signature: (III[)Z
1515
*/
1616
JNIEXPORT jlong JNICALL Java_com_yahoo_ml_jcaffe_Mat_allocate
17-
(JNIEnv *env, jobject object, jint height, jint width, jbyteArray array, jboolean isSigned) {
17+
(JNIEnv *env, jobject object, jint channels, jint height, jint width, jbyteArray array) {
1818

1919
jboolean isCopy = false;
2020
jbyte *data = env->GetByteArrayElements(array, &isCopy);
@@ -38,7 +38,7 @@ JNIEXPORT jlong JNICALL Java_com_yahoo_ml_jcaffe_Mat_allocate
3838
}
3939

4040
/* create a native Mat object */
41-
cv::Mat* native_ptr = new cv::Mat(height, width, (isSigned? CV_8SC1 : CV_8UC1), data);
41+
cv::Mat* native_ptr = new cv::Mat(height, width, CV_8UC(channels), data);
4242

4343
/* associate native object with JVM object */
4444
SetNativeAddress(env, object, native_ptr);

‎caffe-distri/src/main/java/com/yahoo/ml/jcaffe/Mat.java‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,32 +21,24 @@ public class Mat extends BaseObject {
2121
* @param data
2222
*/
2323
public Mat(byte[] data) {
24-
this(data, false);
25-
}
26-
27-
/**
28-
* Constructor of a Mat without a specific dimensions
29-
* @param data
30-
* @param signed
31-
*/
32-
public Mat(byte[] data, boolean signed) {
33-
this(data.length, 1, data, signed);
24+
this(1, 1, data.length, data);
3425
}
3526

3627
/**
3728
* Constructor of a Mat with a specific dimensions
29+
* @param channels
3830
* @param height
3931
* @param width
4032
* @param data
4133
* @param signed
4234
*/
43-
public Mat(int height, int width, byte[] data, boolean signed) {
44-
dataaddress = allocate(height, width, data, signed);
35+
public Mat(int channels, int height, int width, byte[] data) {
36+
dataaddress = allocate(channels, height, width, data);
4537
if (dataaddress == 0)
4638
throw new RuntimeException("Failed to create Mat object");
4739
}
4840

49-
private native long allocate(int height, int width, byte[] data, boolean signed);
41+
private native long allocate(int channels, int height, int width, byte[] data);
5042

5143
private long dataaddress = 0;
5244

@@ -79,7 +71,7 @@ public synchronized void decode(int flags){
7971
*/
8072
public synchronized void resize(int height, int width){
8173
resize(height, width, dataaddress);
82-
dataaddress = 0;
74+
dataaddress = 0;
8375
}
8476
private native void resize(int height, int width, long dataaddress);
8577

‎caffe-distri/src/test/java/com/yahoo/ml/jcaffe/MatTest.java‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -124,26 +124,34 @@ private void matResizeDecodeTest() throws Exception {
124124
m.deallocate();
125125
}
126126

127+
@Test
128+
private void matChannelsTest() throws Exception {
129+
byte[] data0 = getDataFromFile(0);
130+
Mat m = new Mat(3, 9, 9, data0);
131+
assertEquals(m.channels(), 3);
132+
m.deallocate();
133+
}
134+
127135
@Test
128136
private void basicDataTest() throws Exception {
129137
MatVector matVec = new MatVector(1);
130138
byte[] data0 = getDataFromFile(0);
131-
Mat mat = new Mat(data0);
132-
matVec.put(0, mat);
133-
byte[] resultData0 = matVec.data(0);
139+
Mat mat = new Mat(data0);
140+
matVec.put(0, mat);
141+
byte[] resultData0 = matVec.data(0);
134142
//What we wrote is what we get
135-
assertTrue(Arrays.equals(data0,resultData0));
143+
assertTrue(Arrays.equals(data0, resultData0));
136144

137145
//Now replace matVec 0th mat object with a new one and make sure it is the new one
138146
byte[] data1 = getDataFromFile(1);
139147
mat = new Mat(data1);
140148
resultData0 = matVec.data(0);
141-
assertTrue(Arrays.equals(data0,resultData0));
142-
Mat oldmat = matVec.put(0,mat);
149+
assertTrue(Arrays.equals(data0, resultData0));
150+
Mat oldmat = matVec.put(0, mat);
143151
byte[] resultData1 = matVec.data(0);
144-
assertTrue(Arrays.equals(data1,resultData1));
152+
assertTrue(Arrays.equals(data1, resultData1));
145153
matVec.deallocate();
146-
assertTrue(Arrays.equals(data0,oldmat.data()));
154+
assertTrue(Arrays.equals(data0, oldmat.data()));
147155
oldmat.deallocate();
148156
}
149157
}

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

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,7 @@ object CaffeOnSpark {
5151
val featureDF = caffeSpark.features(source)
5252

5353
//save extracted features into the specified file
54-
val rdf = source.conf.outputFormat match {
55-
case "parquet" => {
56-
featureDF.write.parquet(source.conf.outputPath)
57-
}
58-
case _ => {
59-
featureDF.write.json(source.conf.outputPath)
60-
}
61-
}
54+
val rdf = featureDF.write.format(source.conf.outputFormat).save(source.conf.outputPath)
6255
}else { //test
6356
val result = caffeSpark.test(source)
6457

@@ -173,7 +166,7 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
173166
//Phase 5: find the minimum size of partitions
174167
var minPartSize = 0
175168
if (conf.clusterSize > 1) {
176-
minPartSize = trainDataRDD.mapPartitions {
169+
val sizeRDD = trainDataRDD.mapPartitions {
177170
iter => {
178171
val partSize = iter.size
179172
// synchronize among the executors,
@@ -182,8 +175,9 @@ class CaffeOnSpark(@transient val sc: SparkContext) extends Serializable {
182175
processor.sync()
183176
Iterator(partSize)
184177
}
185-
}.min
186-
log.info("minPartSize = " + minPartSize)
178+
}.persist()
179+
minPartSize = sizeRDD.min()
180+
log.info("Partition size: min=" + minPartSize + " max="+sizeRDD.max())
187181
}
188182

189183
//Phase 6: feed the processor

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,13 @@ private[caffe] class CaffeProcessor[T1, T2](val source: DataSource[T1, T2],
173173
//stop transformers & solvers
174174
import scala.collection.JavaConversions._
175175
for (solver <- solvers) Await.result(solver, Duration.Inf)
176-
for (transformer <- transformers) Await.result(transformer, Duration(1, "nanos"))
176+
for (transformer <- transformers) {
177+
try {
178+
Await.result(transformer, Duration(1, "ms"))
179+
} catch {
180+
case e: Exception => log.warn("Some tranformer threads haven't been terminated yet")
181+
}
182+
}
177183
threadsStarted = false
178184
}
179185

@@ -298,7 +304,10 @@ private[caffe] class CaffeProcessor[T1, T2](val source: DataSource[T1, T2],
298304
if (tpl == STOP_MARK) {
299305
queuePair.Free.put(tpl)
300306
} else {
301-
caffeNet.train(syncIdx, tpl._2, toDataPtr(tpl._3))
307+
val rs : Boolean = caffeNet.train(syncIdx, tpl._2, toDataPtr(tpl._3))
308+
if (!rs) {
309+
log.warn("Failed at training at iteration "+it)
310+
}
302311
queuePair.Free.put(tpl)
303312

304313
if ((rank == 0) && isRootSolver && (snapshotInterval > 0) && ((it + 1) % snapshotInterval == 0)) {

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,16 @@ class Config(sc: SparkContext, args: Array[String]) extends Serializable {
2424
options.addOption("test", "test", false, "test mode")
2525
options.addOption("features", "features", true, "name of output blobs")
2626
options.addOption("label", "label", true, "name of label blobs to be included in features")
27-
options.addOption("outputFormat", "outputFormat", true, "feature output format, currently support json and parquet, default: json")
27+
options.addOption("inputFormat", "inputFormat", true,
28+
"input dataframe format, currently support json and parquet, default: json")
29+
options.addOption("select", "select", true, "Dataframe SQL statements. default: none")
30+
options.addOption("outputFormat", "outputFormat", true,
31+
"feature output format, currently support json and parquet, default: json")
2832
options.addOption("model", "model", true, "model path")
2933
options.addOption("output", "output", true, "output path")
3034
options.addOption("devices", "devices", true, "number of local GPUs")
31-
options.addOption("persistent", "persistent", false, "should data files be persistented on local file system?")
35+
options.addOption("persistent", "persistent", false,
36+
"should data files be persistented on local file system?")
3237
options.addOption("snapshot", "snapshot", true, "snapshot state file path")
3338
options.addOption("weights", "weights", true, "snapshot model file path")
3439
options.addOption("connection", "connection", true, "ethernet or infiniband (default)")
@@ -130,7 +135,14 @@ class Config(sc: SparkContext, args: Array[String]) extends Serializable {
130135
null
131136
}
132137

133-
val outputFormat : String = if (cmd.hasOption("outputFormat")) cmd.getOptionValue("outputFormat") else "json"
138+
/**
139+
* Input dataframe format. json or parquet
140+
*/
141+
var inputFormat : String = if (cmd.hasOption("inputFormat")) cmd.getOptionValue("inputFormat") else "json"
142+
/**
143+
* Output dataframe format. json or parquet
144+
*/
145+
var outputFormat : String = if (cmd.hasOption("outputFormat")) cmd.getOptionValue("outputFormat") else "json"
134146

135147
/* tool: input path */
136148
var imageRoot : String = if (cmd.hasOption("imageRoot")) cmd.getOptionValue("imageRoot") else null
@@ -141,6 +153,10 @@ class Config(sc: SparkContext, args: Array[String]) extends Serializable {
141153
@transient
142154
var netParam: NetParameter = null
143155

156+
/**
157+
* Initialization of configuration
158+
* @return initialized configuration
159+
*/
144160
def init() : Config = {
145161
val log = LoggerFactory.getLogger(this.getClass)
146162

@@ -196,6 +212,7 @@ class Config(sc: SparkContext, args: Array[String]) extends Serializable {
196212
buildr.append("test:").append(isTest).append("\n")
197213
buildr.append("features:").append(features.mkString(",")).append("\n")
198214
buildr.append("label:").append(label).append("\n")
215+
buildr.append("inputFormat:").append(inputFormat).append("\n")
199216
buildr.append("outputFormat:").append(outputFormat).append("\n")
200217
buildr.append("model:").append(modelPath).append("\n")
201218
buildr.append("output:").append(outputPath).append("\n")
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// Copyright 2016 Yahoo Inc.
2+
// Licensed under the terms of the Apache 2.0 license.
3+
// Please see LICENSE file in the project root for terms.
4+
package com.yahoo.ml.caffe
5+
6+
import org.apache.spark.SparkContext
7+
import org.apache.spark.rdd.RDD
8+
import org.apache.spark.sql.{DataFrame, SQLContext}
9+
import org.apache.spark.storage.StorageLevel
10+
11+
/**
12+
* ImageDataFrame is a built-in data source class using Spark dataframe format.
13+
*
14+
* ImageDataFrame expects dataframe with 2 required columns (lable:String, data:byte[]),
15+
* and 5 optional columns (id: String, channels :Int, height:Int, width:Int, encoded: Boolean).
16+
*
17+
* ImageDataFrame could be configured via 2 MemoryDataLayer parameter:
18+
* (1) dataframe_column_select ... a collection of dataframe SQL selection statements
19+
* (ex. "sampleId as id", "abs(height) as height")
20+
* (2) image_ecnoded ... indicate whether image data are encoded or not. (default: false)
21+
*
22+
* @param conf CaffeSpark configuration
23+
* @param layerId the layer index in the network protocol file
24+
* @param isTrain
25+
*/
26+
class ImageDataFrame(conf: Config, layerId: Int, isTrain: Boolean)
27+
extends ImageDataSource(conf, layerId, isTrain) {
28+
29+
/* construct a sample RDD */
30+
def makeRDD(sc: SparkContext): RDD[(String, String, Int, Int, Int, Boolean, Array[Byte])] = {
31+
val sqlContext = new SQLContext(sc)
32+
//load DataFrame
33+
var df: DataFrame = sqlContext.read.format(conf.inputFormat).load(sourceFilePath)
34+
35+
//select columns if specified
36+
if (memdatalayer_param.getDataframeColumnSelectCount() > 0) {
37+
val selects = memdatalayer_param.getDataframeColumnSelectList()
38+
39+
import scala.collection.JavaConversions._
40+
df = df.selectExpr(selects.toList:_*)
41+
}
42+
43+
//check optional columns
44+
val column_names : Array[String] = df.columns
45+
val has_id : Boolean = column_names.contains("id")
46+
val has_channels : Boolean = column_names.contains("channels")
47+
val has_height : Boolean = column_names.contains("height")
48+
val has_width : Boolean = column_names.contains("width")
49+
val has_encoded : Boolean = column_names.contains("encoded")
50+
51+
//mapping each row to RDD tuple
52+
df.map(row => {
53+
var id: String = if (!has_id) "" else row.getAs[String]("id")
54+
var label: String = row.getAs[String]("label")
55+
val channels : Int = if (!has_channels) 0 else row.getAs[Int]("channels")
56+
val height : Int = if (!has_height) 0 else row.getAs[Int]("height")
57+
val width : Int = if (!has_width) 0 else row.getAs[Int]("width")
58+
val encoded : Boolean = if (!has_encoded) memdatalayer_param.getImageEncoded() else row.getAs[Boolean]("encoded")
59+
val data : Array[Byte] = row.getAs[Any]("data") match {
60+
case str: String => str.getBytes
61+
case arr: Array[Byte@unchecked] => arr
62+
case _ => {
63+
log.error("Unsupport value type")
64+
null
65+
}
66+
}
67+
(id, label, channels, height, width, encoded, data)
68+
}).persist(StorageLevel.DISK_ONLY)
69+
}
70+
}
71+
72+
/**
73+
* ImageDataFrame using Parquet data frame format
74+
*
75+
* @param conf CaffeSpark configuration
76+
* @param layerId the layer index in the network protocol file
77+
* @param isTrain
78+
*/
79+
class ImageDataFrameParquet(conf: Config, layerId: Int, isTrain: Boolean)
80+
extends ImageDataFrame(conf, layerId, isTrain) {
81+
conf.inputFormat = "parquet"
82+
}
83+
84+
/**
85+
* ImageDataFrame using Json data frame format
86+
*
87+
* @param conf CaffeSpark configuration
88+
* @param layerId the layer index in the network protocol file
89+
* @param isTrain
90+
*/
91+
class ImageDataFrameJson(conf: Config, layerId: Int, isTrain: Boolean)
92+
extends ImageDataFrame(conf, layerId, isTrain) {
93+
conf.inputFormat = "json"
94+
}

0 commit comments

Comments
 (0)