static FLAX_MODULE: GILOnceCell<Py<PyModule>> = GILOnceCell::new();
fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<HashMap<String, TensorView<'_>>> {
- let mut tensors = HashMap::new();
+ let mut tensors = HashMap::with_capacity(tensor_dict.len());
for (tensor_name, tensor_desc) in tensor_dict {
let mut shape: Option<Vec<usize>> = None;
let mut dtype: Option<Dtype> = None;
fn deserialize(py: Python, bytes: &[u8]) -> PyResult<Vec<(String, HashMap<String, PyObject>)>> {
let safetensor = SafeTensors::deserialize(bytes)
.map_err(|e| SafetensorError::new_err(format!("Error while deserializing: {e:?}")))?;
- let mut items = vec![];
- for (tensor_name, tensor) in safetensor.tensors() {
- let mut map = HashMap::new();
+ let tensors = safetensor.tensors();
+ let mut items = Vec::with_capacity(tensors.len());
+ for (tensor_name, tensor) in tensors {
let pyshape: PyObject = PyList::new(py, tensor.shape().iter()).into();
let pydtype: PyObject = format!("{:?}", tensor.dtype()).into_py(py);
let pydata: PyObject = PyByteArray::new(py, tensor.data()).into();
- map.insert("shape".to_string(), pyshape);
- map.insert("dtype".to_string(), pydtype);
- map.insert("data".to_string(), pydata);
+ let map = HashMap::from([
+ ("shape".to_string(), pyshape),
+ ("dtype".to_string(), pydtype),
+ ("data".to_string(), pydata),
+ ]);
items.push((tensor_name, map));
}
Ok(items)
/// The tensors returned are merely views and the data is not owned by this
/// structure.
pub fn tensors(&self) -> Vec<(String, TensorView<'_>)> {
- let mut tensors = vec![];
+ let mut tensors = Vec::with_capacity(self.metadata.index_map.len());
for (name, &index) in &self.metadata.index_map {
let info = &self.metadata.tensors[index];
let tensorview = TensorView {
metadata: Option<HashMap<String, String>>,
tensors: Vec<(String, TensorInfo)>,
) -> Result<Self, SafeTensorError> {
- let mut index_map = HashMap::new();
+ let mut index_map = HashMap::with_capacity(tensors.len());
let tensors: Vec<_> = tensors
.into_iter()
.sum::<usize>()
* dtype.size(); // 4
let all_data = vec![0; n];
- let mut metadata: HashMap<String, TensorView> = HashMap::new();
+ let mut metadata = HashMap::with_capacity(tensors_desc.len());
let mut offset = 0;
for (name, shape) in tensors_desc {
let n: usize = shape.iter().product();