Is evaluating the network thread-safe?

m2q: <p>I’m sorry if the answer to this question is obvious, but I’m not sure: If I have multiple parallel threads, and each thread has its own input tensor; will evaluating the net-&gt;forward() from each thread happen in parallel?</p>
<p>(Btw you people have done insanely good work with LibTorch!!! Keept it up)</p>

albanD: <p>Hi,</p>
<p>I think forward ops are but not backward.<br>
<a class="mention" href="/u/goldsborough">@goldsborough</a> should be able to give you a more decisive answer for libtorch.</p>

yf225: <p>I synced with <a class="mention" href="/u/goldsborough">@goldsborough</a> and here is the answer on thread safety:</p>
<p><code>net-&gt;forward()</code> is just an interface, and user could put whatever they want into that method. So technically, there’s no guarantee that it is thread safe, unless we know for sure that it doesn’t mutate any field of the <code>net</code> in place.</p>
<p>i.e. if <code>net</code> contains a <code>weight_</code> tensor, and one thread does <code>mul_()</code> and another reads from it at the same time, there’s a race. We could make the access to this <code>mul_()</code> call thread-safe by having a lock, but it’s something that user has to add on their own.</p>

m2q: <p>Thanks for the answer, I should’ve been more specific. I’m still not quite sure what you meant with <code>weight_</code>. Consider this super basic case:</p>
<pre><code class="lang-auto">torch::nn::Linear fc1 = {nullptr}; //assume this is initialied
torch::Tensor forward(torch::Tensor input) override 
{
        image = torch::softmax(fc1-&gt;forward(input));
        return image;
}
</code></pre>
<p>Now the thing I do in each thread would be something like</p>
<pre><code class="lang-auto">auto input_tensor = torch::tensor({1, 2, 3, 4, 5});
auto output_tensor =  net-&gt;forward(input_tensor);

// read data
float f = output_tensor.data&lt;float&gt;()[0]; //or something like that
</code></pre>
<p>If we assume the weights are fixed and no fancy training is going on, can I read from <code>output_tensor</code> safely? Just want to make sure</p>

yf225: <p>In that case, since <code>fc1</code> is not changed in <code>forward()</code>,  it should be safe to run <code>forward()</code> on multiple threads.</p>

m2q: <p>AWESOME! Thanks so much for the help, I love pytorch.</p>

Willem: <p>So just to be sure here: If I call</p>
<p>torch::NoGradGuard guard;<br>
torch::Tensor prediction = model-&gt;forward(features);</p>
<p>from multiple parallel threads. Are these inferences going to interfere with each other? The forward is defined as in the above code…</p>

yf225: <blockquote>
<p>Are these inferences going to interfere with each other?</p>
</blockquote>
<p>The short answer is no, unless your forward code explicitly writes to the same parameter / buffer without any mutex mechanism.</p>

Willem: <p>Thanks. As mentioned, my forward mechanism is just running through a bunch of linear layers and relu. So I should be good… Thanks!</p>

Willem: <p>Sorry, one more related question after running some more tests:</p>
<p>Multicore computations aren’t giving the factor speedup that I would expect. This could be caused by torch::NoGradGuard containing a Mutex mechanism. Does it?</p>
<p>Does the forward code on standard components (e.g. linear layers) contain mutexes?</p>
<p>Any other reason why this doesn’t seem to parallelize completely?</p>

albanD: <p>Hi,</p>
<p><code>torch::NoGradGuard</code> does not contain any mutex, only a thread local variable.</p>
<p>There are no mutexes that I know of in any of the regular layers.</p>
<p>You might want to control the number of threads used by open mp (corresponding to <a href="https://pytorch.org/docs/stable/torch.html#torch.get_num_threads">this</a> python api). If you do large enough ops, they will parallelize internally and might be trying to use too many ressources.</p>

Willem: <p>Hi Alban:</p>
<p>Thanks. I have a fairly small network, 3 layers (20 X 100, 100 X50,50 X30). Each time, I forward a single vector. It seems unlikely that it will paralellize this, right? (This is a RL setting, cpu-only.)</p>
<p>Still, my profiling shows that computing over 1 thread takes 10 seconds, while spawning 4 threads (with std::async) takes something like 8 seconds.</p>
<p>I have a 16 cpu-core system, so I cannot understand this.</p>
<p>Any ideas?</p>

albanD: <p>If you run your program while setting <code>OMP_NUM_THREADS=1 ./your_code</code> does it helps?</p>

