|
11 | 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | | - |
| 14 | +import json |
15 | 15 | from argparse import Namespace |
16 | 16 | from dataclasses import asdict, is_dataclass |
17 | 17 | from typing import Any, Dict, Mapping, MutableMapping, Optional, Union |
@@ -132,6 +132,23 @@ def _sanitize_params(params: Dict[str, Any]) -> Dict[str, Any]: |
132 | 132 | return params |
133 | 133 |
|
134 | 134 |
|
| 135 | +def _convert_json_serializable(params: Dict[str, Any]) -> Dict[str, Any]: |
| 136 | + """Convert non-serializable objects in params to string.""" |
| 137 | + return {k: str(v) if not _is_json_serializable(v) else v for k, v in params.items()} |
| 138 | + |
| 139 | + |
| 140 | +def _is_json_serializable(value: Any) -> bool: |
| 141 | + """Test whether a variable can be encoded as json.""" |
| 142 | + if value is None or isinstance(value, (bool, int, float, str, list, dict)): # fast path |
| 143 | + return True |
| 144 | + try: |
| 145 | + json.dumps(value) |
| 146 | + return True |
| 147 | + except (TypeError, OverflowError): |
| 148 | + # OverflowError is raised if number is too large to encode |
| 149 | + return False |
| 150 | + |
| 151 | + |
135 | 152 | def _add_prefix( |
136 | 153 | metrics: Mapping[str, Union[Tensor, float]], prefix: str, separator: str |
137 | 154 | ) -> Mapping[str, Union[Tensor, float]]: |
|
0 commit comments