Returns a function that is used by the Saliency library to get gradients. Args: model: LIT model that is used to calculate actual gradients. model_input: the model input. image_field_key: the name (key) of the field in the model input that contains the image data with respect to
(
model: lit_model.Model,
model_input: JsonDict,
image_field_key: str,
grad_field_key: str,
grad_target_field_key: str,
grad_target_label: str,
)
| 140 | |
| 141 | |
| 142 | def get_call_model_func( |
| 143 | model: lit_model.Model, |
| 144 | model_input: JsonDict, |
| 145 | image_field_key: str, |
| 146 | grad_field_key: str, |
| 147 | grad_target_field_key: str, |
| 148 | grad_target_label: str, |
| 149 | ) -> CallModelFunction: |
| 150 | """Returns a function that is used by the Saliency library to get gradients. |
| 151 | |
| 152 | Args: |
| 153 | model: LIT model that is used to calculate actual gradients. |
| 154 | model_input: the model input. |
| 155 | image_field_key: the name (key) of the field in the model input that |
| 156 | contains the image data with respect to which the gradients should be |
| 157 | calculated. |
| 158 | grad_field_key: the name (key) of the field in the model output that |
| 159 | contains the computed gradients. |
| 160 | grad_target_field_key: the name (key) of the field in the model input that |
| 161 | is used to specify the label for which the gradients should be calculated. |
| 162 | If the value is None then it is a regression or a single class |
| 163 | classification model that has only one output. |
| 164 | grad_target_label: the value of the label that should be passed as the |
| 165 | `grad_target_field_name` value. |
| 166 | |
| 167 | Returns: |
| 168 | The function that should be passed to the Saliency library. |
| 169 | """ |
| 170 | |
| 171 | def call_model_func( |
| 172 | x_value_batch: np.ndarray, call_model_args, expected_keys: list[str] |
| 173 | ) -> dict[str, np.ndarray]: |
| 174 | """This function is called by the Saliency library to calculate gradients. |
| 175 | |
| 176 | Args: |
| 177 | x_value_batch: a batch of inputs with respect to which the gradients |
| 178 | should be calculated. |
| 179 | call_model_args: unused. |
| 180 | expected_keys: the list of expected keys that the return value should |
| 181 | contain. |
| 182 | |
| 183 | Returns: |
| 184 | A dictionary with gradients values for the batch. |
| 185 | """ |
| 186 | del call_model_args # Unused. |
| 187 | |
| 188 | # Iterate through the batch of saliency lib inputs and convert them to |
| 189 | # a batch acceptable by the LIT model. |
| 190 | model_inputs = [] |
| 191 | for x_value in x_value_batch: |
| 192 | updates = {image_field_key: x_value} |
| 193 | if grad_target_field_key is not None: |
| 194 | updates[grad_target_field_key] = grad_target_label |
| 195 | input_copy = lit_utils.make_modified_input( |
| 196 | model_input, updates, 'ImageSalience' |
| 197 | ) |
| 198 | model_inputs.append(input_copy) |
| 199 |