pyo3: Bad multi-threaded parallel execution efficiency question.

🌍 Environment

  • Your operating system and version: Windows 10 20H2
  • Your python version: python 3.8.7
  • How did you install python (e.g. apt or pyenv)? Did you use a virtualenv?: from exe file / no.
  • Your Rust version (rustc --version): 1.51.0 (beta)
  • Your PyO3 version: 0.13.2
  • Have you tried using latest PyO3 master (replace version = "0.x.y" with git = "https://github.com/PyO3/pyo3")?: no

💥 Description

Hi everyone, I recently migrated some of my algorithms from python written to rust, the code is around 5,000 lines in total. The bad news is, I found that despite the excellent single-threaded execution efficiency, the pyo3 extension plugin in multi-threaded parallel mode does not execute very nicely. After releasing the GIL, running on my 8-core CPU, I was expecting a 4-8x speedup, but the actual speedup was only 2x.

I’m cautiously assuming this is caused by the type conversions between python and rust (convert python lists into rust vectors and then convert back) are all being executed under the GIL, this may be related to the fact that the data type I passed in was som ralatively long two-dimensional python lists. I would like to ask if this situation can be improved (the low-efficiency may be caused by my wrong calling method), or if it is my requirements that make it can not improve at all.

Minimum Implementation

lib.rs: It accepts a M by N matrix and returns after each item +1. The algorithm is much more complex in real production.

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

fn multithread_logic<const N:usize>(matrix: Vec<[f64;N]>
) -> Vec<Vec<f64>> {
    let height = matrix.len() ;
    let width = N;
    let mut result = Vec::new();
    for i in 0..height{
        let mut row:Vec<f64> = Vec::new();
        for j in 0..width {
            row.push(matrix[i][j] + 1.0);
        }
        result.push(row);
    }
    result
}

#[pyfunction]
fn multithread(
    py: Python,
    matrix: Vec<[f64;32]>,
) -> Vec<Vec<f64>> {
    py.allow_threads(|| multithread_logic(matrix))
}

#[pymodule]
fn testlib(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(multithread, m)?)?;
    Ok(())
}

call.py: Uses a simple way to compare the speed of single-thread and multi-threaded execution speed. Time increases linearly in the actual execution, I’d like to know if this is due to my mismanagement of GIL.

import testlib
import time
import threading

matrix = [list(range(32)) for _ in range(2000)]

def single_thread(matrix):
    for i in range(1000):
        testlib.multithread(matrix)

st_time = time.time()
single_thread(matrix)
print(f"Single thread time: {time.time() - st_time} s")

st_time = time.time()
threads = []
for _ in range(8):
    threads.append(threading.Thread(target = single_thread , args = (matrix,)))
for _ in threads:
    _.start()
for _ in threads:
    _.join()
print(f"Multi-threaded time: {time.time() - st_time} s")

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 22 (13 by maintainers)

Most upvoted comments

unless using numpy, this is not a problem that can be optimized at the user level at this stage.

This is exactly the right statement. On every function execution there’s a huge amount of copying that is being done here, making lots of new list and int objects. And the conversion code can only ever run in a single thread at a time because it is making Python objects (and so must hold the GIL).

There are performance improvements that can be made here (e.g. #1308), however this will always be quite inefficient.

A simple example showing use of numpy, which avoids all the copying / Python objects, is significantly faster:

use numpy::PyArray2;
use pyo3::prelude::*;
use pyo3::{wrap_pyfunction, PyNativeType};

use ndarray::{ArrayView2, Array2};

fn multithread_logic(matrix: ArrayView2<f64>) -> Array2<f64> {
    let mut result = matrix.into_owned();
    result.iter_mut().for_each(|x| *x += 1.0);
    result
}

#[pyfunction]
fn multithread(
    matrix: &PyArray2<f64>,
) -> &PyArray2<f64> {
    let py = matrix.py();
    let readonly = matrix.readonly();
    let arr = readonly.as_array();
    PyArray2::from_owned_array(py, py.allow_threads(|| multithread_logic(arr)))
}

#[pymodule]
fn testlib(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(multithread, m)?)?;
    Ok(())
}

Result of execution on my machine:

Single thread time: 0.03507590293884277 s
Multi-threaded time: 0.2570936679840088 s

If you can’t use numpy, then I suggest you make #[pyclass] structs which contain the Vec data you wish to work with. This way the data can always be owned by Rust and you won’t have to pay the huge copying cost.

Yes, multiprocessing has a lot of overhead because it must copy memory between processes to communicate.

Regarding the #[pyclass] solution, if you keep your rows in #[pyclass] structs then you won’t need to allocate new memory all the time. This can save you needing to do lots of expensive copying.

However, #[pyclass] structs can only be edited with the GIL held, so it may complicate your ability to do multithreading.

You might be able to do something like this, for example:

#[pyclass]
struct MyValues {
    x: i32
}

#[pyfunction]
fn modify_myvalues(py: Python, values: Vec<PyRefMut<MyValue>>) {
    let values_mut: Vec<&mut MyValue> = values.iter_mut().map(|pyref| &mut *pyref).collect();
    py.allow_threads(|| values_mut.iter_mut().for_each(|value| value.x += 1));
}

Since your input type is a matrix of fixed width (assuming 32), convert your code to use Vec<f64> and iterate in chunk (of size 32) instead of Vec<Vec<f64>> could be faster due to less memory allocations when doing type conversions.

Since you are using the nightly Rust compiler, try enable the nightly feature on pyo3 to see if it make a difference.

See https://pyo3.rs/v0.13.2/features.html#nightly

It doesn’t seem to make it faster but actually slow it down a little. Optimized this a little in https://github.com/PyO3/pyo3/pull/1502