def flatten(d: dict, _key_prefix: tuple = tuple()) -> dict:
    """Convert nested dict `d` to a flat dict with tuple keys.
    Input `_key_prefix` is prepended to the keys of the resulting dict,
    and is used internally for recursively flattening the dict."""
    result = {}
    for key, value in d.items():
        flat_key = _key_prefix + (key,)
        if isinstance(value, dict):
            result.update(flatten(value, flat_key))
        else:
            result[flat_key] = value
    return result