why .net slowly than python and run slowly in gpu than cpu?
I use tensorflow.net to predit classisify the images. my environment is tensoflow.net0.60.4 、Tensorflow.Keras 0.6.4、SharpCV 0.10.1 、Redist-windows-gpu 2.6.0、OpencvSharp4.runtime.win 4.4.020200915。I write code python and .net,and found .net version slowly than python. here is my python code: ''' model_path = "train-renforce.h5" base_dir = 'dataset' test_dir = os.path.join(base_dir,'test1') model = tf.keras.models.load_model(model_path) model.summary()
def predict(label,filepath): # print(filepath) img = cv2.imread(filepath) print(img.shape) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) x = np.expand_dims(img,axis=0) x = x/255.0 preds = model.predict(x) rs = np.argmax(preds,axis=1) return rs[0]
labels = {0:'0.斑点',1:'1.发霉',2:'2.发芽',3:'3.红皮',4:'4.起泡',5:'5.油污',6:'6.正常',7:'7.白斑'}
total = 0 correct = 0 time_start = time.time() for root,dirs,_ in os.walk(test_dir): for dir in dirs: dirpath = os.path.join(root,dir) label = int(dir[0]) for ,,files in os.walk(os.path.join(test_dir,dir)): for file in files: filepath = os.path.join(dirpath,file) rs = predict(label,filepath) if (rs!=6 and label!=6) or(rs==6 and label==6): correct = correct+1 total = total +1 time_end = time.time() acc = float(correct)/total print('总共' + str(total) + '张图片,正确预测' + str(correct) + '张,准确率' + str(acc) + '用时' + str(time_end-time_start))` ''' and this is .net code :
// tensorflow设置 //tf.debugging.set_log_device_placement(true); tf.Context.Config.GpuOptions.AllowGrowth = true; //tf.compat.v1.disable_eager_execution();
var model = keras.Sequential(new List<ILayer>
{
keras.layers.InputLayer(input_shape:(220,112,3)),
keras.layers.Conv2D(32,3,activation:"relu"),
keras.layers.MaxPooling2D(2),
keras.layers.Conv2D(64,(3,3),activation:"relu"),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Conv2D(128,(3,3),activation:"relu"),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Conv2D(128,(3,3),activation:"relu"),
keras.layers.MaxPooling2D((2,2)),
keras.layers.Flatten(),
keras.layers.Dense(512,activation:"relu"),
keras.layers.Dense(8,activation:"softmax")
});
model.summary();
model.load_weights("ok-weight.h5");
// 测试文件目录
var test_dir = @"E:\peanut\peanut_train\dataset\test";
DirectoryInfo dir = new DirectoryInfo(test_dir);
DirectoryInfo[] subDirs = dir.GetDirectories();
int count = 0;
DateTime startTime = DateTime.Now;
foreach (var folder in subDirs)
{
FileInfo[] files = folder.GetFiles();
//List<NDArray> listCells = new List<NDArray>();
foreach (var file in files)
{
var img = cv2.imread(file.FullName);
img = cv2.cvtColor(img, SharpCV.ColorConversionCodes.COLOR_BGR2RGB);
var x = np.expand_dims(img, axis: 0);
x = x / 255.0f;
var preds = model.predict(x);
//print(preds);
var rs = tf.arg_max(preds, 1);
count++;
//var rs = np.argmax(preds,axis:1);
//print(rs.numpy()[0]);
}
}
DateTime endTime = DateTime.Now;
TimeSpan span = endTime.Subtract(startTime);
print("共耗时:", span.Seconds, "处理图片:", count);
` I run the code , python's code cost 27s with gpu, and .net cost 40s,why? How to fix it?
Can you retry v0.60.5?
I just did some experiment on my current C# code. I'm doing reinforcement learning that alternate between practice (lots of cpu computation and lots of prediction with the model) and training (dataprep and fit) With version v0.40.1 I tried the CPU redist vs the GPU redist on exactly the same code. I believe the dataset and the model are small enough to fit into GPU memory CPU redist : Practice 2.49h Train 5.88m GPU redist : Practice 3.63h Train 9.21m
The GPU redist is 50% slower even for training. I will try to do the same with v0.60.5
Ok just did same test with v.60.5 CPU redist : Practice 4.09h Train 8.05m GPU redist : Practice 4.4h Train 6.55m
So for the prediction part, GPU is 9% slower but for training GPU is 20% faster than CPU Knowing that it seems that tensorflow is using all of my 12/24 cores cpu during the training, could we assume that the GPU version is 10-15x faster than a mono-core CPU ?
@CrimyTheBold It's not always, because there is I/O cost underlying. Do you have a small piece of code to demostrate the slow phenomenon?
the prediction part being slower is not surprising because I predict values one by one instead of a big batch (due to the nature of underlying algorythm, I cannot do otherwise). So I think, it is the worst case scenario in terms of I/O : for each prediction, the input has to be marshaled and transfered to the GPU, make a single forward pass, get the result back to the CPU and un-marshal it. It is not a problem for me because I intend to multithread the "Practice part" doing predictions with multiple cloned models on CPU and keep the training model on GPU.
I could build some code to test CPU vs GPU predictions with different batch size to see the difference, that could be interesting.
Is there a way to force a model on a specific device, like the Tensorflow in python ?
tf.device api is not implemented yet.
api/ function level comparison is more helpful.
model level is hard to find out root cause.