MCPcopy Create free account
hub / github.com/apple/axlearn / rekey

Function rekey

axlearn/common/input_tf_data.py:1087–1142  ·  view source on GitHub ↗

Replace the feature keys according to mapping in `key_map`. Like seqio's rekey, except: 1. We allow for a configurable default value (used if the reference key is falsey--e.g. None--or if missing in the input example). 2. We optionally allow retaining keys not explic

(
    key_map: dict[str, str],
    default_value: Optional[Any] = "",
    retain_original_inputs: bool = False,
    separator: Optional[str] = None,
)

Source from the content-addressed store, hash-verified

1085
1086
1087def rekey(
1088 key_map: dict[str, str],
1089 default_value: Optional[Any] = "",
1090 retain_original_inputs: bool = False,
1091 separator: Optional[str] = None,
1092) -> DatasetToDatasetFn:
1093 """Replace the feature keys according to mapping in `key_map`.
1094
1095 Like seqio's rekey, except:
1096 1. We allow for a configurable default value
1097 (used if the reference key is falsey--e.g. None--or if missing in the input example).
1098 2. We optionally allow retaining keys not explicitly mentioned in the key-map.
1099 3. We optionally allow keys to be paths (if separator is provided).
1100
1101 Ref: <https://github.com/google/seqio/blob/9748501b/seqio/preprocessors.py#L30-L52>
1102
1103 Args:
1104 key_map: A dictionary mapping new keys to original keys.
1105 If falsey, return input (to match seqio behavior).
1106 default_value: Value to set new key to if old key-value doesn&#x27;t exist.
1107 If None, then we do not write the new key-value pair when missing an old key-value
1108 or when the provided reference key is falsey (to match seqio).
1109 retain_original_inputs: Whether to retain all the keys provided in the original input
1110 example (if False, only keys specified in the key map will be in the output).
1111 separator: An optional separator. If provided, all keys and values of `key_map` will be
1112 treated as paths and split by the separator.
1113
1114 Returns:
1115 A DatasetToDatasetFn, where each input example should be a dict.
1116 """
1117
1118 def has_path(x, path: str) -> bool:
1119 try:
1120 get_recursively(x, path, separator=separator)
1121 return True
1122 except KeyError:
1123 return False
1124
1125 def fn(example: dict[str, tf.Tensor]) -> dict[str, tf.Tensor]:
1126 if not key_map:
1127 return example
1128 output = example if retain_original_inputs else {}
1129 for new_key, old_key in key_map.items():
1130 if not old_key or not has_path(example, old_key):
1131 if default_value is not None:
1132 set_recursively(output, value=default_value, path=new_key, separator=separator)
1133 continue
1134 set_recursively(
1135 output,
1136 value=get_recursively(example, old_key, separator=separator),
1137 path=new_key,
1138 separator=separator,
1139 )
1140 return output
1141
1142 return seqio.map_over_dataset(fn)
1143
1144

Calls

no outgoing calls