Willem: <p>Not really; it slows down both the parallel and the nonparallel version of the code, but doesn’t result in the expected speedup of parallel vs nonparallel.</p>
<p>I have done some profiling using gprof. Program spends a lot of time in following three functions:</p>
<p>35% (of total):<br>
std::_Sp_counted_base&lt;(__gnu_cxx::<em>Lock_policy)2&gt;::<em>M_release()<br>
29%:<br>
c10::intrusive_ptr&lt;c10::TensorImpl, c10::UndefinedTensorImpl&gt;::reset</em>()<br>
11%:<br>
c10::intrusive_ptr&lt;c10::TensorImpl, c10::detail::intrusive_target_default_null_type&lt;&lt;<a>c10::TensorImpl</a> &gt;::reset</em>()</p>
<p>Following code uses the torch model:</p>
<pre><code>auto features = torch::empty({ 1,(long)(numFeats) });
		for (size_t i = 0; i &lt; numFeats; i++)
		{
			features[0][i] = mdp.GetFeature(state, i);
		}
		//Note that NoGradGuard was called elsewhere
		torch::Tensor prediction = model-&gt;forward(features);			
		std::vector&lt;float&gt; logprobs(prediction.data&lt;float&gt;(), prediction.data&lt;float&gt;() + prediction.numel());
</code></pre>
<p>Any idea what could be causing this? Maybe the memory allocations/dealloacations? Is it possible to reuse the same memory for this?</p>
<p>Definition of model:</p>
<pre><code>    torch::Tensor forward(torch::Tensor input) {
    {
	return torch::relu(linear3(torch::relu(linear2(torch::relu(linear1(input))))));
}
torch::nn::Linear linear1, linear2, linear3;</code></pre>

albanD: <p>Hi,</p>
<p>After asking to other people, <a href="https://github.com/pytorch/pytorch/pull/30340">this</a> should have greatly improved the multithreaded performances. You might want to try again with a build from master as it was merged about a week ago.</p>
<p>Also since pytorch used to be only used from python, multithreading was not a thing (because of the GIL mostly). So this has been fairly recent work in the core of pytorch but it should get better very soon.</p>
<p>Also if you have a model that behaves particularly bad and you can make a simple reproducible example, we can take a look into it.</p>

Willem: <p>Installing the newest PyTorch indeed did help, so that is great! Still, there seems to be significant (factor 2) slowdown if I run work in parallel, compared to running it serially.</p>
<p>I attach a reproducible example, where a lot of inference is done in parallel. (Note that the inference model is random here, to keep things simple. In production, this would be a pretrained model…) When the workers run in parallel, they take about 100 ms to complete. In series, they take about 45 ms. So, accounting for the fact that I run 16 cores, I get a 7* speedup from parallelization, where I would expect 14-16 times, since this is (or should be) completely CPU-bound. I believe this model is too small (and especially batch of 1) for PyTorch to do meaningful parallelization under the hood here.</p>
<p>Ps I hope I didn’t do any stupid things in implementation here. Any improvement to the implementation here is of course also very much appreciated!</p>
<hr>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicon.ico" class="site-icon" width="32" height="32">
      <a href="https://github.com/WillemvJ/parallelInference" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars3.githubusercontent.com/u/51718587?s=400&amp;v=4" class="thumbnail onebox-avatar" width="420" height="420">

<h3><a href="https://github.com/WillemvJ/parallelInference" target="_blank" rel="nofollow noopener">WillemvJ/parallelInference</a></h3>

<p>MWE parallel inference in pytorch c++ front-end. Contribute to WillemvJ/parallelInference development by creating an account on GitHub.</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


albanD: <p>Thanks for the code sample. This is indeed a very small model !</p>
<p>Can you try replacing <code>torch::NoGradGuard guard;</code> by <code>at::AutoNonVariableTypeMode non_var_type_mode(true);</code>? This is not supposed to be public api but might help for now.</p>

Willem: <p>Welcome. Note that this continues to be a problem when the model is a bit bigger (say 10 times bigger), though the problem becomes less pronounced.</p>
<p>I tried the replacement along the lines you suggest, it does not make a substantial difference. Maybe some benefit, but hard to measure. Parallel is still about factor 2 slower than serial.</p>

albanD: <p>One last thing as well is that the blas libraries (like mkl) have a tendency to aggressively use compute cores and I think that in a multithreaded environment, they can actually slow each other down.<br>
You definitely want to do batching if possible to avoid this.<br>
Will keep you updated if I get further ideas.</p>

Willem: <p>Thanks. Your idea that MKL might be behind this sounds plausible. I now compile with -skylake (not sure about exact relation to MKL). Will remove to see if it helps.</p>
<p>Also: do you have any idea if the compiler can be told to use one and only one core for each thread?</p>
<p>You mention that batching will help. Can you elaborate on how this will actually help? It seems that batching on each thread will only encourage the use of multiple cores, which will slow things down.<br>
__<br>
Compiling without --skylake support slows down both serial and parallel execution. Gap narrows a bit, but not much. I think your hypothesis that in parallel mode, there are less options to use multiple cores sounds very plausible. All in all, the code parallel code is 3 times faster since I started this thread, so thanks a lot for your help and responsiveness! (Still would love to hear how you would think that batching would help exactly…)</p>