MCPcopy Create free account
hub / github.com/PyO3/rust-numpy / half_bf16_works

Function half_bf16_works

tests/array.rs:605–644  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

603#[cfg(feature = "half")]
604#[test]
605fn half_bf16_works() {
606 Python::attach(|py| {
607 let np = py.eval(c_str!("__import__('numpy')"), None, None).unwrap();
608 // NumPy itself does not provide a `bfloat16` dtype itself,
609 // so we import ml_dtypes which does register such a dtype.
610 let mldt = py
611 .eval(c_str!("__import__('ml_dtypes')"), None, None)
612 .unwrap();
613 let locals = [("np", &np), ("mldt", &mldt)].into_py_dict(py).unwrap();
614
615 let array = py
616 .eval(
617 c_str!("np.array([[1, 2], [3, 4]], dtype='bfloat16')"),
618 None,
619 Some(&locals),
620 )
621 .unwrap()
622 .cast_into::<PyArray2<bf16>>()
623 .unwrap();
624
625 assert_eq!(
626 array.readonly().as_array(),
627 array![
628 [bf16::from_f32(1.0), bf16::from_f32(2.0)],
629 [bf16::from_f32(3.0), bf16::from_f32(4.0)]
630 ]
631 );
632
633 array
634 .readwrite()
635 .as_array_mut()
636 .map_inplace(|value| *value *= bf16::from_f32(2.0));
637
638 py_run!(
639 py,
640 array np,
641 "assert np.all(array == np.array([[2, 4], [6, 8]], dtype='bfloat16'))"
642 );
643 });
644}
645
646#[test]
647fn ascii_strings_with_explicit_dtype_works() {

Callers

nothing calls this directly

Calls 2

readwriteMethod · 0.80
as_array_mutMethod · 0.45

Tested by

no test coverage detected