| 64 | } |
| 65 | |
| 66 | void init_random(nb::module_& parent_module) { |
| 67 | auto m = parent_module.def_submodule( |
| 68 | "random", |
| 69 | "mlx.core.random: functionality related to random number generation"); |
| 70 | |
| 71 | m.def("__getattr__", [&](nb::handle key) -> nb::object { |
| 72 | // Create random.state lazily to avoid initializing device during import. |
| 73 | if (nb::isinstance<nb::str>(key) && nb::cast<std::string>(key) == "state") { |
| 74 | return default_key().state(); |
| 75 | } |
| 76 | return nb::steal(PyErr_Format( |
| 77 | PyExc_AttributeError, |
| 78 | "Module 'random' has no attribute %R", |
| 79 | key.ptr())); |
| 80 | }); |
| 81 | m.def( |
| 82 | "seed", |
| 83 | [](uint64_t seed) { default_key().seed(seed); }, |
| 84 | "seed"_a, |
| 85 | R"pbdoc( |
| 86 | Seed the global PRNG. |
| 87 | |
| 88 | Args: |
| 89 | seed (int): Seed for the global PRNG. |
| 90 | )pbdoc"); |
| 91 | m.def( |
| 92 | "key", |
| 93 | &mx::random::key, |
| 94 | "seed"_a, |
| 95 | R"pbdoc( |
| 96 | Get a PRNG key from a seed. |
| 97 | |
| 98 | Args: |
| 99 | seed (int): Seed for the PRNG. |
| 100 | |
| 101 | Returns: |
| 102 | array: The PRNG key array. |
| 103 | )pbdoc"); |
| 104 | m.def( |
| 105 | "split", |
| 106 | nb::overload_cast<const mx::array&, int, mx::StreamOrDevice>( |
| 107 | &mx::random::split), |
| 108 | "key"_a, |
| 109 | "num"_a = 2, |
| 110 | "stream"_a = nb::none(), |
| 111 | nb::sig( |
| 112 | "def split(key: array, num: int = 2, stream: Union[None, Stream, Device] = None) -> array"), |
| 113 | R"pbdoc( |
| 114 | Split a PRNG key into sub keys. |
| 115 | |
| 116 | Args: |
| 117 | key (array): Input key to split. |
| 118 | num (int, optional): Number of sub keys. Default: ``2``. |
| 119 | |
| 120 | Returns: |
| 121 | array: The array of sub keys with ``num`` as its first dimension. |
| 122 | )pbdoc"); |
| 123 | m.def( |
no test coverage detected