Converts a Python object to a bfloat16 value. Returns true on success, returns false and reports a Python error on failure.
| 130 | // Converts a Python object to a bfloat16 value. Returns true on success, |
| 131 | // returns false and reports a Python error on failure. |
| 132 | bool CastToBfloat16(PyObject* arg, bfloat16* output) { |
| 133 | if (PyBfloat16_Check(arg)) { |
| 134 | *output = PyBfloat16_Bfloat16(arg); |
| 135 | return true; |
| 136 | } |
| 137 | if (PyFloat_Check(arg)) { |
| 138 | double d = PyFloat_AsDouble(arg); |
| 139 | if (PyErr_Occurred()) { |
| 140 | return false; |
| 141 | } |
| 142 | // TODO(phawkins): check for overflow |
| 143 | *output = bfloat16(d); |
| 144 | return true; |
| 145 | } |
| 146 | if (TfPyInt_Check(arg)) { |
| 147 | long l = TfPyInt_AsLong(arg); // NOLINT |
| 148 | if (PyErr_Occurred()) { |
| 149 | return false; |
| 150 | } |
| 151 | // TODO(phawkins): check for overflow |
| 152 | *output = bfloat16(static_cast<float>(l)); |
| 153 | return true; |
| 154 | } |
| 155 | if (PyArray_IsScalar(arg, Half)) { |
| 156 | Eigen::half f; |
| 157 | PyArray_ScalarAsCtype(arg, &f); |
| 158 | *output = bfloat16(f); |
| 159 | return true; |
| 160 | } |
| 161 | if (PyArray_IsScalar(arg, Float)) { |
| 162 | float f; |
| 163 | PyArray_ScalarAsCtype(arg, &f); |
| 164 | *output = bfloat16(f); |
| 165 | return true; |
| 166 | } |
| 167 | if (PyArray_IsScalar(arg, Double)) { |
| 168 | double f; |
| 169 | PyArray_ScalarAsCtype(arg, &f); |
| 170 | *output = bfloat16(f); |
| 171 | return true; |
| 172 | } |
| 173 | if (PyArray_IsZeroDim(arg)) { |
| 174 | Safe_PyObjectPtr ref; |
| 175 | PyArrayObject* arr = reinterpret_cast<PyArrayObject*>(arg); |
| 176 | if (PyArray_TYPE(arr) != npy_bfloat16) { |
| 177 | ref = make_safe(PyArray_Cast(arr, npy_bfloat16)); |
| 178 | if (PyErr_Occurred()) { |
| 179 | return false; |
| 180 | } |
| 181 | arg = ref.get(); |
| 182 | arr = reinterpret_cast<PyArrayObject*>(arg); |
| 183 | } |
| 184 | *output = *reinterpret_cast<bfloat16*>(PyArray_DATA(arr)); |
| 185 | return true; |
| 186 | } |
| 187 | return false; |
| 188 | } |
| 189 |
no test coverage detected