python_code
stringlengths
0
229k
#!/usr/bin/env python3 from typing import Any, Callable, List, Tuple, Union import torch from captum._utils.common import _format_output from captum._utils.gradient import _forward_layer_eval from captum._utils.typing import ModuleOrModuleList from captum.attr._utils.attribution import LayerAttribution from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerActivation(LayerAttribution): r""" Computes activation of selected layer for given input. """ def __init__( self, forward_func: Callable, layer: ModuleOrModuleList, device_ids: Union[None, List[int]] = None, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module or list of torch.nn.Module): Layer or layers for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. If multiple layers are provided, attributions are returned as a list, each element corresponding to the activations of the corresponding layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], additional_forward_args: Any = None, attribute_to_layer_input: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer activation is computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False Returns: *Tensor* or *tuple[Tensor, ...]* or list of **attributions**: - **attributions** (*Tensor*, *tuple[Tensor, ...]*, or *list*): Activation of each neuron in given layer output. Attributions will always be the same size as the output of the given layer. Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. If multiple layers are provided, attributions are returned as a list, each element corresponding to the activations of the corresponding layer. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> layer_act = LayerActivation(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes layer activation. >>> # attribution is layer output, with size Nx12x32x32 >>> attribution = layer_cond.attribute(input) """ with torch.no_grad(): layer_eval = _forward_layer_eval( self.forward_func, inputs, self.layer, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) if isinstance(self.layer, Module): return _format_output(len(layer_eval) > 1, layer_eval) else: return [ _format_output(len(single_layer_eval) > 1, single_layer_eval) for single_layer_eval in layer_eval ] @property def multiplies_by_inputs(self): return True
#!/usr/bin/env python3 import typing from typing import Any, Callable, List, Tuple, Union import torch from captum._utils.common import ( _expand_additional_forward_args, _expand_target, _format_additional_forward_args, _format_output, ) from captum._utils.gradient import compute_layer_gradients_and_eval from captum._utils.typing import BaselineType, Literal, TargetType from captum.attr._utils.approximation_methods import approximation_parameters from captum.attr._utils.attribution import GradientAttribution, LayerAttribution from captum.attr._utils.batching import _batch_attribution from captum.attr._utils.common import ( _format_input_baseline, _reshape_and_sum, _validate_input, ) from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerConductance(LayerAttribution, GradientAttribution): r""" Computes conductance with respect to the given layer. The returned output is in the shape of the layer's output, showing the total conductance of each hidden layer neuron. The details of the approach can be found here: https://arxiv.org/abs/1805.12233 https://arxiv.org/abs/1807.09946 Note that this provides the total conductance of each neuron in the layer's output. To obtain the breakdown of a neuron's conductance by input features, utilize NeuronConductance instead, and provide the target neuron index. """ def __init__( self, forward_func: Callable, layer: Module, device_ids: Union[None, List[int]] = None, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module): Layer for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) GradientAttribution.__init__(self, forward_func) def has_convergence_delta(self) -> bool: return True @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, *, return_convergence_delta: Literal[True], attribute_to_layer_input: bool = False, ) -> Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor]: ... @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, return_convergence_delta: Literal[False] = False, attribute_to_layer_input: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...]]: ... @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[ None, int, float, Tensor, Tuple[Union[int, float, Tensor], ...] ] = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer conductance is computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. baselines (scalar, Tensor, tuple of scalar, or Tensor, optional): Baselines define the starting point from which integral is computed and can be provided as: - a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs. - a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor. - a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs' tuple can be: - either a tensor with matching dimensions to corresponding tensor in the inputs' tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor. - or a scalar, corresponding to a tensor in the inputs' tuple. This scalar value is broadcasted for corresponding input tensor. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of `n_steps` along the integrated path. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None n_steps (int, optional): The number of steps used by the approximation method. Default: 50. method (str, optional): Method for approximating the integral, one of `riemann_right`, `riemann_left`, `riemann_middle`, `riemann_trapezoid` or `gausslegendre`. Default: `gausslegendre` if no method is provided. internal_batch_size (int, optional): Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to 2 * #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer inputs, otherwise it will be computed with respect to layer outputs. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Conductance of each neuron in given layer input or output. Attributions will always be the same size as the input or output of the given layer, depending on whether we attribute to the inputs or outputs of the layer which is decided by the input flag `attribute_to_layer_input`. Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. - **delta** (*Tensor*, returned if return_convergence_delta=True): The difference between the total approximated and true conductance. This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must equal the total sum of the attributions. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of examples in inputs. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> layer_cond = LayerConductance(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes layer conductance for class 3. >>> # attribution size matches layer output, Nx12x32x32 >>> attribution = layer_cond.attribute(input, target=3) """ inputs, baselines = _format_input_baseline(inputs, baselines) _validate_input(inputs, baselines, n_steps, method) num_examples = inputs[0].shape[0] if internal_batch_size is not None: num_examples = inputs[0].shape[0] attrs = _batch_attribution( self, num_examples, internal_batch_size, n_steps + 1, include_endpoint=True, inputs=inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, method=method, attribute_to_layer_input=attribute_to_layer_input, ) else: attrs = self._attribute( inputs=inputs, baselines=baselines, target=target, additional_forward_args=additional_forward_args, n_steps=n_steps, method=method, attribute_to_layer_input=attribute_to_layer_input, ) is_layer_tuple = isinstance(attrs, tuple) attributions = attrs if is_layer_tuple else (attrs,) if return_convergence_delta: start_point, end_point = baselines, inputs delta = self.compute_convergence_delta( attributions, start_point, end_point, target=target, additional_forward_args=additional_forward_args, ) return _format_output(is_layer_tuple, attributions), delta return _format_output(is_layer_tuple, attributions) def _attribute( self, inputs: Tuple[Tensor, ...], baselines: Tuple[Union[Tensor, int, float], ...], target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", attribute_to_layer_input: bool = False, step_sizes_and_alphas: Union[None, Tuple[List[float], List[float]]] = None, ) -> Union[Tensor, Tuple[Tensor, ...]]: num_examples = inputs[0].shape[0] if step_sizes_and_alphas is None: # Retrieve scaling factors for specified approximation method step_sizes_func, alphas_func = approximation_parameters(method) alphas = alphas_func(n_steps + 1) else: _, alphas = step_sizes_and_alphas # Compute scaled inputs from baseline to final input. scaled_features_tpl = tuple( torch.cat( [baseline + alpha * (input - baseline) for alpha in alphas], dim=0 ).requires_grad_() for input, baseline in zip(inputs, baselines) ) additional_forward_args = _format_additional_forward_args( additional_forward_args ) # apply number of steps to additional forward args # currently, number of steps is applied only to additional forward arguments # that are nd-tensors. It is assumed that the first dimension is # the number of batches. # dim -> (#examples * #steps x additional_forward_args[0].shape[1:], ...) input_additional_args = ( _expand_additional_forward_args(additional_forward_args, n_steps + 1) if additional_forward_args is not None else None ) expanded_target = _expand_target(target, n_steps + 1) # Conductance Gradients - Returns gradient of output with respect to # hidden layer and hidden layer evaluated at each input. (layer_gradients, layer_evals,) = compute_layer_gradients_and_eval( forward_fn=self.forward_func, layer=self.layer, inputs=scaled_features_tpl, additional_forward_args=input_additional_args, target_ind=expanded_target, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) # Compute differences between consecutive evaluations of layer_eval. # This approximates the total input gradient of each step multiplied # by the step size. grad_diffs = tuple( layer_eval[num_examples:] - layer_eval[:-num_examples] for layer_eval in layer_evals ) # Element-wise multiply gradient of output with respect to hidden layer # and summed gradients with respect to input (chain rule) and sum # across stepped inputs. attributions = tuple( _reshape_and_sum( grad_diff * layer_gradient[:-num_examples], n_steps, num_examples, layer_eval.shape[1:], ) for layer_gradient, layer_eval, grad_diff in zip( layer_gradients, layer_evals, grad_diffs ) ) return _format_output(len(attributions) > 1, attributions) @property def multiplies_by_inputs(self): return True
#!/usr/bin/env python3 from typing import Any, Callable, List, Tuple, Union import torch import torch.nn.functional as F from captum._utils.common import ( _format_additional_forward_args, _format_output, _format_tensor_into_tuples, ) from captum._utils.gradient import compute_layer_gradients_and_eval from captum._utils.typing import TargetType from captum.attr._utils.attribution import GradientAttribution, LayerAttribution from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerGradCam(LayerAttribution, GradientAttribution): r""" Computes GradCAM attribution for chosen layer. GradCAM is designed for convolutional neural networks, and is usually applied to the last convolutional layer. GradCAM computes the gradients of the target output with respect to the given layer, averages for each output channel (dimension 2 of output), and multiplies the average gradient for each channel by the layer activations. The results are summed over all channels. Note that in the original GradCAM algorithm described in the paper, ReLU is applied to the output, returning only non-negative attributions. For providing more flexibility to the user, we choose to not perform the ReLU internally by default and return the sign information. To match the original GradCAM algorithm, it is necessary to pass the parameter relu_attributions=True to apply ReLU on the final attributions or alternatively only visualize the positive attributions. Note: this procedure sums over the second dimension (# of channels), so the output of GradCAM attributions will have a second dimension of 1, but all other dimensions will match that of the layer output. GradCAM attributions are generally upsampled and can be viewed as a mask to the input, since a convolutional layer output generally matches the input image spatially. This upsampling can be performed using LayerAttribution.interpolate, as shown in the example below. More details regarding the GradCAM method can be found in the original paper here: https://arxiv.org/abs/1610.02391 """ def __init__( self, forward_func: Callable, layer: Module, device_ids: Union[None, List[int]] = None, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module): Layer for which attributions are computed. Output size of attribute matches this layer's output dimensions, except for dimension 2, which will be 1, since GradCAM sums over channels. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) GradientAttribution.__init__(self, forward_func) @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, attribute_to_layer_input: bool = False, relu_attributions: bool = False, attr_dim_summation: bool = True, ) -> Union[Tensor, Tuple[Tensor, ...]]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None attribute_to_layer_input (bool, optional): Indicates whether to compute the attributions with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to the layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the outputs of internal layers, depending on whether we attribute to the input or output, are single tensors. Support for multiple tensors will be added later. Default: False relu_attributions (bool, optional): Indicates whether to apply a ReLU operation on the final attribution, returning only non-negative attributions. Setting this flag to True matches the original GradCAM algorithm, otherwise, by default, both positive and negative attributions are returned. Default: False attr_dim_summation (bool, optional): Indicates whether to sum attributions along dimension 1 (usually channel). The default (True) means to sum along dimension 1. Default: True Returns: *Tensor* or *tuple[Tensor, ...]* of **attributions**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Attributions based on GradCAM method. Attributions will be the same size as the output of the given layer, except for dimension 2, which will be 1 due to summing over channels. Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains a layer conv4, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx50x8x8. >>> # It is the last convolution layer, which is the recommended >>> # use case for GradCAM. >>> net = ImageClassifier() >>> layer_gc = LayerGradCam(net, net.conv4) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes layer GradCAM for class 3. >>> # attribution size matches layer output except for dimension >>> # 1, so dimensions of attr would be Nx1x8x8. >>> attr = layer_gc.attribute(input, 3) >>> # GradCAM attributions are often upsampled and viewed as a >>> # mask to the input, since the convolutional layer output >>> # spatially matches the original input image. >>> # This can be done with LayerAttribution's interpolate method. >>> upsampled_attr = LayerAttribution.interpolate(attr, (32, 32)) """ inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args( additional_forward_args ) # Returns gradient of output with respect to # hidden layer and hidden layer evaluated at each input. layer_gradients, layer_evals = compute_layer_gradients_and_eval( self.forward_func, self.layer, inputs, target, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) summed_grads = tuple( torch.mean( layer_grad, dim=tuple(x for x in range(2, len(layer_grad.shape))), keepdim=True, ) if len(layer_grad.shape) > 2 else layer_grad for layer_grad in layer_gradients ) if attr_dim_summation: scaled_acts = tuple( torch.sum(summed_grad * layer_eval, dim=1, keepdim=True) for summed_grad, layer_eval in zip(summed_grads, layer_evals) ) else: scaled_acts = tuple( summed_grad * layer_eval for summed_grad, layer_eval in zip(summed_grads, layer_evals) ) if relu_attributions: scaled_acts = tuple(F.relu(scaled_act) for scaled_act in scaled_acts) return _format_output(len(scaled_acts) > 1, scaled_acts)
#!/usr/bin/env python3 from typing import Any, Callable, List, Tuple, Union from captum._utils.common import ( _format_additional_forward_args, _format_output, _format_tensor_into_tuples, ) from captum._utils.gradient import compute_layer_gradients_and_eval from captum._utils.typing import ModuleOrModuleList, TargetType from captum.attr._utils.attribution import GradientAttribution, LayerAttribution from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerGradientXActivation(LayerAttribution, GradientAttribution): r""" Computes element-wise product of gradient and activation for selected layer on given inputs. """ def __init__( self, forward_func: Callable, layer: ModuleOrModuleList, device_ids: Union[None, List[int]] = None, multiply_by_inputs: bool = True, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module or list of torch.nn.Module): Layer or layers for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. If multiple layers are provided, attributions are returned as a list, each element corresponding to the attributions of the corresponding layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in, then this type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of layer gradient x activation, if `multiply_by_inputs` is set to True, final sensitivity scores are being multiplied by layer activations for inputs. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) GradientAttribution.__init__(self, forward_func) self._multiply_by_inputs = multiply_by_inputs @property def multiplies_by_inputs(self): return self._multiply_by_inputs @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, attribute_to_layer_input: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Default: False Returns: *Tensor* or *tuple[Tensor, ...]* or list of **attributions**: - **attributions** (*Tensor*, *tuple[Tensor, ...]*, or *list*): Product of gradient and activation for each neuron in given layer output. Attributions will always be the same size as the output of the given layer. Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. If multiple layers are provided, attributions are returned as a list, each element corresponding to the activations of the corresponding layer. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> layer_ga = LayerGradientXActivation(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes layer activation x gradient for class 3. >>> # attribution size matches layer output, Nx12x32x32 >>> attribution = layer_ga.attribute(input, 3) """ inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args( additional_forward_args ) # Returns gradient of output with respect to # hidden layer and hidden layer evaluated at each input. layer_gradients, layer_evals = compute_layer_gradients_and_eval( self.forward_func, self.layer, inputs, target, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) if isinstance(self.layer, Module): return _format_output( len(layer_evals) > 1, self.multiply_gradient_acts(layer_gradients, layer_evals), ) else: return [ _format_output( len(layer_evals[i]) > 1, self.multiply_gradient_acts(layer_gradients[i], layer_evals[i]), ) for i in range(len(self.layer)) ] def multiply_gradient_acts( self, gradients: Tuple[Tensor, ...], evals: Tuple[Tensor, ...] ) -> Tuple[Tensor, ...]: return tuple( single_gradient * single_eval if self.multiplies_by_inputs else single_gradient for single_gradient, single_eval in zip(gradients, evals) )
#!/usr/bin/env python3 import typing from typing import Any, Callable, cast, List, Tuple, Union import numpy as np import torch from captum._utils.gradient import _forward_layer_eval, compute_layer_gradients_and_eval from captum._utils.typing import Literal, TargetType, TensorOrTupleOfTensorsGeneric from captum.attr._core.gradient_shap import _scale_input from captum.attr._core.noise_tunnel import NoiseTunnel from captum.attr._utils.attribution import GradientAttribution, LayerAttribution from captum.attr._utils.common import ( _compute_conv_delta_and_format_attrs, _format_callable_baseline, _format_input_baseline, ) from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerGradientShap(LayerAttribution, GradientAttribution): r""" Implements gradient SHAP for layer based on the implementation from SHAP's primary author. For reference, please, view: https://github.com/slundberg/shap\ #deep-learning-example-with-gradientexplainer-tensorflowkeraspytorch-models A Unified Approach to Interpreting Model Predictions https://papers.nips.cc/paper\ 7062-a-unified-approach-to-interpreting-model-predictions GradientShap approximates SHAP values by computing the expectations of gradients by randomly sampling from the distribution of baselines/references. It adds white noise to each input sample `n_samples` times, selects a random baseline from baselines' distribution and a random point along the path between the baseline and the input, and computes the gradient of outputs with respect to selected random points in chosen `layer`. The final SHAP values represent the expected values of `gradients * (layer_attr_inputs - layer_attr_baselines)`. GradientShap makes an assumption that the input features are independent and that the explanation model is linear, meaning that the explanations are modeled through the additive composition of feature effects. Under those assumptions, SHAP value can be approximated as the expectation of gradients that are computed for randomly generated `n_samples` input samples after adding gaussian noise `n_samples` times to each input for different baselines/references. In some sense it can be viewed as an approximation of integrated gradients by computing the expectations of gradients for different baselines. Current implementation uses Smoothgrad from :class:`.NoiseTunnel` in order to randomly draw samples from the distribution of baselines, add noise to input samples and compute the expectation (smoothgrad). """ def __init__( self, forward_func: Callable, layer: Module, device_ids: Union[None, List[int]] = None, multiply_by_inputs: bool = True, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module): Layer for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in, then this type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of layer gradient shap, if `multiply_by_inputs` is set to True, the sensitivity scores for scaled inputs are being multiplied by layer activations for inputs - layer activations for baselines. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) GradientAttribution.__init__(self, forward_func) self._multiply_by_inputs = multiply_by_inputs @typing.overload def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: Union[TensorOrTupleOfTensorsGeneric, Callable], n_samples: int = 5, stdevs: Union[float, Tuple[float, ...]] = 0.0, target: TargetType = None, additional_forward_args: Any = None, *, return_convergence_delta: Literal[True], attribute_to_layer_input: bool = False, ) -> Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor]: ... @typing.overload def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: Union[TensorOrTupleOfTensorsGeneric, Callable], n_samples: int = 5, stdevs: Union[float, Tuple[float, ...]] = 0.0, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: Literal[False] = False, attribute_to_layer_input: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...]]: ... @log_usage() def attribute( self, inputs: TensorOrTupleOfTensorsGeneric, baselines: Union[TensorOrTupleOfTensorsGeneric, Callable], n_samples: int = 5, stdevs: Union[float, Tuple[float, ...]] = 0.0, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input which are used to compute SHAP attribution values for a given `layer`. If `forward_func` takes a single tensor as input, a single input tensor should be provided. If `forward_func` takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. baselines (Tensor, tuple[Tensor, ...], or Callable): Baselines define the starting point from which expectation is computed and can be provided as: - a single tensor, if inputs is a single tensor, with the first dimension equal to the number of examples in the baselines' distribution. The remaining dimensions must match with input tensor's dimension starting from the second dimension. - a tuple of tensors, if inputs is a tuple of tensors, with the first dimension of any tensor inside the tuple equal to the number of examples in the baseline's distribution. The remaining dimensions must match the dimensions of the corresponding input tensor starting from the second dimension. - callable function, optionally takes `inputs` as an argument and either returns a single tensor or a tuple of those. It is recommended that the number of samples in the baselines' tensors is larger than one. n_samples (int, optional): The number of randomly generated examples per sample in the input batch. Random examples are generated by adding gaussian random noise to each sample. Default: `5` if `n_samples` is not provided. stdevs (float or tuple of float, optional): The standard deviation of gaussian noise with zero mean that is added to each input in the batch. If `stdevs` is a single float value then that same value is used for all inputs. If it is a tuple, then it must have the same length as the inputs tuple. In this case, each stdev value in the stdevs tuple corresponds to the input with the same index in the inputs tuple. Default: 0.0 target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It can contain a tuple of ND tensors or any arbitrary python type of any shape. In case of the ND tensor the first dimension of the tensor must correspond to the batch size. It will be repeated for each `n_steps` for each randomly generated input sample. Note that the attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Attribution score computed based on GradientSHAP with respect to layer's input or output. Attributions will always be the same size as the provided layer's inputs or outputs, depending on whether we attribute to the inputs or outputs of the layer. Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. - **delta** (*Tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must be very close to the total sum of the attributions based on layer gradient SHAP. Delta is calculated for each example in the input after adding `n_samples` times gaussian noise to each of them. Therefore, the dimensionality of the deltas tensor is equal to the `number of examples in the input` * `n_samples` The deltas are ordered by each input example and `n_samples` noisy samples generated for it. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> layer_grad_shap = LayerGradientShap(net, net.linear1) >>> input = torch.randn(3, 3, 32, 32, requires_grad=True) >>> # choosing baselines randomly >>> baselines = torch.randn(20, 3, 32, 32) >>> # Computes gradient SHAP of output layer when target is equal >>> # to 0 with respect to the layer linear1. >>> # Attribution size matches to the size of the linear1 layer >>> attribution = layer_grad_shap.attribute(input, baselines, target=5) """ # since `baselines` is a distribution, we can generate it using a function # rather than passing it as an input argument baselines = _format_callable_baseline(baselines, inputs) assert isinstance(baselines[0], torch.Tensor), ( "Baselines distribution has to be provided in a form " "of a torch.Tensor {}.".format(baselines[0]) ) input_min_baseline_x_grad = LayerInputBaselineXGradient( self.forward_func, self.layer, device_ids=self.device_ids, multiply_by_inputs=self.multiplies_by_inputs, ) nt = NoiseTunnel(input_min_baseline_x_grad) attributions = nt.attribute.__wrapped__( nt, # self inputs, nt_type="smoothgrad", nt_samples=n_samples, stdevs=stdevs, draw_baseline_from_distrib=True, baselines=baselines, target=target, additional_forward_args=additional_forward_args, return_convergence_delta=return_convergence_delta, attribute_to_layer_input=attribute_to_layer_input, ) return attributions def has_convergence_delta(self) -> bool: return True @property def multiplies_by_inputs(self): return self._multiply_by_inputs class LayerInputBaselineXGradient(LayerAttribution, GradientAttribution): def __init__( self, forward_func: Callable, layer: Module, device_ids: Union[None, List[int]] = None, multiply_by_inputs: bool = True, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module): Layer for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in, then this type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of layer input minus baseline x gradient, if `multiply_by_inputs` is set to True, the sensitivity scores for scaled inputs are being multiplied by layer activations for inputs - layer activations for baselines. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) GradientAttribution.__init__(self, forward_func) self._multiply_by_inputs = multiply_by_inputs @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: Literal[False] = False, attribute_to_layer_input: bool = False, ) -> Union[Tensor, Tuple[Tensor, ...]]: ... @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, *, return_convergence_delta: Literal[True], attribute_to_layer_input: bool = False, ) -> Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor]: ... @log_usage() def attribute( # type: ignore self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[Tensor, Tuple[Tensor, ...]], target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: inputs, baselines = _format_input_baseline(inputs, baselines) rand_coefficient = torch.tensor( np.random.uniform(0.0, 1.0, inputs[0].shape[0]), device=inputs[0].device, dtype=inputs[0].dtype, ) input_baseline_scaled = tuple( _scale_input(input, baseline, rand_coefficient) for input, baseline in zip(inputs, baselines) ) grads, _ = compute_layer_gradients_and_eval( self.forward_func, self.layer, input_baseline_scaled, target, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) attr_baselines = _forward_layer_eval( self.forward_func, baselines, self.layer, additional_forward_args=additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) attr_inputs = _forward_layer_eval( self.forward_func, inputs, self.layer, additional_forward_args=additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) if self.multiplies_by_inputs: input_baseline_diffs = tuple( input - baseline for input, baseline in zip(attr_inputs, attr_baselines) ) attributions = tuple( input_baseline_diff * grad for input_baseline_diff, grad in zip(input_baseline_diffs, grads) ) else: attributions = grads return _compute_conv_delta_and_format_attrs( self, return_convergence_delta, attributions, baselines, inputs, additional_forward_args, target, cast(Union[Literal[True], Literal[False]], len(attributions) > 1), ) def has_convergence_delta(self) -> bool: return True @property def multiplies_by_inputs(self): return self._multiply_by_inputs
#!/usr/bin/env python3 from typing import Any, Callable, List, Tuple, Union import torch from captum._utils.common import ( _extract_device, _format_additional_forward_args, _format_output, _format_tensor_into_tuples, _run_forward, ) from captum._utils.gradient import _forward_layer_eval from captum._utils.typing import BaselineType, TargetType from captum.attr._core.feature_ablation import FeatureAblation from captum.attr._utils.attribution import LayerAttribution, PerturbationAttribution from captum.log import log_usage from torch import Tensor from torch.nn import Module from torch.nn.parallel.scatter_gather import scatter class LayerFeatureAblation(LayerAttribution, PerturbationAttribution): r""" A perturbation based approach to computing layer attribution, involving replacing values in the input / output of a layer with a given baseline / reference, and computing the difference in output. By default, each neuron (scalar input / output value) within the layer is replaced independently. Passing a layer mask allows grouping neurons to be ablated together. Each neuron in the group will be given the same attribution value equal to the change in target as a result of ablating the entire neuron group. """ def __init__( self, forward_func: Callable, layer: Module, device_ids: Union[None, List[int]] = None, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (torch.nn.Module): Layer for which attributions are computed. Output size of attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself (or otherwise has a device_ids attribute with the device ID list), then it is not necessary to provide this argument. """ LayerAttribution.__init__(self, forward_func, layer, device_ids) PerturbationAttribution.__init__(self, forward_func) @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], layer_baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, layer_mask: Union[None, Tensor, Tuple[Tensor, ...]] = None, attribute_to_layer_input: bool = False, perturbations_per_eval: int = 1, ) -> Union[Tensor, Tuple[Tensor, ...]]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. layer_baselines (scalar, Tensor, tuple of scalar, or Tensor, optional): Layer baselines define reference values which replace each layer input / output value when ablated. Layer baselines should be a single tensor with dimensions matching the input / output of the target layer (or broadcastable to match it), based on whether we are attributing to the input or output of the target layer. In the cases when `baselines` is not provided, we internally use zero as the baseline for each neuron. Default: None target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None layer_mask (Tensor or tuple[Tensor, ...], optional): layer_mask defines a mask for the layer, grouping elements of the layer input / output which should be ablated together. layer_mask should be a single tensor with dimensions matching the input / output of the target layer (or broadcastable to match it), based on whether we are attributing to the input or output of the target layer. layer_mask should contain integers in the range 0 to num_groups - 1, and all elements with the same value are considered to be in the same group. If None, then a layer mask is constructed which assigns each neuron within the layer as a separate group, which is ablated independently. Default: None attribute_to_layer_input (bool, optional): Indicates whether to compute the attributions with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer's inputs, otherwise it will be computed with respect to layer's outputs. Note that currently it is assumed that either the input or the output of the layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False perturbations_per_eval (int, optional): Allows ablation of multiple neuron (groups) to be processed simultaneously in one call to forward_fn. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. Default: 1 Returns: *Tensor* or *tuple[Tensor, ...]* of **attributions**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Attribution of each neuron in given layer input or output. Attributions will always be the same size as the input or output of the given layer, depending on whether we attribute to the inputs or outputs of the layer which is decided by the input flag `attribute_to_layer_input` Attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. Examples:: >>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x3x3. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # Defining LayerFeatureAblation interpreter >>> ablator = LayerFeatureAblation(net, net.conv1) >>> # Computes ablation attribution, ablating each of the 108 >>> # neurons independently. >>> attr = ablator.attribute(input, target=1) >>> # Alternatively, we may want to ablate neurons in groups, e.g. >>> # grouping all the layer outputs in the same row. >>> # This can be done by creating a layer mask as follows, which >>> # defines the groups of layer inputs / outouts, e.g.: >>> # +---+---+---+ >>> # | 0 | 0 | 0 | >>> # +---+---+---+ >>> # | 1 | 1 | 1 | >>> # +---+---+---+ >>> # | 2 | 2 | 2 | >>> # +---+---+---+ >>> # With this mask, all the 36 neurons in a row / channel are ablated >>> # simultaneously, and the attribution for each neuron in the same >>> # group (0 - 2) per example are the same. >>> # The attributions can be calculated as follows: >>> # layer mask has dimensions 1 x 3 x 3 >>> layer_mask = torch.tensor([[[0,0,0],[1,1,1], >>> [2,2,2]]]) >>> attr = ablator.attribute(input, target=1, >>> layer_mask=layer_mask) """ def layer_forward_func(*args): layer_length = args[-1] layer_input = args[:layer_length] original_inputs = args[layer_length:-1] device_ids = self.device_ids if device_ids is None: device_ids = getattr(self.forward_func, "device_ids", None) all_layer_inputs = {} if device_ids is not None: scattered_layer_input = scatter(layer_input, target_gpus=device_ids) for device_tensors in scattered_layer_input: all_layer_inputs[device_tensors[0].device] = device_tensors else: all_layer_inputs[layer_input[0].device] = layer_input def forward_hook(module, inp, out=None): device = _extract_device(module, inp, out) is_layer_tuple = ( isinstance(out, tuple) if out is not None else isinstance(inp, tuple) ) if device not in all_layer_inputs: raise AssertionError( "Layer input not placed on appropriate " "device. If using a DataParallel model, either provide the " "DataParallel model as forward_func or provide device ids" " to the constructor." ) if not is_layer_tuple: return all_layer_inputs[device][0] return all_layer_inputs[device] hook = None try: if attribute_to_layer_input: hook = self.layer.register_forward_pre_hook(forward_hook) else: hook = self.layer.register_forward_hook(forward_hook) eval = _run_forward(self.forward_func, original_inputs, target=target) finally: if hook is not None: hook.remove() return eval with torch.no_grad(): inputs = _format_tensor_into_tuples(inputs) additional_forward_args = _format_additional_forward_args( additional_forward_args ) layer_eval = _forward_layer_eval( self.forward_func, inputs, self.layer, additional_forward_args, device_ids=self.device_ids, attribute_to_layer_input=attribute_to_layer_input, ) layer_eval_len = (len(layer_eval),) all_inputs = ( (inputs + additional_forward_args + layer_eval_len) if additional_forward_args is not None else inputs + layer_eval_len ) ablator = FeatureAblation(layer_forward_func) layer_attribs = ablator.attribute.__wrapped__( ablator, # self layer_eval, baselines=layer_baselines, additional_forward_args=all_inputs, feature_mask=layer_mask, perturbations_per_eval=perturbations_per_eval, ) _attr = _format_output(len(layer_attribs) > 1, layer_attribs) return _attr
#!/usr/bin/env python3 import functools import warnings from typing import Any, Callable, List, overload, Tuple, Union import torch from captum._utils.common import ( _extract_device, _format_additional_forward_args, _format_outputs, ) from captum._utils.gradient import _forward_layer_eval, _run_forward from captum._utils.typing import BaselineType, Literal, ModuleOrModuleList, TargetType from captum.attr._core.integrated_gradients import IntegratedGradients from captum.attr._utils.attribution import GradientAttribution, LayerAttribution from captum.attr._utils.common import ( _format_input_baseline, _tensorize_baseline, _validate_input, ) from captum.log import log_usage from torch import Tensor from torch.nn.parallel.scatter_gather import scatter class LayerIntegratedGradients(LayerAttribution, GradientAttribution): r""" Layer Integrated Gradients is a variant of Integrated Gradients that assigns an importance score to layer inputs or outputs, depending on whether we attribute to the former or to the latter one. Integrated Gradients is an axiomatic model interpretability algorithm that attributes / assigns an importance score to each input feature by approximating the integral of gradients of the model's output with respect to the inputs along the path (straight line) from given baselines / references to inputs. Baselines can be provided as input arguments to attribute method. To approximate the integral we can choose to use either a variant of Riemann sum or Gauss-Legendre quadrature rule. More details regarding the integrated gradients method can be found in the original paper: https://arxiv.org/abs/1703.01365 """ def __init__( self, forward_func: Callable, layer: ModuleOrModuleList, device_ids: Union[None, List[int]] = None, multiply_by_inputs: bool = True, ) -> None: r""" Args: forward_func (Callable): The forward function of the model or any modification of it layer (ModuleOrModuleList): Layer or list of layers for which attributions are computed. For each layer the output size of the attribute matches this layer's input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to the attribution of each neuron in the input or output of this layer. Please note that layers to attribute on cannot be dependent on each other. That is, a subset of layers in `layer` cannot produce the inputs for another layer. For example, if your model is of a simple linked-list based graph structure (think nn.Sequence), e.g. x -> l1 -> l2 -> l3 -> output. If you pass in any one of those layers, you cannot pass in another due to the dependence, e.g. if you pass in l2 you cannot pass in l1 or l3. device_ids (list[int]): Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in, then this type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of layer integrated gradients, if `multiply_by_inputs` is set to True, final sensitivity scores are being multiplied by layer activations for inputs - layer activations for baselines. """ LayerAttribution.__init__(self, forward_func, layer, device_ids=device_ids) GradientAttribution.__init__(self, forward_func) self.ig = IntegratedGradients(forward_func, multiply_by_inputs) if isinstance(layer, list) and len(layer) > 1: warnings.warn( "Multiple layers provided. Please ensure that each layer is" "**not** solely dependent on the outputs of" "another layer. Please refer to the documentation for more" "detail." ) @overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType, target: TargetType, additional_forward_args: Any, n_steps: int, method: str, internal_batch_size: Union[None, int], return_convergence_delta: Literal[False], attribute_to_layer_input: bool, ) -> Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]]: ... @overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType, target: TargetType, additional_forward_args: Any, n_steps: int, method: str, internal_batch_size: Union[None, int], return_convergence_delta: Literal[True], attribute_to_layer_input: bool, ) -> Tuple[ Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]], Tensor, ]: ... @overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, ) -> Union[ Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]], Tuple[ Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]], Tensor, ], ]: ... @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, n_steps: int = 50, method: str = "gausslegendre", internal_batch_size: Union[None, int] = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, ) -> Union[ Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]], Tuple[ Union[Tensor, Tuple[Tensor, ...], List[Union[Tensor, Tuple[Tensor, ...]]]], Tensor, ], ]: r""" This method attributes the output of the model with given target index (in case it is provided, otherwise it assumes that output is a scalar) to layer inputs or outputs of the model, depending on whether `attribute_to_layer_input` is set to True or False, using the approach described above. In addition to that it also returns, if `return_convergence_delta` is set to True, integral approximation delta based on the completeness property of integrated gradients. Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer integrated gradients are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately. baselines (scalar, Tensor, tuple of scalar, or Tensor, optional): Baselines define the starting point from which integral is computed and can be provided as: - a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs. - a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor. - a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs' tuple can be: - either a tensor with matching dimensions to corresponding tensor in the inputs' tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor. - or a scalar, corresponding to a tensor in the inputs' tuple. This scalar value is broadcasted for corresponding input tensor. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of `n_steps` along the integrated path. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None n_steps (int, optional): The number of steps used by the approximation method. Default: 50. method (str, optional): Method for approximating the integral, one of `riemann_right`, `riemann_left`, `riemann_middle`, `riemann_trapezoid` or `gausslegendre`. Default: `gausslegendre` if no method is provided. internal_batch_size (int, optional): Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Integrated gradients with respect to `layer`'s inputs or outputs. Attributions will always be the same size and dimensionality as the input or output of the given layer, depending on whether we attribute to the inputs or outputs of the layer which is decided by the input flag `attribute_to_layer_input`. For a single layer, attributions are returned in a tuple if the layer inputs / outputs contain multiple tensors, otherwise a single tensor is returned. For multiple layers, attributions will always be returned as a list. Each element in this list will be equivalent to that of a single layer output, i.e. in the case that one layer, in the given layers, inputs / outputs multiple tensors: the corresponding output element will be a tuple of tensors. The ordering of the outputs will be the same order as the layers given in the constructor. - **delta** (*Tensor*, returned if return_convergence_delta=True): The difference between the total approximated and true integrated gradients. This is computed using the property that the total sum of forward_func(inputs) - forward_func(baselines) must equal the total sum of the integrated gradient. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of examples in inputs. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> lig = LayerIntegratedGradients(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes layer integrated gradients for class 3. >>> # attribution size matches layer output, Nx12x32x32 >>> attribution = lig.attribute(input, target=3) """ inps, baselines = _format_input_baseline(inputs, baselines) _validate_input(inps, baselines, n_steps, method) baselines = _tensorize_baseline(inps, baselines) additional_forward_args = _format_additional_forward_args( additional_forward_args ) def flatten_tuple(tup): return tuple( sum((list(x) if isinstance(x, (tuple, list)) else [x] for x in tup), []) ) if self.device_ids is None: self.device_ids = getattr(self.forward_func, "device_ids", None) inputs_layer = _forward_layer_eval( self.forward_func, inps, self.layer, device_ids=self.device_ids, additional_forward_args=additional_forward_args, attribute_to_layer_input=attribute_to_layer_input, ) # if we have one output if not isinstance(self.layer, list): inputs_layer = (inputs_layer,) num_outputs = [1 if isinstance(x, Tensor) else len(x) for x in inputs_layer] num_outputs_cumsum = torch.cumsum( torch.IntTensor([0] + num_outputs), dim=0 # type: ignore ) inputs_layer = flatten_tuple(inputs_layer) baselines_layer = _forward_layer_eval( self.forward_func, baselines, self.layer, device_ids=self.device_ids, additional_forward_args=additional_forward_args, attribute_to_layer_input=attribute_to_layer_input, ) baselines_layer = flatten_tuple(baselines_layer) # inputs -> these inputs are scaled def gradient_func( forward_fn: Callable, inputs: Union[Tensor, Tuple[Tensor, ...]], target_ind: TargetType = None, additional_forward_args: Any = None, ) -> Tuple[Tensor, ...]: if self.device_ids is None or len(self.device_ids) == 0: scattered_inputs = (inputs,) else: # scatter method does not have a precise enough return type in its # stub, so suppress the type warning. scattered_inputs = scatter( # type:ignore inputs, target_gpus=self.device_ids ) scattered_inputs_dict = { scattered_input[0].device: scattered_input for scattered_input in scattered_inputs } with torch.autograd.set_grad_enabled(True): def layer_forward_hook( module, hook_inputs, hook_outputs=None, layer_idx=0 ): device = _extract_device(module, hook_inputs, hook_outputs) is_layer_tuple = ( isinstance(hook_outputs, tuple) # hook_outputs is None if attribute_to_layer_input == True if hook_outputs is not None else isinstance(hook_inputs, tuple) ) if is_layer_tuple: return scattered_inputs_dict[device][ num_outputs_cumsum[layer_idx] : num_outputs_cumsum[ layer_idx + 1 ] ] return scattered_inputs_dict[device][num_outputs_cumsum[layer_idx]] hooks = [] try: layers = self.layer if not isinstance(layers, list): layers = [self.layer] for layer_idx, layer in enumerate(layers): hook = None # TODO: # Allow multiple attribute_to_layer_input flags for # each layer, i.e. attribute_to_layer_input[layer_idx] if attribute_to_layer_input: hook = layer.register_forward_pre_hook( functools.partial( layer_forward_hook, layer_idx=layer_idx ) ) else: hook = layer.register_forward_hook( functools.partial( layer_forward_hook, layer_idx=layer_idx ) ) hooks.append(hook) output = _run_forward( self.forward_func, tuple(), target_ind, additional_forward_args ) finally: for hook in hooks: if hook is not None: hook.remove() assert output[0].numel() == 1, ( "Target not provided when necessary, cannot" " take gradient with respect to multiple outputs." ) # torch.unbind(forward_out) is a list of scalar tensor tuples and # contains batch_size * #steps elements grads = torch.autograd.grad(torch.unbind(output), inputs) return grads self.ig.gradient_func = gradient_func all_inputs = ( (inps + additional_forward_args) if additional_forward_args is not None else inps ) attributions = self.ig.attribute.__wrapped__( # type: ignore self.ig, # self inputs_layer, baselines=baselines_layer, target=target, additional_forward_args=all_inputs, n_steps=n_steps, method=method, internal_batch_size=internal_batch_size, return_convergence_delta=False, ) # handle multiple outputs output: List[Tuple[Tensor, ...]] = [ tuple( attributions[ int(num_outputs_cumsum[i]) : int(num_outputs_cumsum[i + 1]) ] ) for i in range(len(num_outputs)) ] if return_convergence_delta: start_point, end_point = baselines, inps # computes approximation error based on the completeness axiom delta = self.compute_convergence_delta( attributions, start_point, end_point, additional_forward_args=additional_forward_args, target=target, ) return _format_outputs(isinstance(self.layer, list), output), delta return _format_outputs(isinstance(self.layer, list), output) def has_convergence_delta(self) -> bool: return True @property def multiplies_by_inputs(self): return self.ig.multiplies_by_inputs
#!/usr/bin/env python3 import typing from typing import Any, Callable, cast, Sequence, Tuple, Union import torch from captum._utils.common import ( _expand_target, _format_additional_forward_args, _format_baseline, _format_tensor_into_tuples, ExpansionTypes, ) from captum._utils.gradient import compute_layer_gradients_and_eval from captum._utils.typing import ( BaselineType, Literal, TargetType, TensorOrTupleOfTensorsGeneric, ) from captum.attr._core.deep_lift import DeepLift, DeepLiftShap from captum.attr._utils.attribution import LayerAttribution from captum.attr._utils.common import ( _call_custom_attribution_func, _compute_conv_delta_and_format_attrs, _format_callable_baseline, _tensorize_baseline, _validate_input, ) from captum.log import log_usage from torch import Tensor from torch.nn import Module class LayerDeepLift(LayerAttribution, DeepLift): r""" Implements DeepLIFT algorithm for the layer based on the following paper: Learning Important Features Through Propagating Activation Differences, Avanti Shrikumar, et. al. https://arxiv.org/abs/1704.02685 and the gradient formulation proposed in: Towards better understanding of gradient-based attribution methods for deep neural networks, Marco Ancona, et.al. https://openreview.net/pdf?id=Sy21R9JAW This implementation supports only Rescale rule. RevealCancel rule will be supported in later releases. Although DeepLIFT's(Rescale Rule) attribution quality is comparable with Integrated Gradients, it runs significantly faster than Integrated Gradients and is preferred for large datasets. Currently we only support a limited number of non-linear activations but the plan is to expand the list in the future. Note: As we know, currently we cannot access the building blocks, of PyTorch's built-in LSTM, RNNs and GRUs such as Tanh and Sigmoid. Nonetheless, it is possible to build custom LSTMs, RNNS and GRUs with performance similar to built-in ones using TorchScript. More details on how to build custom RNNs can be found here: https://pytorch.org/blog/optimizing-cuda-rnn-with-torchscript/ """ def __init__( self, model: Module, layer: Module, multiply_by_inputs: bool = True, ) -> None: r""" Args: model (nn.Module): The reference to PyTorch model instance. layer (torch.nn.Module): Layer for which attributions are computed. The size and dimensionality of the attributions corresponds to the size and dimensionality of the layer's input or output depending on whether we attribute to the inputs or outputs of the layer. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of Layer DeepLift, if `multiply_by_inputs` is set to True, final sensitivity scores are being multiplied by layer activations for inputs - layer activations for baselines. This flag applies only if `custom_attribution_func` is set to None. """ LayerAttribution.__init__(self, model, layer) DeepLift.__init__(self, model) self.model = model self._multiply_by_inputs = multiply_by_inputs # Ignoring mypy error for inconsistent signature with DeepLift @typing.overload # type: ignore def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: Literal[False] = False, attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[Tensor, Tuple[Tensor, ...]]: ... @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, *, return_convergence_delta: Literal[True], attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor]: ... @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: BaselineType = None, target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer attributions are computed. If model takes a single tensor as input, a single input tensor should be provided. If model takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately. baselines (scalar, Tensor, tuple of scalar, or Tensor, optional): Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided as: - a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs. - a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor. - a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs' tuple can be: - either a tensor with matching dimensions to corresponding tensor in the inputs' tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor. - or a scalar, corresponding to a tensor in the inputs' tuple. This scalar value is broadcasted for corresponding input tensor. In the cases when `baselines` is not provided, we internally use zero scalar corresponding to each input tensor. Default: None target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to model in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attribution with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer input, otherwise it will be computed with respect to layer output. Note that currently it is assumed that either the input or the output of internal layer, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False custom_attribution_func (Callable, optional): A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature: - custom_attribution_func(multipliers) - custom_attribution_func(multipliers, inputs) - custom_attribution_func(multipliers, inputs, baselines) In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, `multipliers`, `inputs` and `baselines` are provided in tuples of same length. `custom_attribution_func` returns a tuple of attribution tensors that have the same length as the `inputs`. Default: None Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Attribution score computed based on DeepLift's rescale rule with respect to layer's inputs or outputs. Attributions will always be the same size as the provided layer's inputs or outputs, depending on whether we attribute to the inputs or outputs of the layer. If the layer input / output is a single tensor, then just a tensor is returned; if the layer input / output has multiple tensors, then a corresponding tuple of tensors is returned. - **delta** (*Tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of model(inputs) - model(baselines) must equal the total sum of the attributions computed based on DeepLift's rescale rule. Delta is calculated per example, meaning that the number of elements in returned delta tensor is equal to the number of examples in input. Note that the logic described for deltas is guaranteed when the default logic for attribution computations is used, meaning that the `custom_attribution_func=None`, otherwise it is not guaranteed and depends on the specifics of the `custom_attribution_func`. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = LayerDeepLift(net, net.conv4) >>> input = torch.randn(1, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for conv4 layer and class 3. >>> attribution = dl.attribute(input, target=1) """ inputs = _format_tensor_into_tuples(inputs) baselines = _format_baseline(baselines, inputs) _validate_input(inputs, baselines) baselines = _tensorize_baseline(inputs, baselines) main_model_hooks = [] try: main_model_hooks = self._hook_main_model() self.model.apply( lambda mod: self._register_hooks( mod, attribute_to_layer_input=attribute_to_layer_input ) ) additional_forward_args = _format_additional_forward_args( additional_forward_args ) expanded_target = _expand_target( target, 2, expansion_type=ExpansionTypes.repeat ) wrapped_forward_func = self._construct_forward_func( self.model, (inputs, baselines), expanded_target, additional_forward_args, ) def chunk_output_fn(out: TensorOrTupleOfTensorsGeneric) -> Sequence: if isinstance(out, Tensor): return out.chunk(2) return tuple(out_sub.chunk(2) for out_sub in out) gradients, attrs = compute_layer_gradients_and_eval( wrapped_forward_func, self.layer, inputs, attribute_to_layer_input=attribute_to_layer_input, output_fn=lambda out: chunk_output_fn(out), ) attr_inputs = tuple(map(lambda attr: attr[0], attrs)) attr_baselines = tuple(map(lambda attr: attr[1], attrs)) gradients = tuple(map(lambda grad: grad[0], gradients)) if custom_attribution_func is None: if self.multiplies_by_inputs: attributions = tuple( (input - baseline) * gradient for input, baseline, gradient in zip( attr_inputs, attr_baselines, gradients ) ) else: attributions = gradients else: attributions = _call_custom_attribution_func( custom_attribution_func, gradients, attr_inputs, attr_baselines ) finally: # remove hooks from all activations self._remove_hooks(main_model_hooks) return _compute_conv_delta_and_format_attrs( self, return_convergence_delta, attributions, baselines, inputs, additional_forward_args, target, cast(Union[Literal[True], Literal[False]], len(attributions) > 1), ) @property def multiplies_by_inputs(self): return self._multiply_by_inputs class LayerDeepLiftShap(LayerDeepLift, DeepLiftShap): r""" Extends LayerDeepLift and DeepLiftShap algorithms and approximates SHAP values for given input `layer`. For each input sample - baseline pair it computes DeepLift attributions with respect to inputs or outputs of given `layer` averages resulting attributions across baselines. Whether to compute the attributions with respect to the inputs or outputs of the layer is defined by the input flag `attribute_to_layer_input`. More details about the algorithm can be found here: https://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf Note that the explanation model: 1. Assumes that input features are independent of one another 2. Is linear, meaning that the explanations are modeled through the additive composition of feature effects. Although, it assumes a linear model for each explanation, the overall model across multiple explanations can be complex and non-linear. """ def __init__( self, model: Module, layer: Module, multiply_by_inputs: bool = True, ) -> None: r""" Args: model (nn.Module): The reference to PyTorch model instance. layer (torch.nn.Module): Layer for which attributions are computed. The size and dimensionality of the attributions corresponds to the size and dimensionality of the layer's input or output depending on whether we attribute to the inputs or outputs of the layer. multiply_by_inputs (bool, optional): Indicates whether to factor model inputs' multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs' multiplier isn't factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104 In case of LayerDeepLiftShap, if `multiply_by_inputs` is set to True, final sensitivity scores are being multiplied by layer activations for inputs - layer activations for baselines This flag applies only if `custom_attribution_func` is set to None. """ LayerDeepLift.__init__(self, model, layer) DeepLiftShap.__init__(self, model, multiply_by_inputs) # Ignoring mypy error for inconsistent signature with DeepLiftShap @typing.overload # type: ignore def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[ Tensor, Tuple[Tensor, ...], Callable[..., Union[Tensor, Tuple[Tensor, ...]]] ], target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: Literal[False] = False, attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[Tensor, Tuple[Tensor, ...]]: ... @typing.overload def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[ Tensor, Tuple[Tensor, ...], Callable[..., Union[Tensor, Tuple[Tensor, ...]]] ], target: TargetType = None, additional_forward_args: Any = None, *, return_convergence_delta: Literal[True], attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor]: ... @log_usage() def attribute( self, inputs: Union[Tensor, Tuple[Tensor, ...]], baselines: Union[ Tensor, Tuple[Tensor, ...], Callable[..., Union[Tensor, Tuple[Tensor, ...]]] ], target: TargetType = None, additional_forward_args: Any = None, return_convergence_delta: bool = False, attribute_to_layer_input: bool = False, custom_attribution_func: Union[None, Callable[..., Tuple[Tensor, ...]]] = None, ) -> Union[ Tensor, Tuple[Tensor, ...], Tuple[Union[Tensor, Tuple[Tensor, ...]], Tensor] ]: r""" Args: inputs (Tensor or tuple[Tensor, ...]): Input for which layer attributions are computed. If model takes a single tensor as input, a single input tensor should be provided. If model takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately. baselines (Tensor, tuple[Tensor, ...], or Callable): Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided as: - a single tensor, if inputs is a single tensor, with the first dimension equal to the number of examples in the baselines' distribution. The remaining dimensions must match with input tensor's dimension starting from the second dimension. - a tuple of tensors, if inputs is a tuple of tensors, with the first dimension of any tensor inside the tuple equal to the number of examples in the baseline's distribution. The remaining dimensions must match the dimensions of the corresponding input tensor starting from the second dimension. - callable function, optionally takes `inputs` as an argument and either returns a single tensor or a tuple of those. It is recommended that the number of samples in the baselines' tensors is larger than one. target (int, tuple, Tensor, or list, optional): Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. Default: None additional_forward_args (Any, optional): If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to model in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None return_convergence_delta (bool, optional): Indicates whether to return convergence delta or not. If `return_convergence_delta` is set to True convergence delta will be returned in a tuple following attributions. Default: False attribute_to_layer_input (bool, optional): Indicates whether to compute the attributions with respect to the layer input or output. If `attribute_to_layer_input` is set to True then the attributions will be computed with respect to layer inputs, otherwise it will be computed with respect to layer outputs. Note that currently it assumes that both the inputs and outputs of internal layers are single tensors. Support for multiple tensors will be added later. Default: False custom_attribution_func (Callable, optional): A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature: - custom_attribution_func(multipliers) - custom_attribution_func(multipliers, inputs) - custom_attribution_func(multipliers, inputs, baselines) In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, `multipliers`, `inputs` and `baselines` are provided in tuples of same length. `custom_attribution_func` returns a tuple of attribution tensors that have the same length as the `inputs`. Default: None Returns: **attributions** or 2-element tuple of **attributions**, **delta**: - **attributions** (*Tensor* or *tuple[Tensor, ...]*): Attribution score computed based on DeepLift's rescale rule with respect to layer's inputs or outputs. Attributions will always be the same size as the provided layer's inputs or outputs, depending on whether we attribute to the inputs or outputs of the layer. Attributions are returned in a tuple based on whether the layer inputs / outputs are contained in a tuple from a forward hook. For standard modules, inputs of a single tensor are usually wrapped in a tuple, while outputs of a single tensor are not. - **delta** (*Tensor*, returned if return_convergence_delta=True): This is computed using the property that the total sum of model(inputs) - model(baselines) must be very close to the total sum of attributions computed based on approximated SHAP values using DeepLift's rescale rule. Delta is calculated for each example input and baseline pair, meaning that the number of elements in returned delta tensor is equal to the `number of examples in input` * `number of examples in baseline`. The deltas are ordered in the first place by input example, followed by the baseline. Note that the logic described for deltas is guaranteed when the default logic for attribution computations is used, meaning that the `custom_attribution_func=None`, otherwise it is not guaranteed and depends on the specifics of the `custom_attribution_func`. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = LayerDeepLiftShap(net, net.conv4) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # Computes shap values using deeplift for class 3. >>> attribution = dl.attribute(input, target=3) """ inputs = _format_tensor_into_tuples(inputs) baselines = _format_callable_baseline(baselines, inputs) assert isinstance(baselines[0], torch.Tensor) and baselines[0].shape[0] > 1, ( "Baselines distribution has to be provided in form of a torch.Tensor" " with more than one example but found: {}." " If baselines are provided in shape of scalars or with a single" " baseline example, `LayerDeepLift`" " approach can be used instead.".format(baselines[0]) ) # batch sizes inp_bsz = inputs[0].shape[0] base_bsz = baselines[0].shape[0] ( exp_inp, exp_base, exp_target, exp_addit_args, ) = DeepLiftShap._expand_inputs_baselines_targets( self, baselines, inputs, target, additional_forward_args ) attributions = LayerDeepLift.attribute.__wrapped__( # type: ignore self, exp_inp, exp_base, target=exp_target, additional_forward_args=exp_addit_args, return_convergence_delta=cast( Literal[True, False], return_convergence_delta ), attribute_to_layer_input=attribute_to_layer_input, custom_attribution_func=custom_attribution_func, ) if return_convergence_delta: attributions, delta = attributions if isinstance(attributions, tuple): attributions = tuple( DeepLiftShap._compute_mean_across_baselines( self, inp_bsz, base_bsz, cast(Tensor, attrib) ) for attrib in attributions ) else: attributions = DeepLiftShap._compute_mean_across_baselines( self, inp_bsz, base_bsz, attributions ) if return_convergence_delta: return attributions, delta else: return attributions @property def multiplies_by_inputs(self): return self._multiply_by_inputs
#!/usr/bin/env python3 from collections import defaultdict import torch from pytext.models.embeddings.dict_embedding import DictEmbedding from pytext.models.embeddings.word_embedding import WordEmbedding from pytext.models.model import EmbeddingBase, EmbeddingList class PyTextInterpretableEmbedding(EmbeddingBase): r""" In PyText DocNN models we need a way to access word embedding layers, generate the embeddings and subtract the baseline. To do so, we separate embedding layers from the model, compute the embeddings separately and do all operations needed outside of the model. The original embedding layer is being replaced by `PyTextInterpretableEmbedding` layer which passes precomputed embedding vectors to lower layers. """ def __init__(self, embeddings) -> None: self.embedding_dims = [embedding.embedding_dim for embedding in embeddings] super().__init__(sum(self.embedding_dims)) self.embeddings = embeddings def forward(self, input): r""" The forward pass of embedding layer. This can be for the text or any type of embedding. Args input: Input embeddings tensor Return output: Output tensor is the same as input. It passes through the embedding tensors to lower layers without any modifications """ return input def get_attribution_map(self, attributions): r""" After attribution scores are computed for an input embedding vector we need to split it up into attribution sub tensors for each feature type: word, dict and other types TODO: we can potentally also output tuples of attributions. This might be a better option. We'll work on this in a separate diff. Args attributions: A tensor that contains attribution values for each input field. It usually has the same dimensions as the input tensor Return attribution_map: A dictionary of feature_type and attribution values """ begin = 0 attribution_map = defaultdict() for embedding, embedding_size in zip(self.embeddings, self.embedding_dims): end = begin + embedding_size if isinstance(embedding, WordEmbedding): attribution_map["word"] = attributions[:, :, begin:end] elif isinstance(embedding, DictEmbedding): attribution_map["dict"] = attributions[:, :, begin:end] else: raise NotImplementedError( "Currently only word and dict " "embeddings are supported" ) begin = end return attribution_map class BaselineGenerator: r""" This is an example input baseline generator for DocNN model which uses word and dict features. """ PAD = "<pad>" def __init__(self, model, data_handler, device) -> None: self.model = model self.data_handler = data_handler if "dict_feat" in data_handler.features: self.vocab_dict = data_handler.features["dict_feat"].vocab if "word_feat" in data_handler.features: self.vocab_word = data_handler.features["word_feat"].vocab self.baseline_single_word_feature = self._generate_baseline_single_word_feature( device ) self.baseline_single_dict_feature = self._generate_baseline_single_dict_feature( device ) def generate_baseline(self, integ_grads_embeddings, seq_length): r""" Generates baseline for input word and dict features. In the future we will extend it to support char and other features as well. This baseline is entirely based on the `<pad>` token. Args integ_grads_embeddings: A reference to integrated gradients embedding layer seq_length: The length of each sequence which depends on batch size Return baseline: A tuple of feature baselines Each feature type has a corresponding baseline tensor in the tuple. Currently only Dict and Word feature types are supported """ baseline = [] for embedding in integ_grads_embeddings.embeddings: if isinstance(embedding, WordEmbedding): baseline.append(self._generate_word_baseline(seq_length)) elif isinstance(embedding, DictEmbedding): baseline.append(self._generate_dict_baseline(seq_length)) else: raise NotImplementedError( "Currently only word and dict " "embeddings are supported" ) return tuple(baseline) def _generate_baseline_single_word_feature(self, device): return ( torch.tensor( [self.vocab_word.stoi[self.PAD] if hasattr(self, "vocab_word") else 0] ) .unsqueeze(0) .to(device) ) def _generate_baseline_single_dict_feature(self, device): r"""Generate dict features based on Assistant's case study by using sia_transformer: fbcode/assistant/sia/transformer/sia_transformer.py sia_transformer generates dict features in a special gazetter format See `fbsource/fbcode/pytext/models/embeddings/dict_embedding.py` It generates word dict feature embeddings for each word token. The output of SIATransformer after running it on `<pad>` token looks as following: OutputRecord(tokens=['<', 'pad', '>'], token_ranges=[(0, 1), (1, 4), (4, 5)], gazetteer_feats=['<pad>', '<pad>', '<pad>'], gazetteer_feat_lengths=[1, 1, 1], gazetteer_feat_weights=[0.0, 0.0, 0.0], characters=[['<', '<pad>', '<pad>'], ['p', 'a', 'd'], ['>', '<pad>', '<pad>']], pretrained_token_embedding=[ ], dense_feats=None) """ gazetteer_feats = [self.PAD, self.PAD, self.PAD] gazetteer_feat_lengths = [1, 1, 1] gazetteer_feat_weights = [0.0, 0.0, 0.0] gazetteer_feat_id = ( torch.tensor( [ self.vocab_dict.stoi[gazetteer_feat] if hasattr(self, "vocab_dict") else 0 for gazetteer_feat in gazetteer_feats ] ) .unsqueeze(0) .to(device) ) gazetteer_feat_weights = ( torch.tensor(gazetteer_feat_weights).unsqueeze(0).to(device) ) gazetteer_feat_lengths = ( torch.tensor(gazetteer_feat_lengths).to(device).view(1, -1)[:, 1] ) return (gazetteer_feat_id, gazetteer_feat_weights, gazetteer_feat_lengths) def _generate_word_baseline(self, seq_length): return self.baseline_single_word_feature.repeat(1, seq_length) def _generate_dict_baseline(self, seq_length): return ( self.baseline_single_dict_feature[0].repeat(1, seq_length), self.baseline_single_dict_feature[1].repeat(1, seq_length), self.baseline_single_dict_feature[2].repeat(1, seq_length), ) def configure_task_integ_grads_embeddings(task): r""" Wraps Pytext's DocNN model embedding with `IntegratedGradientsEmbedding` for a given input task. IntegratedGradientsEmbedding allows to perform baseline related operations Args task: DocNN task reference Returns integrated_gradients_embedding_lst: The embedding layer which contains IntegratedGradientsEmbedding as a wrapper over the original embeddings of the model """ integrated_gradients_embedding_lst = configure_model_integ_grads_embeddings( task.model ) task.model.embedding = integrated_gradients_embedding_lst return integrated_gradients_embedding_lst[0] def configure_model_integ_grads_embeddings(model): r""" Wraps Pytext's DocNN model embedding with `IntegratedGradientsEmbedding` IntegratedGradientsEmbedding allows to perform baseline related operations Args model: a reference to DocModel Returns integrated_gradients_embedding_lst: The embedding layer which contains IntegratedGradientsEmbedding as a wrapper over the original embeddings of the model """ embeddings = model.embedding integrated_gradients_embedding = PyTextInterpretableEmbedding(embeddings) return EmbeddingList([integrated_gradients_embedding], False) def reshape_word_features(word_features): r""" Creates one-sample batch for word features for sanity check purposes Args word_features: A tensor of diemnsions #words x #embeddings Return word_features: A tensor of dimensions 1 x #words x #embeddings """ return word_features.unsqueeze(0) def reshape_dict_features( dict_feature_id_batch, dict_weight_batch, dict_seq_len_batch, seq_length, idx ): r""" Creates one-sample batch for dict features for sanity check purposes It reads and reshapes id, weight and seq_length feature arrays for given input index `idx` from the input batch Args dict_feature_id_batch: The batch tensor for ids dict_weight_matrix: The batch tensor for weights dict_seq_len_matrix: The batch tensor for sequence length seq_length: The number of tokens per sequence idx: The index of sample in the batch Return dict_feature_ids: A tensor of dimensions [ bsz x # dict feature embeddings] dict_feature_weights: [ bsz x # dict feature embeddings] dict_feature_lens: [ bsz * seq_length ] """ dict_feature_ids = dict_feature_id_batch[idx].unsqueeze(0) dict_feature_weights = dict_weight_batch[idx].unsqueeze(0) dict_feature_lens = dict_seq_len_batch[idx].unsqueeze(0) return (dict_feature_ids, dict_feature_weights, dict_feature_lens)
#!/usr/bin/env python3 import warnings from functools import reduce import torch from torch.nn import Module class InterpretableEmbeddingBase(Module): r""" Since some embedding vectors, e.g. word are created and assigned in the embedding layers of Pytorch models we need a way to access those layers, generate the embeddings and subtract the baseline. To do so, we separate embedding layers from the model, compute the embeddings separately and do all operations needed outside of the model. The original embedding layer is being replaced by `InterpretableEmbeddingBase` layer which passes already precomputed embedding vectors to the layers below. """ def __init__(self, embedding, full_name) -> None: Module.__init__(self) self.num_embeddings = getattr(embedding, "num_embeddings", None) self.embedding_dim = getattr(embedding, "embedding_dim", None) self.embedding = embedding self.full_name = full_name def forward(self, *inputs, **kwargs): r""" The forward function of a wrapper embedding layer that takes and returns embedding layer. It allows embeddings to be created outside of the model and passes them seamlessly to the preceding layers of the model. Args: *inputs (Any, optional): A sequence of inputs arguments that the forward function takes. Since forward functions can take any type and number of arguments, this will ensure that we can execute the forward pass using interpretable embedding layer. Note that if inputs are specified, it is assumed that the first argument is the embedding tensor generated using the `self.embedding` layer using all input arguments provided in `inputs` and `kwargs`. **kwargs (Any, optional): Similar to `inputs` we want to make sure that our forward pass supports arbitrary number and type of key-value arguments. If `inputs` is not provided, `kwargs` must be provided and the first argument corresponds to the embedding tensor generated using the `self.embedding`. Note that we make here an assumption here that `kwargs` is an ordered dict which is new in python 3.6 and is not guaranteed that it will consistently remain that way in the newer versions. In case current implementation doesn't work for special use cases, it is encouraged to override `InterpretableEmbeddingBase` and address those specifics in descendant classes. Returns: embedding_tensor (Tensor): Returns a tensor which is the same as first argument passed to the forward function. It passes pre-computed embedding tensors to lower layers without any modifications. """ assert len(inputs) > 0 or len(kwargs) > 0, ( "No input arguments are provided to `InterpretableEmbeddingBase`." "Input embedding tensor has to be provided as first argument to forward " "function either through inputs argument or kwargs." ) return inputs[0] if len(inputs) > 0 else list(kwargs.values())[0] def indices_to_embeddings(self, *input, **kwargs): r""" Maps indices to corresponding embedding vectors. E.g. word embeddings Args: *input (Any, optional): This can be a tensor(s) of input indices or any other variable necessary to comput the embeddings. A typical example of input indices are word or token indices. **kwargs (Any, optional): Similar to `input` this can be any sequence of key-value arguments necessary to compute final embedding tensor. Returns: tensor: A tensor of word embeddings corresponding to the indices specified in the input """ return self.embedding(*input, **kwargs) class TokenReferenceBase: r""" A base class for creating reference (aka baseline) tensor for a sequence of tokens. A typical example of such token is `PAD`. Users need to provide the index of the reference token in the vocabulary as an argument to `TokenReferenceBase` class. """ def __init__(self, reference_token_idx: int = 0) -> None: self.reference_token_idx = reference_token_idx def generate_reference(self, sequence_length, device: torch.device) -> torch.Tensor: r""" Generated reference tensor of given `sequence_length` using `reference_token_idx`. Args: sequence_length (int): The length of the reference sequence device (torch.device): The device on which the reference tensor will be created. Returns: tensor: A sequence of reference token with shape: [sequence_length] """ return torch.tensor([self.reference_token_idx] * sequence_length, device=device) def _get_deep_layer_name(obj, layer_names): r""" Traverses through the layer names that are separated by dot in order to access the embedding layer. """ return reduce(getattr, layer_names.split("."), obj) def _set_deep_layer_value(obj, layer_names, value): r""" Traverses through the layer names that are separated by dot in order to access the embedding layer and update its value. """ layer_names = layer_names.split(".") setattr(reduce(getattr, layer_names[:-1], obj), layer_names[-1], value) def configure_interpretable_embedding_layer( model: Module, embedding_layer_name: str = "embedding" ) -> InterpretableEmbeddingBase: r""" This method wraps a model's embedding layer with an interpretable embedding layer that allows us to access the embeddings through their indices. Args: model (torch.nn.Module): An instance of PyTorch model that contains embeddings. embedding_layer_name (str, optional): The name of the embedding layer in the `model` that we would like to make interpretable. Returns: interpretable_emb (InterpretableEmbeddingBase): An instance of `InterpretableEmbeddingBase` embedding layer that wraps model's embedding layer that is being accessed through `embedding_layer_name`. Examples:: >>> # Let's assume that we have a DocumentClassifier model that >>> # has a word embedding layer named 'embedding'. >>> # To make that layer interpretable we need to execute the >>> # following command: >>> net = DocumentClassifier() >>> interpretable_emb = configure_interpretable_embedding_layer(net, >>> 'embedding') >>> # then we can use interpretable embedding to convert our >>> # word indices into embeddings. >>> # Let's assume that we have the following word indices >>> input_indices = torch.tensor([1, 0, 2]) >>> # we can access word embeddings for those indices with the command >>> # line stated below. >>> input_emb = interpretable_emb.indices_to_embeddings(input_indices) >>> # Let's assume that we want to apply integrated gradients to >>> # our model and that target attribution class is 3 >>> ig = IntegratedGradients(net) >>> attribution = ig.attribute(input_emb, target=3) >>> # after we finish the interpretation we need to remove >>> # interpretable embedding layer with the following command: >>> remove_interpretable_embedding_layer(net, interpretable_emb) """ embedding_layer = _get_deep_layer_name(model, embedding_layer_name) assert ( embedding_layer.__class__ is not InterpretableEmbeddingBase ), "InterpretableEmbeddingBase has already been configured for layer {}".format( embedding_layer_name ) warnings.warn( "In order to make embedding layers more interpretable they will " "be replaced with an interpretable embedding layer which wraps the " "original embedding layer and takes word embedding vectors as inputs of " "the forward function. This allows us to generate baselines for word " "embeddings and compute attributions for each embedding dimension. " "The original embedding layer must be set " "back by calling `remove_interpretable_embedding_layer` function " "after model interpretation is finished. " ) interpretable_emb = InterpretableEmbeddingBase( embedding_layer, embedding_layer_name ) _set_deep_layer_value(model, embedding_layer_name, interpretable_emb) return interpretable_emb def remove_interpretable_embedding_layer( model: Module, interpretable_emb: InterpretableEmbeddingBase ) -> None: r""" Removes interpretable embedding layer and sets back original embedding layer in the model. Args: model (torch.nn.Module): An instance of PyTorch model that contains embeddings interpretable_emb (InterpretableEmbeddingBase): An instance of `InterpretableEmbeddingBase` that was originally created in `configure_interpretable_embedding_layer` function and has to be removed after interpretation is finished. Examples:: >>> # Let's assume that we have a DocumentClassifier model that >>> # has a word embedding layer named 'embedding'. >>> # To make that layer interpretable we need to execute the >>> # following command: >>> net = DocumentClassifier() >>> interpretable_emb = configure_interpretable_embedding_layer(net, >>> 'embedding') >>> # then we can use interpretable embedding to convert our >>> # word indices into embeddings. >>> # Let's assume that we have the following word indices >>> input_indices = torch.tensor([1, 0, 2]) >>> # we can access word embeddings for those indices with the command >>> # line stated below. >>> input_emb = interpretable_emb.indices_to_embeddings(input_indices) >>> # Let's assume that we want to apply integrated gradients to >>> # our model and that target attribution class is 3 >>> ig = IntegratedGradients(net) >>> attribution = ig.attribute(input_emb, target=3) >>> # after we finish the interpretation we need to remove >>> # interpretable embedding layer with the following command: >>> remove_interpretable_embedding_layer(net, interpretable_emb) """ _set_deep_layer_value( model, interpretable_emb.full_name, interpretable_emb.embedding )
#!/usr/bin/env python3 from captum.concept._core.cav import CAV # noqa from captum.concept._core.concept import Concept, ConceptInterpreter # noqa from captum.concept._core.tcav import TCAV # noqa from captum.concept._utils.classifier import Classifier, DefaultClassifier # noqa
#!/usr/bin/env python3 import glob import os from typing import Callable, Iterator from torch import Tensor from torch.utils.data import DataLoader, Dataset, IterableDataset class CustomIterableDataset(IterableDataset): r""" An auxiliary class for iterating through a dataset. """ def __init__(self, transform_filename_to_tensor: Callable, path: str) -> None: r""" Args: transform_filename_to_tensor (Callable): Function to read a data file from path and return a tensor from that file. path (str): Path to dataset files. This can be either a path to a directory or a file where input examples are stored. """ self.file_itr = None self.path = path if os.path.isdir(self.path): self.file_itr = glob.glob(self.path + "*") self.transform_filename_to_tensor = transform_filename_to_tensor def __iter__(self) -> Iterator[Tensor]: r""" Returns: iter (Iterator[Tensor]): A map from a function that processes a list of file path(s) to a list of Tensors. """ if self.file_itr is not None: return map(self.transform_filename_to_tensor, self.file_itr) else: return self.transform_filename_to_tensor(self.path) def dataset_to_dataloader(dataset: Dataset, batch_size: int = 64) -> DataLoader: r""" An auxiliary function that creates torch DataLoader from torch Dataset using input `batch_size`. Args: dataset (Dataset): A torch dataset that allows to iterate over the batches of examples. batch_size (int, optional): Batch size of for each tensor in the iteration. Returns: dataloader_iter (DataLoader): a DataLoader for data iteration. """ return DataLoader(dataset, batch_size=batch_size)
#!/usr/bin/env python3 import random import warnings from abc import ABC, abstractmethod from typing import Any, Dict, List, Tuple, Union import torch from captum._utils.models.linear_model import model from torch import Tensor from torch.utils.data import DataLoader, TensorDataset class Classifier(ABC): r""" An abstract class definition of any classifier that allows to train a model and access trained weights of that model. More specifically the classifier can, for instance, be trained on the activations of a particular layer. Below we can see an example a sklearn linear classifier wrapped by the `CustomClassifier` which extends `Classifier` abstract class. Example:: >>> from sklearn import linear_model >>> >>> class CustomClassifier(Classifier): >>> >>> def __init__(self): >>> >>> self.lm = linear_model.SGDClassifier(alpha=0.01, max_iter=1000, >>> tol=1e-3) >>> >>> def train_and_eval(self, dataloader): >>> >>> x_train, x_test, y_train, y_test = train_test_split(inputs, labels) >>> self.lm.fit(x_train.detach().numpy(), y_train.detach().numpy()) >>> >>> preds = torch.tensor(self.lm.predict(x_test.detach().numpy())) >>> return {'accs': (preds == y_test).float().mean()} >>> >>> >>> def weights(self): >>> >>> if len(self.lm.coef_) == 1: >>> # if there are two concepts, there is only one label. >>> # We split it in two. >>> return torch.tensor([-1 * self.lm.coef_[0], self.lm.coef_[0]]) >>> else: >>> return torch.tensor(self.lm.coef_) >>> >>> >>> def classes(self): >>> return self.lm.classes_ >>> >>> """ @abstractmethod def __init__(self) -> None: pass @abstractmethod def train_and_eval( self, dataloader: DataLoader, **kwargs: Any ) -> Union[Dict, None]: r""" This method is responsible for training a classifier using the data provided through `dataloader` input arguments. Based on the specific implementation, it may or may not return a statistics about model training and evaluation. Args: dataloader (dataloader): A dataloader that enables batch-wise access to the inputs and corresponding labels. Dataloader allows us to iterate over the dataset by loading the batches in lazy manner. kwargs (dict): Named arguments that are used for training and evaluating concept classifier. Default: None Returns: stats (dict): a dictionary of statistics about the performance of the model. For example the accuracy of the model on the test and/or train dataset(s). The user may decide to return None or an empty dictionary if they decide to not return any performance statistics. """ pass @abstractmethod def weights(self) -> Tensor: r""" This function returns a C x F tensor weights, where C is the number of classes and F is the number of features. Returns: weights (Tensor): A torch Tensor with the weights resulting from the model training. """ pass @abstractmethod def classes(self) -> List[int]: r""" This function returns the list of all classes that are used by the classifier to train the model in the `train_and_eval` method. The order of returned classes has to match the same order used in the weights matrix returned by the `weights` method. Returns: classes (list): The list of classes used by the classifier to train the model in the `train_and_eval` method. """ pass class DefaultClassifier(Classifier): r""" A default Linear Classifier based on sklearn's SGDClassifier for learning decision boundaries between concepts. Note that default implementation slices input dataset into train and test splits and keeps them in memory. In case concept datasets are large, this can lead to out of memory and we recommend to provide a custom Classier that extends `Classifier` abstract class and handles large concept datasets accordingly. """ def __init__(self) -> None: warnings.warn( "Using default classifier for TCAV which keeps input" " both train and test datasets in the memory. Consider defining" " your own classifier that doesn't rely heavily on memory, for" " large number of concepts, by extending" " `Classifer` abstract class" ) self.lm = model.SkLearnSGDClassifier(alpha=0.01, max_iter=1000, tol=1e-3) def train_and_eval( self, dataloader: DataLoader, test_split_ratio: float = 0.33, **kwargs: Any ) -> Union[Dict, None]: r""" Implements Classifier::train_and_eval abstract method for small concept datsets provided by `dataloader`. It is assumed that when iterating over `dataloader` we can still retain the entire dataset in the memory. This method shuffles all examples randomly provided, splits them into train and test partitions and trains an SGDClassifier using sklearn library. Ultimately, it measures and returns model accuracy using test split of the dataset. Args: dataloader (dataloader): A dataloader that enables batch-wise access to the inputs and corresponding labels. Dataloader allows us to iterate over the dataset by loading the batches in lazy manner. test_split_ratio (float): The ratio of test split in the entire dataset served by input data loader `dataloader`. Default: 0.33 Returns: stats (dict): a dictionary of statistics about the performance of the model. In this case stats represents a dictionary of model accuracy measured on the test split of the dataset. """ inputs = [] labels = [] for input, label in dataloader: inputs.append(input) labels.append(label) device = "cpu" if input is None else input.device x_train, x_test, y_train, y_test = _train_test_split( torch.cat(inputs), torch.cat(labels), test_split=test_split_ratio ) self.lm.device = device self.lm.fit(DataLoader(TensorDataset(x_train, y_train))) predict = self.lm(x_test) predict = self.lm.classes()[torch.argmax(predict, dim=1)] # type: ignore score = predict.long() == y_test.long().cpu() accs = score.float().mean() return {"accs": accs} def weights(self) -> Tensor: r""" This function returns a C x F tensor weights, where C is the number of classes and F is the number of features. In case of binary classification, C = 2 otherwise it is > 2. Returns: weights (Tensor): A torch Tensor with the weights resulting from the model training. """ assert self.lm.linear is not None, ( "The weights cannot be obtained because no model was trained." "In order to train the model call `train_and_eval` method first." ) weights = self.lm.representation() if weights.shape[0] == 1: # if there are two concepts, there is only one label. We split it in two. return torch.stack([-1 * weights[0], weights[0]]) else: return weights def classes(self) -> List[int]: r""" This function returns the list of all classes that are used by the classifier to train the model in the `train_and_eval` method. The order of returned classes has to match the same order used in the weights matrix returned by the `weights` method. Returns: classes (list): The list of classes used by the classifier to train the model in the `train_and_eval` method. """ return self.lm.classes().detach().numpy() # type: ignore def _train_test_split( x_list: Tensor, y_list: Tensor, test_split: float = 0.33 ) -> Tuple[Tensor, Tensor, Tensor, Tensor]: # Shuffle z_list = list(zip(x_list, y_list)) random.shuffle(z_list) # Split test_size = int(test_split * len(z_list)) z_test, z_train = z_list[:test_size], z_list[test_size:] x_test, y_test = zip(*z_test) x_train, y_train = zip(*z_train) return ( torch.stack(x_train), torch.stack(x_test), torch.stack(y_train), torch.stack(y_test), )
#!/usr/bin/env python3 from typing import List from captum.concept._core.concept import Concept def concepts_to_str(concepts: List[Concept]) -> str: r""" Returns a string of hyphen("-") concatenated concept names. Example output: "striped-random_0-random_1" Args: concepts (list[Concept]): a List of concept names to be concatenated and used as a concepts key. These concept names are respective to the Concept objects used for the classifier train. Returns: names_str (str): A string of hyphen("-") concatenated concept names. Ex.: "striped-random_0-random_1" """ return "-".join([str(c.id) for c in concepts])
#!/usr/bin/env python3 import os from typing import Any, Dict, List import torch from captum.concept._core.concept import Concept from captum.concept._utils.common import concepts_to_str class CAV: r""" Concept Activation Vector (CAV) is a vector orthogonal to the decision boundary of a classifier which distinguishes between activation vectors produced by different concepts. More details can be found in the paper: https://arxiv.org/abs/1711.11279 """ def __init__( self, concepts: List[Concept], layer: str, stats: Dict[str, Any] = None, save_path: str = "./cav/", model_id: str = "default_model_id", ) -> None: r""" This class encapsulates the instances of CAVs objects, saves them in and loads them from the disk (storage). Args: concepts (list[Concept]): a List of Concept objects. Only their names will be saved and loaded. layer (str): The layer where concept activation vectors are computed using a predefined classifier. stats (dict, optional): a dictionary that retains information about the CAV classifier such as CAV weights and accuracies. Ex.: stats = {"weights": weights, "classes": classes, "accs": accs}, where "weights" are learned model parameters, "classes" are a list of classes used by the model to generate the "weights" and "accs" the classifier training or validation accuracy. save_path (str, optional): The path where the CAV objects are stored. model_id (str, optional): A unique model identifier associated with this CAV instance. """ self.concepts = concepts self.layer = layer self.stats = stats self.save_path = save_path self.model_id = model_id @staticmethod def assemble_save_path( path: str, model_id: str, concepts: List[Concept], layer: str ) -> str: r""" A utility method for assembling filename and its path, from a concept list and a layer name. Args: path (str): A path to be concatenated with the concepts key and layer name. model_id (str): A unique model identifier associated with input `layer` and `concepts` concepts (list[Concept]): A list of concepts that are concatenated together and used as a concept key using their ids. These concept ids are retrieved from TCAV s`Concept` objects. layer (str): The name of the layer for which the activations are computed. Returns: cav_path(str): A string containing the path where the computed CAVs will be stored. For example, given: concept_ids = [0, 1, 2] concept_names = ["striped", "random_0", "random_1"] layer = "inception4c" path = "/cavs", the resulting save path will be: "/cavs/default_model_id/0-1-2-inception4c.pkl" """ file_name = concepts_to_str(concepts) + "-" + layer + ".pkl" return os.path.join(path, model_id, file_name) def save(self): r""" Saves a dictionary of the CAV computed values into a pickle file in the location returned by the "assemble_save_path" static methods. The dictionary contains the concept names list, the layer name for which the activations are computed for, the stats dictionary which contains information about the classifier train/eval statistics such as the weights and training accuracies. Ex.: save_dict = { "concept_ids": [0, 1, 2], "concept_names": ["striped", "random_0", "random_1"], "layer": "inception4c", "stats": {"weights": weights, "classes": classes, "accs": accs} } """ save_dict = { "concept_ids": [c.id for c in self.concepts], "concept_names": [c.name for c in self.concepts], "layer": self.layer, "stats": self.stats, } cavs_path = CAV.assemble_save_path( self.save_path, self.model_id, self.concepts, self.layer ) torch.save(save_dict, cavs_path) @staticmethod def create_cav_dir_if_missing(save_path: str, model_id: str) -> None: r""" A utility function for creating the directories where the CAVs will be stored. CAVs are saved in a folder under named by `model_id` under `save_path`. Args: save_path (str): A root path where the CAVs will be stored model_id (str): A unique model identifier associated with the CAVs. A folder named `model_id` is created under `save_path`. The CAVs are later stored there. """ cav_model_id_path = os.path.join(save_path, model_id) if not os.path.exists(cav_model_id_path): os.makedirs(cav_model_id_path) @staticmethod def load(cavs_path: str, model_id: str, concepts: List[Concept], layer: str): r""" Loads CAV dictionary from a pickle file for given input `layer` and `concepts`. Args: cavs_path (str): The root path where the cavs are stored in the storage (on the disk). Ex.: "/cavs" model_id (str): A unique model identifier associated with the CAVs. There exist a folder named `model_id` under `cavs_path` path. The CAVs are loaded from this folder. concepts (list[Concept]): A List of concepts for which we would like to load the cavs. layer (str): The layer name. Ex.: "inception4c". In case of nested layers we use dots to specify the depth / hierarchy. Ex.: "layer.sublayer.subsublayer" Returns: cav(CAV): An instance of a CAV class, containing the respective CAV score per concept and layer. An example of a path where the cavs are loaded from is: "/cavs/default_model_id/0-1-2-inception4c.pkl" """ cavs_path = CAV.assemble_save_path(cavs_path, model_id, concepts, layer) if os.path.exists(cavs_path): save_dict = torch.load(cavs_path) concept_names = save_dict["concept_names"] concept_ids = save_dict["concept_ids"] concepts = [ Concept(concept_id, concept_name, None) for concept_id, concept_name in zip(concept_ids, concept_names) ] cav = CAV(concepts, save_dict["layer"], save_dict["stats"]) return cav return None
#!/usr/bin/env python3 from typing import Callable, Union import torch from torch.nn import Module class Concept: r""" Concepts are human-friendly abstract representations that can be numerically encoded into torch tensors. They can be illustrated as images, text or any other form of representation. In case of images, for example, "stripes" concept can be represented through a number of example images resembling "stripes" in various different contexts. In case of Natural Language Processing, the concept of "happy", for instance, can be illustrated through a number of adjectives and words that convey happiness. """ def __init__( self, id: int, name: str, data_iter: Union[None, torch.utils.data.DataLoader] ) -> None: r""" Args: id (int): The unique identifier of the concept. name (str): A unique name of the concept. data_iter (DataLoader): A pytorch DataLoader object that combines a dataset and a sampler, and provides an iterable over a given dataset. Only the input batches are provided by `data_iter`. Concept ids can be used as labels if necessary. For more information, please check: https://pytorch.org/docs/stable/data.html Example:: >>> # Creates a Concept object named "striped", with a data_iter >>> # object to iterate over all files in "./concepts/striped" >>> concept_name = "striped" >>> concept_path = os.path.join("./concepts", concept_name) + "/" >>> concept_iter = dataset_to_dataloader( >>> get_tensor_from_filename, concepts_path=concept_path) >>> concept_object = Concept( id=0, name=concept_name, data_iter=concept_iter) """ self.id = id self.name = name self.data_iter = data_iter @property def identifier(self) -> str: return "%s-%s" % (self.name, self.id) def __repr__(self) -> str: return "Concept(%r, %r)" % (self.id, self.name) class ConceptInterpreter: r""" An abstract class that exposes an abstract interpret method that has to be implemented by a specific algorithm for concept-based model interpretability. """ def __init__(self, model: Module) -> None: r""" Args: model (torch.nn.Module): An instance of pytorch model. """ self.model = model interpret: Callable r""" An abstract interpret method that performs concept-based model interpretability and returns the interpretation results in form of tensors, dictionaries or other data structures. Args: inputs (Tensor or tuple[Tensor, ...]): Inputs for which concept-based interpretation scores are computed. It can be provided as a single tensor or a tuple of multiple tensors. If multiple input tensors are provided, the batch size (the first dimension of the tensors) must be aligned across all tensors. """
#!/usr/bin/env python3 from collections import defaultdict from typing import Any, cast, Dict, List, Set, Tuple, Union import numpy as np import torch import torch.multiprocessing as multiprocessing from captum._utils.av import AV from captum._utils.common import _format_tensor_into_tuples, _get_module_from_name from captum._utils.typing import TargetType, TensorOrTupleOfTensorsGeneric from captum.attr import LayerActivation, LayerAttribution, LayerGradientXActivation from captum.concept._core.cav import CAV from captum.concept._core.concept import Concept, ConceptInterpreter from captum.concept._utils.classifier import Classifier, DefaultClassifier from captum.concept._utils.common import concepts_to_str from captum.log import log_usage from torch import Tensor from torch.nn import Module from torch.utils.data import DataLoader, Dataset class LabelledDataset(Dataset): """ A torch Dataset whose __getitem__ returns both a batch of activation vectors, as well as a batch of labels associated with those activation vectors. It is used to train a classifier in train_tcav """ def __init__(self, datasets: List[AV.AVDataset], labels: List[int]) -> None: """ Creates the LabelledDataset given a list of K Datasets, and a length K list of integer labels representing K different concepts. The assumption is that the k-th Dataset of datasets is associated with the k-th element of labels. The LabelledDataset is the concatenation of the K Datasets in datasets. However, __get_item__ not only returns a batch of activation vectors, but also a batch of labels indicating which concept that batch of activation vectors is associated with. Args: datasets (list[Dataset]): The k-th element of datasets is a Dataset representing activation vectors associated with the k-th concept labels (list[int]): The k-th element of labels is the integer label associated with the k-th concept """ assert len(datasets) == len( labels ), "number of datasets does not match the number of concepts" from itertools import accumulate offsets = [0] + list(accumulate(map(len, datasets), (lambda x, y: x + y))) self.length = offsets[-1] self.datasets = datasets self.labels = labels self.lowers = offsets[:-1] self.uppers = offsets[1:] def _i_to_k(self, i): left, right = 0, len(self.uppers) while left < right: mid = (left + right) // 2 if self.lowers[mid] <= i and i < self.uppers[mid]: return mid if i >= self.uppers[mid]: left = mid else: right = mid def __getitem__(self, i: int): """ Returns a batch of activation vectors, as well as a batch of labels indicating which concept the batch of activation vectors is associated with. Args: i (int): which (activation vector, label) batch in the dataset to return Returns: inputs (Tensor): i-th batch in Dataset (representing activation vectors) labels (Tensor): labels of i-th batch in Dataset """ assert i < self.length k = self._i_to_k(i) inputs = self.datasets[k][i - self.lowers[k]] assert len(inputs.shape) == 2 labels = torch.tensor([self.labels[k]] * inputs.size(0), device=inputs.device) return inputs, labels def __len__(self) -> int: """ returns the total number of batches in the labelled_dataset """ return self.length def train_cav( model_id, concepts: List[Concept], layers: Union[str, List[str]], classifier: Classifier, save_path: str, classifier_kwargs: Dict, ) -> Dict[str, Dict[str, CAV]]: r""" A helper function for parallel CAV computations that can be called from a python process. Please see the TCAV class documentation for further information. Args: model_id (str): A unique identifier for the PyTorch model for which we would like to load the layer activations and train a model in order to compute CAVs. concepts (list[Concept]): A list of Concept objects that are used to train a classifier and learn decision boundaries between those concepts for each layer defined in the `layers` argument. layers (str or list[str]): A list of layer names or a single layer name that is used to compute the activations of all concept examples per concept and train a classifier using those activations. classifier (Classifier): A custom classifier class, such as the Sklearn "linear_model" that allows us to train a model using the activation vectors extracted for a layer per concept. It also allows us to access trained weights of the classifier and the list of prediction classes. save_path (str): The path for storing Concept Activation Vectors (CAVs) and Activation Vectors (AVs). classifier_kwargs (dict): Additional named arguments that are passed to concept classifier's `train_and_eval` method. Returns: cavs (dict): A dictionary of CAV objects indexed by concept ids and layer names. It gives access to the weights of each concept in a given layer and model statistics such as accuracies that resulted in trained concept weights. """ concepts_key = concepts_to_str(concepts) cavs: Dict[str, Dict[str, CAV]] = defaultdict() cavs[concepts_key] = defaultdict() layers = [layers] if isinstance(layers, str) else layers for layer in layers: # Create data loader to initialize the trainer. datasets = [ AV.load(save_path, model_id, concept.identifier, layer) for concept in concepts ] labels = [concept.id for concept in concepts] labelled_dataset = LabelledDataset(cast(List[AV.AVDataset], datasets), labels) def batch_collate(batch): inputs, labels = zip(*batch) return torch.cat(inputs), torch.cat(labels) dataloader = DataLoader(labelled_dataset, collate_fn=batch_collate) classifier_stats_dict = classifier.train_and_eval( dataloader, **classifier_kwargs ) classifier_stats_dict = ( {} if classifier_stats_dict is None else classifier_stats_dict ) weights = classifier.weights() assert ( weights is not None and len(weights) > 0 ), "Model weights connot be None or empty" classes = classifier.classes() assert ( classes is not None and len(classes) > 0 ), "Classes cannot be None or empty" classes = ( cast(torch.Tensor, classes).detach().numpy() if isinstance(classes, torch.Tensor) else classes ) cavs[concepts_key][layer] = CAV( concepts, layer, {"weights": weights, "classes": classes, **classifier_stats_dict}, save_path, model_id, ) # Saving cavs on the disk cavs[concepts_key][layer].save() return cavs class TCAV(ConceptInterpreter): r""" This class implements ConceptInterpreter abstract class using an approach called Testing with Concept Activation Vectors (TCAVs), as described in the paper: https://arxiv.org/abs/1711.11279 TCAV scores for a given layer, a list of concepts and input example are computed using the dot product between prediction's layer sensitivities for given input examples and Concept Activation Vectors (CAVs) in that same layer. CAVs are defined as vectors that are orthogonal to the classification boundary hyperplane that separate given concepts in a given layer from each other. For a given layer, CAVs are computed by training a classifier that uses the layer activation vectors for a set of concept examples as input examples and concept ids as corresponding input labels. Trained weights of that classifier represent CAVs. CAVs are represented as a learned weight matrix with the dimensionality C X F, where: F represents the number of input features in the classifier. C is the number of concepts used for the classification. Concept ids are used as labels for concept examples during the training. We can use any layer attribution algorithm to compute layer sensitivities of a model prediction. For example, the gradients of an output prediction w.r.t. the outputs of the layer. The CAVs and the Sensitivities (SENS) are used to compute the TCAV score: 0. TCAV = CAV • SENS, a dot product between those two vectors The final TCAV score can be computed by aggregating the TCAV scores for each input concept based on the sign or magnitude of the tcav scores. 1. sign_count_score = | TCAV > 0 | / | TCAV | 2. magnitude_score = SUM(ABS(TCAV * (TCAV > 0))) / SUM(ABS(TCAV)) """ def __init__( self, model: Module, layers: Union[str, List[str]], model_id: str = "default_model_id", classifier: Classifier = None, layer_attr_method: LayerAttribution = None, attribute_to_layer_input=False, save_path: str = "./cav/", **classifier_kwargs: Any, ) -> None: r""" Args: model (Module): An instance of pytorch model that is used to compute layer activations and attributions. layers (str or list[str]): A list of layer name(s) that are used for computing concept activations (cavs) and layer attributions. model_id (str, optional): A unique identifier for the PyTorch `model` passed as first argument to the constructor of TCAV class. It is used to store and load activations for given input `model` and associated `layers`. classifier (Classifier, optional): A custom classifier class, such as the Sklearn "linear_model" that allows us to train a model using the activation vectors extracted for a layer per concept. It also allows us to access trained weights of the model and the list of prediction classes. layer_attr_method (LayerAttribution, optional): An instance of a layer attribution algorithm that helps us to compute model prediction sensitivity scores. Default: None If `layer_attr_method` is None, we default it to gradients for the layers using `LayerGradientXActivation` layer attribution algorithm. save_path (str, optional): The path for storing CAVs and Activation Vectors (AVs). classifier_kwargs (Any, optional): Additional arguments such as `test_split_ratio` that are passed to concept `classifier`. Examples:: >>> >>> # TCAV use example: >>> >>> # Define the concepts >>> stripes = Concept(0, "stripes", striped_data_iter) >>> random = Concept(1, "random", random_data_iter) >>> >>> >>> mytcav = TCAV(model=imagenet, >>> layers=['inception4c', 'inception4d']) >>> >>> scores = mytcav.interpret(inputs, [[stripes, random]], target = 0) >>> For more thorough examples, please check out TCAV tutorial and test cases. """ ConceptInterpreter.__init__(self, model) self.layers = [layers] if isinstance(layers, str) else layers self.model_id = model_id self.concepts: Set[Concept] = set() self.classifier = classifier self.classifier_kwargs = classifier_kwargs self.cavs: Dict[str, Dict[str, CAV]] = defaultdict(lambda: defaultdict()) if self.classifier is None: self.classifier = DefaultClassifier() if layer_attr_method is None: self.layer_attr_method = cast( LayerAttribution, LayerGradientXActivation( # type: ignore model, None, multiply_by_inputs=False ), ) else: self.layer_attr_method = layer_attr_method assert model_id, ( "`model_id` cannot be None or empty. Consider giving `model_id` " "a meaningful name or leave it unspecified. If model_id is unspecified we " "will use `default_model_id` as its default value." ) self.attribute_to_layer_input = attribute_to_layer_input self.save_path = save_path # Creates CAV save directory if it doesn't exist. It is created once in the # constructor before generating the CAVs. # It is assumed that `model_id` can be used as a valid directory name # otherwise `create_cav_dir_if_missing` will raise an error CAV.create_cav_dir_if_missing(self.save_path, model_id) def generate_all_activations(self) -> None: r""" Computes layer activations for all concepts and layers that are defined in `self.layers` and `self.concepts` instance variables. """ for concept in self.concepts: self.generate_activation(self.layers, concept) def generate_activation(self, layers: Union[str, List], concept: Concept) -> None: r""" Computes layer activations for the specified `concept` and the list of layer(s) `layers`. Args: layers (str or list[str]): A list of layer names or a layer name that is used to compute layer activations for the specific `concept`. concept (Concept): A single Concept object that provides access to concept examples using a data iterator. """ layers = [layers] if isinstance(layers, str) else layers layer_modules = [_get_module_from_name(self.model, layer) for layer in layers] layer_act = LayerActivation(self.model, layer_modules) assert concept.data_iter is not None, ( "Data iterator for concept id:", "{} must be specified".format(concept.id), ) for i, examples in enumerate(concept.data_iter): activations = layer_act.attribute.__wrapped__( # type: ignore layer_act, examples, attribute_to_layer_input=self.attribute_to_layer_input, ) for activation, layer_name in zip(activations, layers): activation = torch.reshape(activation, (activation.shape[0], -1)) AV.save( self.save_path, self.model_id, concept.identifier, layer_name, activation.detach(), str(i), ) def generate_activations(self, concept_layers: Dict[Concept, List[str]]) -> None: r""" Computes layer activations for the concepts and layers specified in `concept_layers` dictionary. Args: concept_layers (dict[Concept, list[str]]): Dictionay that maps Concept objects to a list of layer names to generate the activations. Ex.: concept_layers = {"striped": ['inception4c', 'inception4d']} """ for concept in concept_layers: self.generate_activation(concept_layers[concept], concept) def load_cavs( self, concepts: List[Concept] ) -> Tuple[List[str], Dict[Concept, List[str]]]: r""" This function load CAVs as a dictionary of concept ids and layers. CAVs are stored in a directory located under `self.save_path` path, in .pkl files with the format: <self.save_path>/<concept_ids>-<layer_name>.pkl. Ex.: "/cavs/0-1-2-inception4c.pkl", where 0, 1 and 2 are concept ids. It returns a list of layers and a dictionary of concept-layers mapping for the concepts and layer that require CAV computation through training. This can happen if the CAVs aren't already pre-computed for a given list of concepts and layer. Args: concepts (list[Concept]): A list of Concept objects for which we want to load the CAV. Returns: layers (list[layer]): A list of layers for which some CAVs still need to be computed. concept_layers (dict[concept, layer]): A dictionay of concept-layers mapping for which we need to perform CAV computation through training. """ concepts_key = concepts_to_str(concepts) layers = [] concept_layers = defaultdict(list) for layer in self.layers: self.cavs[concepts_key][layer] = CAV.load( self.save_path, self.model_id, concepts, layer ) # If CAV aren't loaded if ( concepts_key not in self.cavs or layer not in self.cavs[concepts_key] or not self.cavs[concepts_key][layer] ): layers.append(layer) # For all concepts in this experimental_set for concept in concepts: # Collect not activated layers for this concept if not AV.exists( self.save_path, self.model_id, layer, concept.identifier ): concept_layers[concept].append(layer) return layers, concept_layers def compute_cavs( self, experimental_sets: List[List[Concept]], force_train: bool = False, processes: int = None, ): r""" This method computes CAVs for given `experiments_sets` and layers specified in `self.layers` instance variable. Internally, it trains a classifier and creates an instance of CAV class using the weights of the trained classifier for each experimental set. It also allows to compute the CAVs in parallel using python's multiprocessing API and the number of processes specified in the argument. Args: experimental_sets (list[list[Concept]]): A list of lists of concept instances for which the cavs will be computed. force_train (bool, optional): A flag that indicates whether to train the CAVs regardless of whether they are saved or not. Default: False processes (int, optional): The number of processes to be created when running in multi-processing mode. If processes > 0 then CAV computation will be performed in parallel using multi-processing, otherwise it will be performed sequentially in a single process. Default: None Returns: cavs (dict) : A mapping of concept ids and layers to CAV objects. If CAVs for the concept_ids-layer pairs are present in the data storage they will be loaded into the memory, otherwise they will be computed using a training process and stored in the data storage that can be configured using `save_path` input argument. """ # Update self.concepts with concepts for concepts in experimental_sets: self.concepts.update(concepts) concept_ids = [] for concept in self.concepts: assert concept.id not in concept_ids, ( "There is more than one instance " "of a concept with id {} defined in experimental sets. Please, " "make sure to reuse the same instance of concept".format( str(concept.id) ) ) concept_ids.append(concept.id) if force_train: self.generate_all_activations() # List of layers per concept key (experimental_set item) to be trained concept_key_to_layers = defaultdict(list) for concepts in experimental_sets: concepts_key = concepts_to_str(concepts) # If not 'force_train', try to load a saved CAV if not force_train: layers, concept_layers = self.load_cavs(concepts) concept_key_to_layers[concepts_key] = layers # Generate activations for missing (concept, layers) self.generate_activations(concept_layers) else: concept_key_to_layers[concepts_key] = self.layers if processes is not None and processes > 1: pool = multiprocessing.Pool(processes) cavs_list = pool.starmap( train_cav, [ ( self.model_id, concepts, concept_key_to_layers[concepts_to_str(concepts)], self.classifier, self.save_path, self.classifier_kwargs, ) for concepts in experimental_sets ], ) pool.close() pool.join() else: cavs_list = [] for concepts in experimental_sets: cavs_list.append( train_cav( self.model_id, concepts, concept_key_to_layers[concepts_to_str(concepts)], cast(Classifier, self.classifier), self.save_path, self.classifier_kwargs, ) ) # list[Dict[concept, Dict[layer, list]]] => Dict[concept, Dict[layer, list]] for cavs in cavs_list: for c_key in cavs: self.cavs[c_key].update(cavs[c_key]) return self.cavs @log_usage() def interpret( self, inputs: TensorOrTupleOfTensorsGeneric, experimental_sets: List[List[Concept]], target: TargetType = None, additional_forward_args: Any = None, processes: int = None, **kwargs: Any, ) -> Dict[str, Dict[str, Dict[str, Tensor]]]: r""" This method computes magnitude and sign-based TCAV scores for each experimental sets in `experimental_sets` list. TCAV scores are computed using a dot product between layer attribution scores for specific predictions and CAV vectors. Args: inputs (Tensor or tuple[Tensor, ...]): Inputs for which predictions are performed and attributions are computed. If model takes a single tensor as input, a single input tensor should be provided. If model takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately. experimental_sets (list[list[Concept]]): A list of list of Concept instances. target (int, tuple, Tensor, or list, optional): Output indices for which attributions are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either: - a single integer or a tensor containing a single integer, which is applied to all input examples - a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example. For outputs with > 2 dimensions, targets can be either: - A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples. - A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example. additional_forward_args (Any, optional): Extra arguments that are passed to model when computing the attributions for `inputs` w.r.t. layer output. Default: None processes (int, optional): The number of processes to be created. if processes is larger than one then CAV computations will be performed in parallel using the number of processes equal to `processes`. Otherwise, CAV computations will be performed sequential. Default:None **kwargs (Any, optional): A list of arguments that are passed to layer attribution algorithm's attribute method. This could be for example `n_steps` in case of integrated gradients. Default: None Returns: results (dict): A dictionary of sign and magnitude -based tcav scores for each concept set per layer. The order of TCAV scores in the resulting tensor for each experimental set follows the order in which concepts are passed in `experimental_sets` input argument. results example:: >>> # >>> # scores = >>> # {'0-1': >>> # {'inception4c': >>> # {'sign_count': tensor([0.5800, 0.4200]), >>> # 'magnitude': tensor([0.6613, 0.3387])}, >>> # 'inception4d': >>> # {'sign_count': tensor([0.6200, 0.3800]), >>> # 'magnitude': tensor([0.7707, 0.2293])}}), >>> # '0-2': >>> # {'inception4c': >>> # {'sign_count': tensor([0.6200, 0.3800]), >>> # 'magnitude': tensor([0.6806, 0.3194])}, >>> # 'inception4d': >>> # {'sign_count': tensor([0.6400, 0.3600]), >>> # 'magnitude': tensor([0.6563, 0.3437])}})}) >>> # """ assert "attribute_to_layer_input" not in kwargs, ( "Please, set `attribute_to_layer_input` flag as a constructor " "argument to TCAV class. In that case it will be applied " "consistently to both layer activation and layer attribution methods." ) self.compute_cavs(experimental_sets, processes=processes) scores: Dict[str, Dict[str, Dict[str, Tensor]]] = defaultdict( lambda: defaultdict() ) # Retrieves the lengths of the experimental sets so that we can sort # them by the length and compute TCAV scores in batches. exp_set_lens = np.array( list(map(lambda exp_set: len(exp_set), experimental_sets)), dtype=object ) exp_set_lens_arg_sort = np.argsort(exp_set_lens) # compute offsets using sorted lengths using their indices exp_set_lens_sort = exp_set_lens[exp_set_lens_arg_sort] exp_set_offsets_bool = [False] + list( exp_set_lens_sort[:-1] == exp_set_lens_sort[1:] ) exp_set_offsets = [] for i, offset in enumerate(exp_set_offsets_bool): if not offset: exp_set_offsets.append(i) exp_set_offsets.append(len(exp_set_lens)) # sort experimental sets using the length of the concepts in each set experimental_sets_sorted = np.array(experimental_sets, dtype=object)[ exp_set_lens_arg_sort ] for layer in self.layers: layer_module = _get_module_from_name(self.model, layer) self.layer_attr_method.layer = layer_module attribs = self.layer_attr_method.attribute.__wrapped__( # type: ignore self.layer_attr_method, # self inputs, target=target, additional_forward_args=additional_forward_args, attribute_to_layer_input=self.attribute_to_layer_input, **kwargs, ) attribs = _format_tensor_into_tuples(attribs) # n_inputs x n_features attribs = torch.cat( [torch.reshape(attrib, (attrib.shape[0], -1)) for attrib in attribs], dim=1, ) # n_experiments x n_concepts x n_features cavs = [] classes = [] for concepts in experimental_sets: concepts_key = concepts_to_str(concepts) cavs_stats = cast(Dict[str, Any], self.cavs[concepts_key][layer].stats) cavs.append(cavs_stats["weights"].float().detach().tolist()) classes.append(cavs_stats["classes"]) # sort cavs and classes using the length of the concepts in each set cavs_sorted = np.array(cavs, dtype=object)[exp_set_lens_arg_sort] classes_sorted = np.array(classes, dtype=object)[exp_set_lens_arg_sort] i = 0 while i < len(exp_set_offsets) - 1: cav_subset = np.array( cavs_sorted[exp_set_offsets[i] : exp_set_offsets[i + 1]], dtype=object, ).tolist() classes_subset = classes_sorted[ exp_set_offsets[i] : exp_set_offsets[i + 1] ].tolist() # n_experiments x n_concepts x n_features cav_subset = torch.tensor(cav_subset) cav_subset = cav_subset.to(attribs.device) assert len(cav_subset.shape) == 3, ( "cav should have 3 dimensions: n_experiments x " "n_concepts x n_features." ) experimental_subset_sorted = experimental_sets_sorted[ exp_set_offsets[i] : exp_set_offsets[i + 1] ] self._tcav_sub_computation( scores, layer, attribs, cav_subset, classes_subset, experimental_subset_sorted, ) i += 1 return scores def _tcav_sub_computation( self, scores: Dict[str, Dict[str, Dict[str, Tensor]]], layer: str, attribs: Tensor, cavs: Tensor, classes: List[List[int]], experimental_sets: List[List[Concept]], ) -> None: # n_inputs x n_concepts tcav_score = torch.matmul(attribs.float(), torch.transpose(cavs, 1, 2)) assert len(tcav_score.shape) == 3, ( "tcav_score should have 3 dimensions: n_experiments x " "n_inputs x n_concepts." ) assert attribs.shape[0] == tcav_score.shape[1], ( "attrib and tcav_score should have the same 1st and " "2nd dimensions respectively (n_inputs)." ) # n_experiments x n_concepts sign_count_score = torch.mean((tcav_score > 0.0).float(), dim=1) magnitude_score = torch.mean(tcav_score, dim=1) for i, (cls_set, concepts) in enumerate(zip(classes, experimental_sets)): concepts_key = concepts_to_str(concepts) # sort classes / concepts in the order specified in concept_keys concept_ord = [concept.id for concept in concepts] class_ord = {cls_: idx for idx, cls_ in enumerate(cls_set)} new_ord = torch.tensor( [class_ord[cncpt] for cncpt in concept_ord], device=tcav_score.device ) # sort based on classes scores[concepts_key][layer] = { "sign_count": torch.index_select( sign_count_score[i, :], dim=0, index=new_ord ), "magnitude": torch.index_select( magnitude_score[i, :], dim=0, index=new_ord ), }
#!/usr/bin/env python3 try: from captum.log.fb.internal_log import ( disable_detailed_logging, log, log_usage, patch_methods, set_environment, TimedLog, ) __all__ = [ "log", "log_usage", "TimedLog", "set_environment", "disable_detailed_logging", ] except ImportError: from functools import wraps def log(*args, **kwargs): pass # bug with mypy: https://github.com/python/mypy/issues/1153 class TimedLog: # type: ignore def __init__(self, *args, **kwargs) -> None: pass def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): return exception_value is not None def log_usage(*log_args, **log_kwargs): def _log_usage(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper return _log_usage def set_environment(env): pass def disable_detailed_logging(): pass def patch_methods(tester, patch_log=True): pass
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from setuptools import setup projects = [p.rstrip("\n") for p in open("hydra-configs-projects.txt", "r").readlines()] project_uris = [ f"{project} @ git+https://github.com/pytorch/hydra-torch/#subdirectory={project}" for project in projects ] setup( name="hydra-torch", version="0.9", author=["Omry Yadan", "Rosario Scalise"], author_email=["[email protected]", "[email protected]"], url="http://github.com/pytorch/hydra-torch", include_package_data=True, install_requires=project_uris, )
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import nox import os DEFAULT_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] PYTHON_VERSIONS = os.environ.get( "NOX_PYTHON_VERSIONS", ",".join(DEFAULT_PYTHON_VERSIONS) ).split(",") VERBOSE = os.environ.get("VERBOSE", "0") SILENT = VERBOSE == "0" # Linted dirs/files: lint_targets = "." # Test dirs (corresponds to each project having its own tests folder): # Note the './', this installs local packages test_targets = [ "./" + p.rstrip("\n") for p in open("hydra-configs-projects.txt", "r").readlines() ] def setup_dev_env(session): session.run( "python", "-m", "pip", "install", "--upgrade", "setuptools", "pip", silent=SILENT, ) session.run("pip", "install", "-r", "requirements/dev.txt", silent=SILENT) @nox.session(python=PYTHON_VERSIONS, reuse_venv=True) def lint(session): setup_dev_env(session) session.run("black", *lint_targets, "--check") session.run("flake8", "--config", ".flake8", *lint_targets) @nox.session(python=PYTHON_VERSIONS, reuse_venv=True) def tests(session): setup_dev_env(session) for target in test_targets: session.run( "pip", "install", "-r", target + "/requirements/dev.txt", silent=SILENT ) session.install(*test_targets) # install config packages session.run("pytest", *test_targets)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from setuptools import find_namespace_packages, setup requirements = [ "omegaconf", ] setup( name="hydra-configs-torchvision", version="0.8.2", packages=find_namespace_packages(include=["hydra_configs*"]), author=["Omry Yadan", "Rosario Scalise"], author_email=["[email protected]", "[email protected]"], url="http://github.com/pytorch/hydra-torch", include_package_data=True, install_requires=requirements, )
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import pytest from pathlib import Path from hydra.utils import get_class, instantiate from omegaconf import OmegaConf from typing import Any import torch import torchvision.datasets as datasets @pytest.mark.parametrize( "modulepath, classname, cfg, passthrough_args, passthrough_kwargs, expected_class", [ pytest.param( "datasets.vision", "VisionDataset", {"root": None}, [], {}, datasets.VisionDataset, id="VisionDatasetConf", ), pytest.param( "datasets.mnist", "MNIST", {"root": None}, [], {}, datasets.MNIST, id="MNISTConf", ), pytest.param( "datasets.mnist", "FashionMNIST", {"root": None}, [], {}, datasets.FashionMNIST, id="FashionMNISTConf", ), pytest.param( "datasets.mnist", "KMNIST", {"root": None}, [], {}, datasets.KMNIST, id="KMNISTConf", ), # TODO: These tests will need to be changed after blockers: # 1. EMNISTConf and QMNISTConf are manually created # 2. hydra.utils.instantiate is updated to allow *kwargs instantiation # pytest.param( # "datasets.mnist", # "EMNIST", # {"root":None, # "split":"byclass", # "kwargs":None}, # [], # {}, # datasets.EMNIST, # id="EMNISTConf", # ), # pytest.param( # "datasets.mnist", # "QMNIST", # {"root":None, # "what":'test', # "compat":None, # "kwargs":None}, # [], # {}, # datasets.QMNIST, # id="QMNISTConf", # ), ], ) def test_instantiate_classes( tmpdir: Path, modulepath: str, classname: str, cfg: Any, passthrough_args: Any, passthrough_kwargs: Any, expected_class: Any, ) -> None: # Create fake dataset and put it in tmpdir for test: tmp_data_root = tmpdir.mkdir("data") processed_dir = os.path.join(tmp_data_root, classname, "processed") os.makedirs(processed_dir) torch.save(torch.tensor([[1.0], [1.0]]), processed_dir + "/training.pt") torch.save(torch.tensor([1.0]), processed_dir + "/test.pt") # cfg is populated here since it requires tmpdir testfixture cfg["root"] = str(tmp_data_root) full_class = f"hydra_configs.torchvision.{modulepath}.{classname}Conf" schema = OmegaConf.structured(get_class(full_class)) cfg = OmegaConf.merge(schema, cfg) obj = instantiate(cfg, *passthrough_args, **passthrough_kwargs) expected_obj = expected_class(root=tmp_data_root) assert isinstance(obj, type(expected_obj))
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pytest from hydra.utils import get_class, instantiate from omegaconf import OmegaConf import torch # import torchvision.datasets as datasets import torchvision.transforms as transforms from torchvision.transforms.transforms import ToTensor from typing import Any def identity(x): return x @pytest.mark.parametrize( "modulepath, classname, cfg, passthrough_args, passthrough_kwargs, expected", [ # pytest.param( # "datasets.vision", # "StandardTransform", # {}, # [], # {}, # datasets.vision.StandardTransform(), # id="StandardTransformConf", # ), pytest.param( "transforms.transforms", "CenterCrop", {"size": (10, 10)}, [], {}, transforms.transforms.CenterCrop(size=(10, 10)), id="CenterCropConf", ), pytest.param( "transforms.transforms", "ColorJitter", {}, [], {}, transforms.transforms.ColorJitter(), id="ColorJitterConf", ), pytest.param( "transforms.transforms", "Compose", {"transforms": []}, [], {}, transforms.transforms.Compose(transforms=[]), id="ComposeConf", ), pytest.param( "transforms.transforms", "ConvertImageDtype", {}, [], {"dtype": torch.int32}, transforms.transforms.ConvertImageDtype(dtype=torch.int32), id="ConvertImageDtypeConf", ), pytest.param( "transforms.transforms", "FiveCrop", {"size": (10, 10)}, [], {}, transforms.transforms.FiveCrop(size=(10, 10)), id="FiveCropConf", ), pytest.param( "transforms.transforms", "Grayscale", {}, [], {}, transforms.transforms.Grayscale(), id="GrayscaleConf", ), pytest.param( "transforms.transforms", "Lambda", {}, [], {"lambd": identity}, transforms.transforms.Lambda(lambd=identity), id="LambdaConf", ), pytest.param( "transforms.transforms", "LinearTransformation", {}, [], { "transformation_matrix": torch.eye(2), "mean_vector": torch.Tensor([1, 1]), }, transforms.transforms.LinearTransformation( transformation_matrix=torch.eye(2), mean_vector=torch.Tensor([1, 1]) ), id="LinearTransformationConf", ), pytest.param( "transforms.transforms", "Normalize", {"mean": 0, "std": 1}, [], {}, transforms.transforms.Normalize(mean=0, std=1), id="NormalizeConf", ), pytest.param( "transforms.transforms", "Pad", {"padding": 0}, [], {}, transforms.transforms.Pad(padding=0), id="PaddingConf", ), pytest.param( "transforms.transforms", "PILToTensor", {}, [], {}, transforms.transforms.PILToTensor(), id="PILToTensorConf", ), pytest.param( "transforms.transforms", "RandomAffine", {"degrees": 0}, [], {}, transforms.transforms.RandomAffine(degrees=0), id="RandomAffineConf", ), pytest.param( "transforms.transforms", "RandomApply", {}, [], {"transforms": [ToTensor()]}, transforms.transforms.RandomApply([ToTensor()]), id="RandomApplyConf", ), pytest.param( "transforms.transforms", "RandomChoice", {}, [], {"transforms": [[ToTensor()]]}, transforms.transforms.RandomChoice([ToTensor()]), id="RandomChoiceConf", ), pytest.param( "transforms.transforms", "RandomCrop", {"size": (10, 10)}, [], {}, transforms.transforms.RandomCrop(size=(10, 10)), id="RandomCropConf", ), pytest.param( "transforms.transforms", "RandomErasing", {}, [], {}, transforms.transforms.RandomErasing(), id="RandomErasingConf", ), pytest.param( "transforms.transforms", "RandomGrayscale", {}, [], {}, transforms.transforms.RandomGrayscale(), id="RandomGrayscaleConf", ), pytest.param( "transforms.transforms", "RandomHorizontalFlip", {}, [], {}, transforms.transforms.RandomHorizontalFlip(), id="RandomHorizontalFlipConf", ), pytest.param( "transforms.transforms", "RandomOrder", {}, [], {"transforms": [ToTensor()]}, transforms.transforms.RandomOrder([ToTensor()]), id="RandomOrderConf", ), pytest.param( "transforms.transforms", "RandomPerspective", {}, [], {}, transforms.transforms.RandomPerspective(), id="RandomPerspectiveConf", ), pytest.param( "transforms.transforms", "RandomResizedCrop", {"size": (10, 10)}, [], {}, transforms.transforms.RandomResizedCrop(size=(10, 10)), id="RandomResizedCropConf", ), pytest.param( "transforms.transforms", "RandomRotation", {"degrees": 0}, [], {}, transforms.transforms.RandomRotation(degrees=0), id="RandomRotationConf", ), pytest.param( "transforms.transforms", "RandomTransforms", {"transforms": []}, [], {}, transforms.transforms.RandomTransforms([]), id="RandomTransformsConf", ), pytest.param( "transforms.transforms", "RandomVerticalFlip", {}, [], {}, transforms.transforms.RandomVerticalFlip(), id="RandomVerticalFlipConf", ), pytest.param( "transforms.transforms", "Resize", {"size": (10, 10)}, [], {}, transforms.transforms.Resize(size=(10, 10)), id="ResizeConf", ), pytest.param( "transforms.transforms", "TenCrop", {"size": (10, 10)}, [], {}, transforms.transforms.TenCrop(size=(10, 10)), id="TenCropConf", ), pytest.param( "transforms.transforms", "ToPILImage", {}, [], {}, transforms.transforms.ToPILImage(), id="ToPILImageConf", ), pytest.param( "transforms.transforms", "ToTensor", {}, [], {}, transforms.transforms.ToTensor(), id="ToTensorConf", ), ], ) def test_instantiate_classes( modulepath: str, classname: str, cfg: Any, passthrough_args: Any, passthrough_kwargs: Any, expected: Any, ) -> None: full_class = f"hydra_configs.torchvision.{modulepath}.{classname}Conf" schema = OmegaConf.structured(get_class(full_class)) cfg = OmegaConf.merge(schema, cfg) obj = instantiate(cfg, *passthrough_args, **passthrough_kwargs) assert isinstance(obj, type(expected))
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from packaging import version from pkg_resources import get_distribution import warnings import torchvision CONFIGS_VERSION = get_distribution('hydra-configs-torchvision').version # checks if major.minor versions are matched. patch version is always different if version.parse(torchvision.__version__).release[:2] != version.parse(CONFIGS_VERSION).release[:2]: warnings.warn(f'Your config and library versions are mismatched. \n HYDRA-CONFIGS-TORCHVISION VERSION: {CONFIGS_VERSION}, \n TORCHVISION VERSION: {torchvision.__version__}. \n Please install the matching configs for reliable functionality.')
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class VisionDatasetConf: _target_: str = "torchvision.datasets.vision.VisionDataset" root: Any = MISSING transforms: Any = None transform: Any = None target_transform: Any = None @dataclass class StandardTransformConf: _target_: str = "torchvision.datasets.vision.StandardTransform" transform: Any = None target_transform: Any = None
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class MNISTConf: _target_: str = "torchvision.datasets.mnist.MNIST" root: Any = MISSING train: Any = True transform: Any = None target_transform: Any = None download: Any = False @dataclass class FashionMNISTConf: _target_: str = "torchvision.datasets.mnist.FashionMNIST" root: Any = MISSING train: Any = True transform: Any = None target_transform: Any = None download: Any = False @dataclass class KMNISTConf: _target_: str = "torchvision.datasets.mnist.KMNIST" root: Any = MISSING train: Any = True transform: Any = None target_transform: Any = None download: Any = False
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class CenterCropConf: _target_: str = "torchvision.transforms.transforms.CenterCrop" _convert_: str = "ALL" size: Any = MISSING @dataclass class ColorJitterConf: _target_: str = "torchvision.transforms.transforms.ColorJitter" _convert_: str = "ALL" brightness: Any = 0 contrast: Any = 0 saturation: Any = 0 hue: Any = 0 @dataclass class ComposeConf: _target_: str = "torchvision.transforms.transforms.Compose" _convert_: str = "ALL" transforms: Any = MISSING @dataclass class ConvertImageDtypeConf: _target_: str = "torchvision.transforms.transforms.ConvertImageDtype" _convert_: str = "ALL" dtype: Any = MISSING # dtype @dataclass class FiveCropConf: _target_: str = "torchvision.transforms.transforms.FiveCrop" _convert_: str = "ALL" size: Any = MISSING @dataclass class GrayscaleConf: _target_: str = "torchvision.transforms.transforms.Grayscale" _convert_: str = "ALL" num_output_channels: Any = 1 @dataclass class LambdaConf: _target_: str = "torchvision.transforms.transforms.Lambda" _convert_: str = "ALL" lambd: Any = MISSING @dataclass class LinearTransformationConf: _target_: str = "torchvision.transforms.transforms.LinearTransformation" _convert_: str = "ALL" transformation_matrix: Any = MISSING mean_vector: Any = MISSING @dataclass class NormalizeConf: _target_: str = "torchvision.transforms.transforms.Normalize" _convert_: str = "ALL" mean: Any = MISSING std: Any = MISSING inplace: Any = False @dataclass class PadConf: _target_: str = "torchvision.transforms.transforms.Pad" _convert_: str = "ALL" padding: Any = MISSING fill: Any = 0 padding_mode: Any = "constant" @dataclass class PILToTensorConf: _target_: str = "torchvision.transforms.transforms.PILToTensor" _convert_: str = "ALL" @dataclass class RandomAffineConf: _target_: str = "torchvision.transforms.transforms.RandomAffine" _convert_: str = "ALL" degrees: Any = MISSING translate: Any = None scale: Any = None shear: Any = None resample: Any = 0 fillcolor: Any = 0 @dataclass class RandomApplyConf: _target_: str = "torchvision.transforms.transforms.RandomApply" _convert_: str = "ALL" transforms: Any = MISSING p: Any = 0.5 @dataclass class RandomChoiceConf: _target_: str = "torchvision.transforms.transforms.RandomChoice" _convert_: str = "ALL" transforms: Any = MISSING @dataclass class RandomCropConf: _target_: str = "torchvision.transforms.transforms.RandomCrop" _convert_: str = "ALL" size: Any = MISSING padding: Any = None pad_if_needed: Any = False fill: Any = 0 padding_mode: Any = "constant" @dataclass class RandomErasingConf: _target_: str = "torchvision.transforms.transforms.RandomErasing" _convert_: str = "ALL" p: Any = 0.5 scale: Any = (0.02, 0.33) ratio: Any = (0.3, 3.3) value: Any = 0 inplace: Any = False @dataclass class RandomGrayscaleConf: _target_: str = "torchvision.transforms.transforms.RandomGrayscale" _convert_: str = "ALL" p: Any = 0.1 @dataclass class RandomHorizontalFlipConf: _target_: str = "torchvision.transforms.transforms.RandomHorizontalFlip" _convert_: str = "ALL" p: Any = 0.5 @dataclass class RandomOrderConf: _target_: str = "torchvision.transforms.transforms.RandomOrder" _convert_: str = "ALL" transforms: Any = MISSING @dataclass class RandomPerspectiveConf: _target_: str = "torchvision.transforms.transforms.RandomPerspective" _convert_: str = "ALL" distortion_scale: Any = 0.5 p: Any = 0.5 interpolation: Any = 2 fill: Any = 0 @dataclass class RandomResizedCropConf: _target_: str = "torchvision.transforms.transforms.RandomResizedCrop" _convert_: str = "ALL" size: Any = MISSING scale: Any = (0.08, 1.0) ratio: Any = (0.75, 1.3333333333333333) interpolation: Any = 2 @dataclass class RandomRotationConf: _target_: str = "torchvision.transforms.transforms.RandomRotation" _convert_: str = "ALL" degrees: Any = MISSING resample: Any = False expand: Any = False center: Any = None fill: Any = None @dataclass class RandomTransformsConf: _target_: str = "torchvision.transforms.transforms.RandomTransforms" _convert_: str = "ALL" transforms: Any = MISSING @dataclass class RandomVerticalFlipConf: _target_: str = "torchvision.transforms.transforms.RandomVerticalFlip" _convert_: str = "ALL" p: Any = 0.5 @dataclass class ResizeConf: _target_: str = "torchvision.transforms.transforms.Resize" _convert_: str = "ALL" size: Any = MISSING interpolation: Any = 2 @dataclass class TenCropConf: _target_: str = "torchvision.transforms.transforms.TenCrop" _convert_: str = "ALL" size: Any = MISSING vertical_flip: Any = False @dataclass class ToPILImageConf: _target_: str = "torchvision.transforms.transforms.ToPILImage" _convert_: str = "ALL" mode: Any = None @dataclass class ToTensorConf: _target_: str = "torchvision.transforms.transforms.ToTensor" _convert_: str = "ALL"
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # flake8: noqa from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms from torch.optim import Adadelta from torch.optim.lr_scheduler import StepLR ###### HYDRA BLOCK ###### import hydra from hydra.core.config_store import ConfigStore from dataclasses import dataclass # hydra-torch structured config imports from hydra_configs.torch.optim import AdadeltaConf from hydra_configs.torch.optim.lr_scheduler import StepLRConf @dataclass class MNISTConf: batch_size: int = 64 test_batch_size: int = 1000 epochs: int = 14 no_cuda: bool = False dry_run: bool = False seed: int = 1 log_interval: int = 10 save_model: bool = False checkpoint_name: str = "unnamed.pt" adadelta: AdadeltaConf = AdadeltaConf() steplr: StepLRConf = StepLRConf( step_size=1 ) # we pass a default for step_size since it is required, but missing a default in PyTorch (and consequently in hydra-torch) cs = ConfigStore.instance() cs.store(name="mnistconf", node=MNISTConf) ###### / HYDRA BLOCK ###### class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout2d(0.25) self.dropout2 = nn.Dropout2d(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = F.relu(x) x = self.conv2(x) x = F.relu(x) x = F.max_pool2d(x, 2) x = self.dropout1(x) x = torch.flatten(x, 1) x = self.fc1(x) x = F.relu(x) x = self.dropout2(x) x = self.fc2(x) output = F.log_softmax(x, dim=1) return output def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print( "Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( epoch, batch_idx * len(data), len(train_loader.dataset), 100.0 * batch_idx / len(train_loader), loss.item(), ) ) if args.dry_run: break def test(model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss( output, target, reduction="sum" ).item() # sum up batch loss pred = output.argmax( dim=1, keepdim=True ) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) print( "\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n".format( test_loss, correct, len(test_loader.dataset), 100.0 * correct / len(test_loader.dataset), ) ) @hydra.main(config_name="mnistconf") def main(cfg): # DIFF print(cfg.pretty()) use_cuda = not cfg.no_cuda and torch.cuda.is_available() # DIFF torch.manual_seed(cfg.seed) # DIFF device = torch.device("cuda" if use_cuda else "cpu") train_kwargs = {"batch_size": cfg.batch_size} # DIFF test_kwargs = {"batch_size": cfg.test_batch_size} # DIFF if use_cuda: cuda_kwargs = {"num_workers": 1, "pin_memory": True, "shuffle": True} train_kwargs.update(cuda_kwargs) test_kwargs.update(cuda_kwargs) transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))] ) dataset1 = datasets.MNIST("../data", train=True, download=True, transform=transform) dataset2 = datasets.MNIST("../data", train=False, transform=transform) train_loader = torch.utils.data.DataLoader(dataset1, **train_kwargs) test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs) model = Net().to(device) optimizer = Adadelta( lr=cfg.adadelta.lr, rho=cfg.adadelta.rho, eps=cfg.adadelta.eps, weight_decay=cfg.adadelta.weight_decay, params=model.parameters(), ) # DIFF scheduler = StepLR( step_size=cfg.steplr.step_size, gamma=cfg.steplr.gamma, last_epoch=cfg.steplr.last_epoch, optimizer=optimizer, ) # DIFF for epoch in range(1, cfg.epochs + 1): # DIFF train(cfg, model, device, train_loader, optimizer, epoch) # DIFF test(model, device, test_loader) scheduler.step() if cfg.save_model: # DIFF torch.save(model.state_dict(), cfg.checkpoint_name) # DIFF if __name__ == "__main__": main()
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from setuptools import find_namespace_packages, setup requirements = [ "omegaconf", ] setup( name="hydra-configs-torch", version="1.6.1", packages=find_namespace_packages(include=["hydra_configs*"]), author=["Omry Yadan", "Rosario Scalise"], author_email=["[email protected]", "[email protected]"], url="http://github.com/pytorch/hydra-torch", include_package_data=True, install_requires=requirements, )
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pytest from hydra.utils import get_class, instantiate from omegaconf import OmegaConf import torch.optim as optim import torch from torch import Tensor from torch import nn from typing import Any model = nn.Linear(1, 1) @pytest.mark.parametrize( "modulepath, classname, cfg, passthrough_kwargs, expected", [ pytest.param( "optim.adadelta", "Adadelta", {"lr": 0.1}, {"params": model.parameters()}, optim.Adadelta(lr=0.1, params=model.parameters()), id="AdadeltaConf", ), pytest.param( "optim.adagrad", "Adagrad", {"lr": 0.1}, {"params": model.parameters()}, optim.Adagrad(lr=0.1, params=model.parameters()), id="AdagradConf", ), pytest.param( "optim.adam", "Adam", {"lr": 0.1}, {"params": model.parameters()}, optim.Adam(lr=0.1, params=model.parameters()), id="AdamConf", ), pytest.param( "optim.adamax", "Adamax", {"lr": 0.1}, {"params": model.parameters()}, optim.Adamax(lr=0.1, params=model.parameters()), id="AdamaxConf", ), pytest.param( "optim.adamw", "AdamW", {"lr": 0.1}, {"params": model.parameters()}, optim.AdamW(lr=0.1, params=model.parameters()), id="AdamWConf", ), pytest.param( "optim.asgd", "ASGD", {"lr": 0.1}, {"params": model.parameters()}, optim.ASGD(lr=0.1, params=model.parameters()), id="ASGDConf", ), pytest.param( "optim.lbfgs", "LBFGS", {"lr": 0.1}, {"params": model.parameters()}, optim.LBFGS(lr=0.1, params=model.parameters()), id="LBFGSConf", ), pytest.param( "optim.rmsprop", "RMSprop", {"lr": 0.1}, {"params": model.parameters()}, optim.RMSprop(lr=0.1, params=model.parameters()), id="RMSpropConf", ), pytest.param( "optim.rprop", "Rprop", {"lr": 0.1}, {"params": model.parameters()}, optim.Rprop(lr=0.1, params=model.parameters()), id="RpropConf", ), pytest.param( "optim.sgd", "SGD", {"lr": 0.1}, {"params": model.parameters()}, optim.SGD(lr=0.1, params=model.parameters()), id="SGDConf", ), pytest.param( "optim.sparse_adam", "SparseAdam", {"lr": 0.1}, {"params": list(model.parameters())}, optim.SparseAdam(lr=0.1, params=list(model.parameters())), id="SparseAdamConf", ), ], ) def test_instantiate_classes( modulepath: str, classname: str, cfg: Any, passthrough_kwargs: Any, expected: Any ) -> None: full_class = f"hydra_configs.torch.{modulepath}.{classname}Conf" schema = OmegaConf.structured(get_class(full_class)) cfg = OmegaConf.merge(schema, cfg) obj = instantiate(cfg, **passthrough_kwargs) def closure(): return model(Tensor([10])) assert torch.all(torch.eq(obj.step(closure), expected.step(closure)))
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pytest from hydra.utils import get_class, instantiate from omegaconf import OmegaConf import torch.nn.modules.loss as loss from torch.tensor import Tensor from typing import Any @pytest.mark.parametrize( "modulepath, classname, cfg, passthrough_args, passthrough_kwargs, expected", [ pytest.param( "nn.modules.loss", "BCELoss", {}, [], {"weight": Tensor([1])}, loss.BCELoss(), id="BCELossConf", ), pytest.param( "nn.modules.loss", "BCEWithLogitsLoss", {}, [], {"weight": Tensor([1]), "pos_weight": Tensor([1])}, loss.BCEWithLogitsLoss(), id="BCEWithLogitsLossConf", ), pytest.param( "nn.modules.loss", "CosineEmbeddingLoss", {}, [], {}, loss.CosineEmbeddingLoss(), id="CosineEmbeddingLossConf", ), pytest.param( "nn.modules.loss", "CTCLoss", {}, [], {}, loss.CTCLoss(), id="CTCLossConf", ), pytest.param( "nn.modules.loss", "L1Loss", {}, [], {}, loss.L1Loss(), id="L1LossConf", ), pytest.param( "nn.modules.loss", "HingeEmbeddingLoss", {}, [], {}, loss.HingeEmbeddingLoss(), id="HingeEmbeddingLossConf", ), pytest.param( "nn.modules.loss", "KLDivLoss", {}, [], {}, loss.KLDivLoss(), id="KLDivLossConf", ), pytest.param( "nn.modules.loss", "MarginRankingLoss", {}, [], {}, loss.MarginRankingLoss(), id="MarginRankingLossConf", ), pytest.param( "nn.modules.loss", "MSELoss", {}, [], {}, loss.MSELoss(), id="MSELossConf", ), pytest.param( "nn.modules.loss", "MultiLabelMarginLoss", {}, [], {}, loss.MultiLabelMarginLoss(), id="MultiLabelMarginLossConf", ), pytest.param( "nn.modules.loss", "MultiLabelSoftMarginLoss", {}, [], {"weight": Tensor([1])}, loss.MultiLabelSoftMarginLoss(), id="MultiLabelSoftMarginLossConf", ), pytest.param( "nn.modules.loss", "MultiMarginLoss", {}, [], {"weight": Tensor([1])}, loss.MultiMarginLoss(), id="MultiMarginLossConf", ), pytest.param( "nn.modules.loss", "NLLLoss", {}, [], {"weight": Tensor([1])}, loss.NLLLoss(), id="NLLLossConf", ), pytest.param( "nn.modules.loss", "NLLLoss2d", {}, [], {"weight": Tensor([1])}, loss.NLLLoss2d(), id="NLLLoss2dConf", ), pytest.param( "nn.modules.loss", "PoissonNLLLoss", {}, [], {}, loss.PoissonNLLLoss(), id="PoissonNLLLossConf", ), pytest.param( "nn.modules.loss", "SmoothL1Loss", {}, [], {}, loss.SmoothL1Loss(), id="SmoothL1LossConf", ), pytest.param( "nn.modules.loss", "SoftMarginLoss", {}, [], {}, loss.SoftMarginLoss(), id="SoftMarginLossConf", ), pytest.param( "nn.modules.loss", "TripletMarginLoss", {}, [], {}, loss.TripletMarginLoss(), id="TripletMarginLossConf", ), ], ) def test_instantiate_classes( modulepath: str, classname: str, cfg: Any, passthrough_args: Any, passthrough_kwargs: Any, expected: Any, ) -> None: full_class = f"hydra_configs.torch.{modulepath}.{classname}Conf" schema = OmegaConf.structured(get_class(full_class)) cfg = OmegaConf.merge(schema, cfg) obj = instantiate(cfg, *passthrough_args, **passthrough_kwargs) assert isinstance(obj, type(expected))
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import pytest from hydra.utils import get_class, instantiate from omegaconf import OmegaConf import torch.utils.data as data import torch from typing import Any dummy_tensor = torch.tensor((1, 1)) dummy_dataset = data.dataset.TensorDataset(dummy_tensor) dummy_sampler = data.Sampler(data_source=dummy_dataset) @pytest.mark.parametrize( "modulepath, classname, cfg, passthrough_args, passthrough_kwargs, expected", [ pytest.param( "utils.data.dataloader", "DataLoader", {"batch_size": 4}, [], {"dataset": dummy_dataset}, data.DataLoader(batch_size=4, dataset=dummy_dataset), id="DataLoaderConf", ), pytest.param( "utils.data.dataset", "Dataset", {}, [], {}, data.Dataset(), id="DatasetConf", ), pytest.param( "utils.data.dataset", "ChainDataset", {}, [], {"datasets": [dummy_dataset, dummy_dataset]}, data.ChainDataset(datasets=[dummy_dataset, dummy_dataset]), id="ChainDatasetConf", ), pytest.param( "utils.data.dataset", "ConcatDataset", {}, [], {"datasets": [dummy_dataset, dummy_dataset]}, data.ConcatDataset(datasets=[dummy_dataset, dummy_dataset]), id="ConcatDatasetConf", ), pytest.param( "utils.data.dataset", "IterableDataset", {}, [], {}, data.IterableDataset(), id="IterableDatasetConf", ), # TODO: investigate asterisk in signature instantiation limitation # pytest.param( # "utils.data.dataset", # "TensorDataset", # {}, # [], # {"tensors":[dummy_tensor]}, # data.TensorDataset(dummy_tensor), # id="TensorDatasetConf", # ), pytest.param( "utils.data.dataset", "Subset", {}, [], {"dataset": dummy_dataset, "indices": [0]}, data.Subset(dummy_dataset, 0), id="SubsetConf", ), pytest.param( "utils.data.sampler", "Sampler", {}, [], {"data_source": dummy_dataset}, data.Sampler(data_source=dummy_dataset), id="SamplerConf", ), pytest.param( "utils.data.sampler", "BatchSampler", {"batch_size": 4, "drop_last": False}, [], {"sampler": dummy_sampler}, data.BatchSampler(sampler=dummy_sampler, batch_size=4, drop_last=False), id="BatchSamplerConf", ), pytest.param( "utils.data.sampler", "RandomSampler", {}, [], {"data_source": dummy_dataset}, data.RandomSampler(data_source=dummy_dataset), id="RandomSamplerConf", ), pytest.param( "utils.data.sampler", "SequentialSampler", {}, [], {"data_source": dummy_dataset}, data.SequentialSampler(data_source=dummy_dataset), id="SequentialSamplerConf", ), pytest.param( "utils.data.sampler", "SubsetRandomSampler", {"indices": [1]}, [], {}, data.SubsetRandomSampler(indices=[1]), id="SubsetRandomSamplerConf", ), pytest.param( "utils.data.sampler", "WeightedRandomSampler", {"weights": [1], "num_samples": 1}, [], {}, data.WeightedRandomSampler(weights=[1], num_samples=1), id="WeightedRandomSamplerConf", ), # TODO: investigate testing distributed instantiation # pytest.param( # "utils.data.distributed", # "DistributedSampler", # {}, # [], # {"dataset": dummy_dataset}, # data.DistributedSampler(group=dummy_group,dataset=dummy_dataset), # id="DistributedSamplerConf", # ), ], ) def test_instantiate_classes( modulepath: str, classname: str, cfg: Any, passthrough_args: Any, passthrough_kwargs: Any, expected: Any, ) -> None: full_class = f"hydra_configs.torch.{modulepath}.{classname}Conf" schema = OmegaConf.structured(get_class(full_class)) cfg = OmegaConf.merge(schema, cfg) obj = instantiate(cfg, *passthrough_args, **passthrough_kwargs) assert isinstance(obj, type(expected))
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class BCELossConf: _target_: str = "torch.nn.modules.loss.BCELoss" weight: Any = MISSING # Optional[Tensor] size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class BCEWithLogitsLossConf: _target_: str = "torch.nn.modules.loss.BCEWithLogitsLoss" weight: Any = MISSING # Optional[Tensor] size_average: Any = None reduce: Any = None reduction: str = "mean" pos_weight: Any = MISSING # Optional[Tensor] @dataclass class CosineEmbeddingLossConf: _target_: str = "torch.nn.modules.loss.CosineEmbeddingLoss" margin: float = 0.0 size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class CTCLossConf: _target_: str = "torch.nn.modules.loss.CTCLoss" blank: int = 0 reduction: str = "mean" zero_infinity: bool = False @dataclass class L1LossConf: _target_: str = "torch.nn.modules.loss.L1Loss" size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class HingeEmbeddingLossConf: _target_: str = "torch.nn.modules.loss.HingeEmbeddingLoss" margin: float = 1.0 size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class KLDivLossConf: _target_: str = "torch.nn.modules.loss.KLDivLoss" size_average: Any = None reduce: Any = None reduction: str = "mean" log_target: bool = False @dataclass class MarginRankingLossConf: _target_: str = "torch.nn.modules.loss.MarginRankingLoss" margin: float = 0.0 size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class MSELossConf: _target_: str = "torch.nn.modules.loss.MSELoss" size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class MultiLabelMarginLossConf: _target_: str = "torch.nn.modules.loss.MultiLabelMarginLoss" size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class MultiLabelSoftMarginLossConf: _target_: str = "torch.nn.modules.loss.MultiLabelSoftMarginLoss" weight: Any = MISSING # Optional[Tensor] size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class MultiMarginLossConf: _target_: str = "torch.nn.modules.loss.MultiMarginLoss" p: int = 1 margin: float = 1.0 weight: Any = MISSING # Optional[Tensor] size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class NLLLossConf: _target_: str = "torch.nn.modules.loss.NLLLoss" weight: Any = MISSING # Optional[Tensor] size_average: Any = None ignore_index: int = -100 reduce: Any = None reduction: str = "mean" @dataclass class NLLLoss2dConf: _target_: str = "torch.nn.modules.loss.NLLLoss2d" weight: Any = MISSING # Optional[Tensor] size_average: Any = None ignore_index: int = -100 reduce: Any = None reduction: str = "mean" @dataclass class PoissonNLLLossConf: _target_: str = "torch.nn.modules.loss.PoissonNLLLoss" log_input: bool = True full: bool = False size_average: Any = None eps: float = 1e-08 reduce: Any = None reduction: str = "mean" @dataclass class SmoothL1LossConf: _target_: str = "torch.nn.modules.loss.SmoothL1Loss" size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class SoftMarginLossConf: _target_: str = "torch.nn.modules.loss.SoftMarginLoss" size_average: Any = None reduce: Any = None reduction: str = "mean" @dataclass class TripletMarginLossConf: _target_: str = "torch.nn.modules.loss.TripletMarginLoss" margin: float = 1.0 p: float = 2.0 eps: float = 1e-06 swap: bool = False size_average: Any = None reduce: Any = None reduction: str = "mean"
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class LambdaLRConf: _target_: str = "torch.optim.lr_scheduler.LambdaLR" optimizer: Any = MISSING lr_lambda: Any = MISSING last_epoch: Any = -1 @dataclass class MultiplicativeLRConf: _target_: str = "torch.optim.lr_scheduler.MultiplicativeLR" optimizer: Any = MISSING lr_lambda: Any = MISSING last_epoch: Any = -1 @dataclass class StepLRConf: _target_: str = "torch.optim.lr_scheduler.StepLR" optimizer: Any = MISSING step_size: Any = MISSING gamma: Any = 0.1 last_epoch: Any = -1 @dataclass class MultiStepLRConf: _target_: str = "torch.optim.lr_scheduler.MultiStepLR" optimizer: Any = MISSING milestones: Any = MISSING gamma: Any = 0.1 last_epoch: Any = -1 @dataclass class ExponentialLRConf: _target_: str = "torch.optim.lr_scheduler.ExponentialLR" optimizer: Any = MISSING gamma: Any = MISSING last_epoch: Any = -1 @dataclass class CosineAnnealingLRConf: _target_: str = "torch.optim.lr_scheduler.CosineAnnealingLR" optimizer: Any = MISSING T_max: Any = MISSING eta_min: Any = 0 last_epoch: Any = -1 @dataclass class ReduceLROnPlateauConf: _target_: str = "torch.optim.lr_scheduler.ReduceLROnPlateau" optimizer: Any = MISSING mode: Any = "min" factor: Any = 0.1 patience: Any = 10 verbose: Any = False threshold: Any = 0.0001 threshold_mode: Any = "rel" cooldown: Any = 0 min_lr: Any = 0 eps: Any = 1e-08 @dataclass class CyclicLRConf: _target_: str = "torch.optim.lr_scheduler.CyclicLR" optimizer: Any = MISSING base_lr: Any = MISSING max_lr: Any = MISSING step_size_up: Any = 2000 step_size_down: Any = None mode: Any = "triangular" gamma: Any = 1.0 scale_fn: Any = None scale_mode: Any = "cycle" cycle_momentum: Any = True base_momentum: Any = 0.8 max_momentum: Any = 0.9 last_epoch: Any = -1 @dataclass class CosineAnnealingWarmRestartsConf: _target_: str = "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts" optimizer: Any = MISSING T_0: Any = MISSING T_mult: Any = 1 eta_min: Any = 0 last_epoch: Any = -1 @dataclass class OneCycleLRConf: _target_: str = "torch.optim.lr_scheduler.OneCycleLR" optimizer: Any = MISSING max_lr: Any = MISSING total_steps: Any = None epochs: Any = None steps_per_epoch: Any = None pct_start: Any = 0.3 anneal_strategy: Any = "cos" cycle_momentum: Any = True base_momentum: Any = 0.85 max_momentum: Any = 0.95 div_factor: Any = 25.0 final_div_factor: Any = 10000.0 last_epoch: Any = -1
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class RMSpropConf: _target_: str = "torch.optim.rmsprop.RMSprop" params: Any = MISSING lr: Any = 0.01 alpha: Any = 0.99 eps: Any = 1e-08 weight_decay: Any = 0 momentum: Any = 0 centered: Any = False
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class SparseAdamConf: _target_: str = "torch.optim.sparse_adam.SparseAdam" params: Any = MISSING lr: Any = 0.001 betas: Any = (0.9, 0.999) eps: Any = 1e-08
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class RpropConf: _target_: str = "torch.optim.rprop.Rprop" params: Any = MISSING lr: Any = 0.01 etas: Any = (0.5, 1.2) step_sizes: Any = (1e-06, 50)
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class SGDConf: _target_: str = "torch.optim.sgd.SGD" params: Any = MISSING lr: Any = MISSING # _RequiredParameter momentum: Any = 0 dampening: Any = 0 weight_decay: Any = 0 nesterov: Any = False
# flake8: noqa # Mirrors torch/optim __init__ to allow for symmetric import structure from .adadelta import AdadeltaConf from .adagrad import AdagradConf from .adam import AdamConf from .adamw import AdamWConf from .sparse_adam import SparseAdamConf from .adamax import AdamaxConf from .asgd import ASGDConf from .sgd import SGDConf from .rprop import RpropConf from .rmsprop import RMSpropConf from .lbfgs import LBFGSConf from . import lr_scheduler del adadelta del adagrad del adam del adamw del sparse_adam del adamax del asgd del sgd del rprop del rmsprop del lbfgs
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class AdamaxConf: _target_: str = "torch.optim.adamax.Adamax" params: Any = MISSING lr: Any = 0.002 betas: Any = (0.9, 0.999) eps: Any = 1e-08 weight_decay: Any = 0
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class AdagradConf: _target_: str = "torch.optim.adagrad.Adagrad" params: Any = MISSING lr: Any = 0.01 lr_decay: Any = 0 weight_decay: Any = 0 initial_accumulator_value: Any = 0 eps: Any = 1e-10
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class AdamWConf: _target_: str = "torch.optim.adamw.AdamW" params: Any = MISSING lr: Any = 0.001 betas: Any = (0.9, 0.999) eps: Any = 1e-08 weight_decay: Any = 0.01 amsgrad: Any = False
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class LBFGSConf: _target_: str = "torch.optim.lbfgs.LBFGS" params: Any = MISSING lr: Any = 1 max_iter: Any = 20 max_eval: Any = None tolerance_grad: Any = 1e-07 tolerance_change: Any = 1e-09 history_size: Any = 100 line_search_fn: Any = None
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class AdamConf: _target_: str = "torch.optim.adam.Adam" params: Any = MISSING lr: Any = 0.001 betas: Any = (0.9, 0.999) eps: Any = 1e-08 weight_decay: Any = 0 amsgrad: Any = False
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class ASGDConf: _target_: str = "torch.optim.asgd.ASGD" params: Any = MISSING lr: Any = 0.01 lambd: Any = 0.0001 alpha: Any = 0.75 t0: Any = 1000000.0 weight_decay: Any = 0
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class AdadeltaConf: _target_: str = "torch.optim.adadelta.Adadelta" params: Any = MISSING lr: Any = 1.0 rho: Any = 0.9 eps: Any = 1e-06 weight_decay: Any = 0
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class DatasetConf: _target_: str = "torch.utils.data.dataset.Dataset" @dataclass class ChainDatasetConf: _target_: str = "torch.utils.data.dataset.ChainDataset" datasets: Any = MISSING @dataclass class ConcatDatasetConf: _target_: str = "torch.utils.data.dataset.ConcatDataset" datasets: Any = MISSING @dataclass class IterableDatasetConf: _target_: str = "torch.utils.data.dataset.IterableDataset" @dataclass class TensorDatasetConf: _target_: str = "torch.utils.data.dataset.TensorDataset" tensors: Any = MISSING @dataclass class SubsetConf: _target_: str = "torch.utils.data.dataset.Subset" dataset: Any = MISSING indices: Any = MISSING
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class DistributedSamplerConf: _target_: str = "torch.utils.data.distributed.DistributedSampler" dataset: Any = MISSING num_replicas: Any = None rank: Any = None shuffle: Any = True seed: Any = 0
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class DataLoaderConf: _target_: str = "torch.utils.data.dataloader.DataLoader" dataset: Any = MISSING batch_size: Any = 1 shuffle: Any = False sampler: Any = None batch_sampler: Any = None num_workers: Any = 0 collate_fn: Any = None pin_memory: Any = False drop_last: Any = False timeout: Any = 0 worker_init_fn: Any = None multiprocessing_context: Any = None generator: Any = None
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # # Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/main/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from omegaconf import MISSING from typing import Any @dataclass class SamplerConf: _target_: str = "torch.utils.data.sampler.Sampler" data_source: Any = MISSING @dataclass class BatchSamplerConf: _target_: str = "torch.utils.data.sampler.BatchSampler" sampler: Any = MISSING batch_size: Any = MISSING drop_last: Any = MISSING @dataclass class RandomSamplerConf: _target_: str = "torch.utils.data.sampler.RandomSampler" data_source: Any = MISSING replacement: Any = False num_samples: Any = None generator: Any = None @dataclass class SequentialSamplerConf: _target_: str = "torch.utils.data.sampler.SequentialSampler" data_source: Any = MISSING @dataclass class SubsetRandomSamplerConf: _target_: str = "torch.utils.data.sampler.SubsetRandomSampler" indices: Any = MISSING generator: Any = None @dataclass class WeightedRandomSamplerConf: _target_: str = "torch.utils.data.sampler.WeightedRandomSampler" weights: Any = MISSING num_samples: Any = MISSING replacement: Any = True generator: Any = None
#!/usr/bin/env python import os import shutil import sys from setuptools import setup, find_packages readme = open('README.rst').read() VERSION = '0.0.2' setup( # Metadata name='torchcontrib', version=VERSION, author='PyTorch Core Team and Contributors', author_email='[email protected]', url='https://github.com/pytorch/contrib', description='implementations of ideas from recent papers', long_description=readme, license='BSD', # Package info packages=find_packages(exclude=('test',)), zip_safe=True, )
import re import functools from copy import deepcopy import torch from torch.autograd import Variable from torch import sparse from torch import optim from torch import nn import torchcontrib.optim as contriboptim from .common import TestCase, run_tests from torch.utils import data def rosenbrock(tensor): x, y = tensor return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2 def drosenbrock(tensor): x, y = tensor return torch.DoubleTensor((-400 * x * (y - x ** 2) - 2 * (1 - x), 200 * (y - x ** 2))) def wrap_old_fn(old_fn, **config): def wrapper(closure, params, state): return old_fn(closure, params, config, state) return wrapper class TestSWA(TestCase): # Pavel: I slightly update the _test_... functions to (1) remove the # legacy-related parts and (2) add oprimizer.swap_swa_sgd() in the end of # optimization def _test_rosenbrock(self, constructor, automode=True): # automode shows wether we need to update SWA params manually params = torch.tensor([1.5, 1.5], requires_grad=True) optimizer = constructor([params]) solution = torch.tensor([1., 1.]) initial_dist = params.data.dist(solution) def eval(): # SWA optimizer.zero_grad() loss = rosenbrock(params) loss.backward() # loss.backward() will give **slightly** different # gradients, than drosenbtock, because of a different ordering # of floating point operations. In most cases it doesn't matter, # but some optimizers are so sensitive that they can temporarily # diverge up to 1e-4, just to converge again. This makes the # comparison more stable. params.grad.data.copy_(drosenbrock(params.data)) return loss for i in range(2000): optimizer.step(eval) if not automode: optimizer.update_swa() optimizer.swap_swa_sgd() self.assertLessEqual(params.data.dist(solution), initial_dist) def _test_rosenbrock_sparse(self, constructor, sparse_only=False): params_t = torch.Tensor([1.5, 1.5]) params = torch.tensor([1.5, 1.5], requires_grad=True) optimizer = constructor([params]) if not sparse_only: params_c = params.detach().clone().requires_grad_() optimizer_c = constructor([params_c]) solution = torch.tensor([1., 1.]) initial_dist = params.data.dist(solution) def eval(params, sparse_grad, w): # Depending on w, provide only the x or y gradient optimizer.zero_grad() loss = rosenbrock(params) loss.backward() grad = drosenbrock(params.data) # NB: We torture test the optimizer by returning an # uncoalesced sparse tensor if w: i = torch.LongTensor([[0, 0]]) x = grad[0] v = torch.DoubleTensor([x / 4., x - x / 4.]) else: i = torch.LongTensor([[1, 1]]) y = grad[1] v = torch.DoubleTensor([y - y / 4., y / 4.]) x = sparse.DoubleTensor(i, v, torch.Size([2])) if sparse_grad: params.grad.data = x else: params.grad.data = x.to_dense() return loss for i in range(2000): # Do cyclic coordinate descent w = i % 2 optimizer.step(functools.partial(eval, params, True, w)) if not sparse_only: optimizer_c.step(functools.partial(eval, params_c, False, w)) self.assertEqual(params.data, params_c.data) self.assertLessEqual(params.data.dist(solution), initial_dist) def _test_basic_cases_template(self, weight, bias, input, constructor): weight = weight.requires_grad_() bias = bias.requires_grad_() optimizer = constructor(weight, bias) # to check if the optimizer can be printed as a string optimizer.__repr__() def fn(): optimizer.zero_grad() y = weight.mv(input) if y.is_cuda and bias.is_cuda and y.get_device() != bias.get_device(): y = y.cuda(bias.get_device()) loss = (y + bias).pow(2).sum() loss.backward() return loss initial_value = fn().item() for i in range(200): optimizer.step(fn) self.assertLess(fn().item(), initial_value) def _test_state_dict(self, weight, bias, input, constructor): weight = weight.requires_grad_() bias = bias.requires_grad_() def fn_base(optimizer, weight, bias): optimizer.zero_grad() i = input_cuda if weight.is_cuda else input loss = (weight.mv(i) + bias).pow(2).sum() loss.backward() return loss optimizer = constructor(weight, bias) fn = functools.partial(fn_base, optimizer, weight, bias) # Prime the optimizer optimizer.update_swa() for i in range(20): optimizer.step(fn) # Clone the weights and construct new optimizer for them weight_c = weight.detach().clone().requires_grad_() bias_c = bias.detach().clone().requires_grad_() optimizer_c = constructor(weight_c, bias_c) fn_c = functools.partial(fn_base, optimizer_c, weight_c, bias_c) # Load state dict state_dict = deepcopy(optimizer.state_dict()) state_dict_c = deepcopy(optimizer.state_dict()) optimizer_c.load_state_dict(state_dict_c) self.assertEqual(optimizer.optimizer.state_dict(), optimizer_c.optimizer.state_dict()) # Run both optimizations in parallel for i in range(20): optimizer.optimizer.step(fn) optimizer_c.optimizer.step(fn_c) self.assertEqual(weight, weight_c) self.assertEqual(bias, bias_c) # check that averages also coincide optimizer.swap_swa_sgd() optimizer_c.swap_swa_sgd() self.assertEqual(weight, weight_c) self.assertEqual(bias, bias_c) optimizer.swap_swa_sgd() optimizer_c.swap_swa_sgd() # Make sure state dict wasn't modified self.assertEqual(state_dict, state_dict_c) # Check that state dict can be loaded even when we cast parameters # to a different type and move to a different device. if not torch.cuda.is_available(): return input_cuda = Variable(input.data.float().cuda()) weight_cuda = Variable(weight.data.float().cuda(), requires_grad=True) bias_cuda = Variable(bias.data.float().cuda(), requires_grad=True) optimizer_cuda = constructor(weight_cuda, bias_cuda) fn_cuda = functools.partial(fn_base, optimizer_cuda, weight_cuda, bias_cuda) state_dict = deepcopy(optimizer.state_dict()) state_dict_c = deepcopy(optimizer.state_dict()) optimizer_cuda.load_state_dict(state_dict_c) # Make sure state dict wasn't modified self.assertEqual(state_dict, state_dict_c) for i in range(20): optimizer.step(fn) optimizer_cuda.step(fn_cuda) self.assertEqual(weight, weight_cuda) self.assertEqual(bias, bias_cuda) def _test_basic_cases(self, constructor, ignore_multidevice=False): self._test_state_dict( torch.randn(10, 5), torch.randn(10), torch.randn(5), constructor ) self._test_basic_cases_template( torch.randn(10, 5), torch.randn(10), torch.randn(5), constructor ) # non-contiguous parameters self._test_basic_cases_template( torch.randn(10, 5, 2)[..., 0], torch.randn(10, 2)[..., 0], torch.randn(5), constructor ) # CUDA if not torch.cuda.is_available(): return self._test_basic_cases_template( torch.randn(10, 5).cuda(), torch.randn(10).cuda(), torch.randn(5).cuda(), constructor ) # Multi-GPU if not torch.cuda.device_count() > 1 or ignore_multidevice: return self._test_basic_cases_template( torch.randn(10, 5).cuda(0), torch.randn(10).cuda(1), torch.randn(5).cuda(0), constructor ) def _build_params_dict(self, weight, bias, **kwargs): return [dict(params=[weight]), dict(params=[bias], **kwargs)] def _build_params_dict_single(self, weight, bias, **kwargs): return [dict(params=bias, **kwargs)] # Test SWA def test_swa(self): def sgd_constructor(params): sgd = optim.SGD(params, lr=1e-3) return contriboptim.SWA( sgd, swa_start=1000, swa_freq=1, swa_lr=1e-3) def sgd_manual_constructor(params): sgd = optim.SGD(params, lr=1e-3) return contriboptim.SWA(sgd) def sgd_momentum_constructor(params): sgd = optim.SGD(params, lr=1e-3, momentum=0.9, weight_decay=1e-4) return contriboptim.SWA( sgd, swa_start=1000, swa_freq=1, swa_lr=1e-3) def adam_constructor(params): adam = optim.Adam(params, lr=1e-2) return contriboptim.SWA( adam, swa_start=1000, swa_freq=1, swa_lr=1e-2) def adadelta_constructor(params): adadelta = optim.Adadelta(params) return contriboptim.SWA( adadelta, swa_start=1000, swa_freq=1) def adagrad_constructor(params): adagrad = optim.Adagrad(params, lr=1e-1) return contriboptim.SWA( adagrad, swa_start=1000, swa_freq=1, swa_lr=1e-2) def adamax_constructor(params): adamax = optim.Adamax(params, lr=1e-1) return contriboptim.SWA( adamax, swa_start=1000, swa_freq=1, swa_lr=1e-2) def rmsprop_constructor(params): rmsprop = optim.RMSprop(params, lr=1e-2) return contriboptim.SWA( rmsprop, swa_start=1000, swa_freq=1, swa_lr=1e-3) def rprop_constructor(params): rprop = optim.Rprop(params, lr=1e-2) return contriboptim.SWA( rprop, swa_start=1000, swa_freq=1, swa_lr=1e-3) def asgd_constructor(params): asgd = optim.ASGD(params, lr=1e-3) return contriboptim.SWA( asgd, swa_start=1000, swa_freq=1, swa_lr=1e-3) def lbfgs_constructor(params): lbfgs = optim.LBFGS(params, lr=5e-2, max_iter=5) return contriboptim.SWA( lbfgs, swa_start=1000, swa_freq=1, swa_lr=1e-3) auto_constructor_list = [sgd_constructor, sgd_momentum_constructor, adam_constructor, adadelta_constructor, adagrad_constructor, adamax_constructor, rmsprop_constructor, rprop_constructor, asgd_constructor, lbfgs_constructor] for i, constructor in enumerate(auto_constructor_list): self._test_rosenbrock(constructor) self._test_basic_cases( lambda weight, bias: constructor([weight, bias]), ignore_multidevice=(constructor == lbfgs_constructor) ) if i < len(auto_constructor_list) - 1: self._test_basic_cases( lambda weight, bias: constructor( self._build_params_dict(weight, bias, lr=1e-2))) self._test_basic_cases( lambda weight, bias: constructor( self._build_params_dict_single(weight, bias, lr=1e-2))) self._test_rosenbrock(sgd_manual_constructor, automode=False) def _define_vars_loss_opt(self): x = Variable(torch.Tensor([5., 2.]), requires_grad=True) y = Variable(torch.Tensor([3., 7.]), requires_grad=True) def loss_fun(a, b): return torch.sum(a * b)**2 opt = optim.SGD([{'params': [x]}, {'params': [y], 'lr': 1e-3}], lr=1e-2, momentum=0.9) return x, y, loss_fun, opt @staticmethod def _update_test_vars(i, swa_freq, swa_start, n_avg, x_sum, y_sum, x, y, upd_fun): if i % swa_freq == 0 and i > swa_start: upd_fun() n_avg += 1 x_sum += x.data y_sum += y.data return n_avg, x_sum, y_sum def test_swa_auto(self): # Tests SWA in Auto mode: values of x and y after opt.swap_swa_sgd() # should be equal to the manually computed averages x, y, loss_fun, opt = self._define_vars_loss_opt() swa_start = 5 swa_freq = 2 opt = contriboptim.SWA(opt, swa_start=swa_start, swa_freq=swa_freq, swa_lr=0.001) x_sum = torch.zeros_like(x) y_sum = torch.zeros_like(y) n_avg = 0 for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() n_avg, x_sum, y_sum = self._update_test_vars( i, swa_freq, swa_start, n_avg, x_sum, y_sum, x, y, upd_fun=lambda: None) opt.swap_swa_sgd() x_avg = x_sum / n_avg y_avg = y_sum / n_avg self.assertEqual(x_avg, x) self.assertEqual(y_avg, y) def test_swa_manual(self): # Tests SWA in manual mode: values of x and y after opt.swap_swa_sgd() # should be equal to the manually computed averages x, y, loss_fun, opt = self._define_vars_loss_opt() opt = contriboptim.SWA(opt) swa_start = 5 swa_freq = 2 x_sum = torch.zeros_like(x) y_sum = torch.zeros_like(y) n_avg = 0 for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() n_avg, x_sum, y_sum = self._update_test_vars( i, swa_freq, swa_start, n_avg, x_sum, y_sum, x, y, upd_fun=opt.update_swa) opt.swap_swa_sgd() x_avg = x_sum / n_avg y_avg = y_sum / n_avg self.assertEqual(x_avg, x) self.assertEqual(y_avg, y) def test_swa_manual_group(self): # Tests SWA in manual mode with only y param group updated: # value of x should not change after opt.swap_swa_sgd() and y should # be equal to the manually computed average x, y, loss_fun, opt = self._define_vars_loss_opt() opt = contriboptim.SWA(opt) swa_start = 5 swa_freq = 2 y_sum = torch.zeros_like(y) n_avg = 0 for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() n_avg, _, y_sum = self._update_test_vars( i, swa_freq, swa_start, n_avg, 0, y_sum, x, y, upd_fun=lambda: opt.update_swa_group(opt.param_groups[1])) x_before_swap = x.data.clone() with self.assertWarnsRegex(re.escape(r"SWA wasn't applied to param {}".format(x))): opt.swap_swa_sgd() y_avg = y_sum / n_avg self.assertEqual(y_avg, y) self.assertEqual(x_before_swap, x) def test_swa_auto_group_added_during_run(self): # Tests SWA in Auto mode with the second param group added after several # optimizations steps. The expected behavior is that the averaging for # the second param group starts at swa_start steps after it is added. # For the first group averaging should start swa_start steps after the # first step of the optimizer. x, y, loss_fun, _ = self._define_vars_loss_opt() opt = optim.SGD([x], lr=1e-3, momentum=0.9) swa_start = 5 swa_freq = 2 opt = contriboptim.SWA(opt, swa_start=swa_start, swa_freq=swa_freq, swa_lr=0.001) x_sum = torch.zeros_like(x) y_sum = torch.zeros_like(y) x_n_avg = 0 y_n_avg = 0 x_step = 0 for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() x_step += 1 if i % swa_freq == 0 and i > swa_start: x_n_avg += 1 x_sum += x.data x_avg = x_sum / x_n_avg opt.add_param_group({'params': y, 'lr': 1e-4}) for y_step in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() x_step += 1 if y_step % swa_freq == 0 and y_step > swa_start: y_n_avg += 1 y_sum += y.data if x_step % swa_freq == 0 and x_step > swa_start: x_n_avg += 1 x_sum += x.data x_avg = x_sum / x_n_avg opt.swap_swa_sgd() x_avg = x_sum / x_n_avg y_avg = y_sum / y_n_avg self.assertEqual(x_avg, x) self.assertEqual(y_avg, y) def test_swa_lr(self): # Tests SWA learning rate: in auto mode after swa_start steps the # learning rate should be changed to swa_lr; in manual mode swa_lr # must be ignored # Auto mode x, y, loss_fun, opt = self._define_vars_loss_opt() swa_start = 5 swa_freq = 2 initial_lr = opt.param_groups[0]["lr"] swa_lr = initial_lr * 0.1 opt = contriboptim.SWA(opt, swa_start=swa_start, swa_freq=swa_freq, swa_lr=swa_lr) for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() lr = opt.param_groups[0]["lr"] if i > swa_start: self.assertEqual(lr, swa_lr) else: self.assertEqual(lr, initial_lr) # Manual Mode x, y, loss, opt = self._define_vars_loss_opt() initial_lr = opt.param_groups[0]["lr"] swa_lr = initial_lr * 0.1 with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(opt, swa_lr=swa_lr) for i in range(1, 11): opt.zero_grad() loss = loss_fun(x, y) loss.backward() opt.step() lr = opt.param_groups[0]["lr"] self.assertEqual(lr, initial_lr) def test_swa_auto_mode_detection(self): # Tests that SWA mode (auto or manual) is chosen correctly based on # parameters provided # Auto mode x, y, loss_fun, base_opt = self._define_vars_loss_opt() swa_start = 5 swa_freq = 2 swa_lr = 0.001 opt = contriboptim.SWA( base_opt, swa_start=swa_start, swa_freq=swa_freq, swa_lr=swa_lr) self.assertEqual(opt._auto_mode, True) opt = contriboptim.SWA(base_opt, swa_start=swa_start, swa_freq=swa_freq) self.assertEqual(opt._auto_mode, True) with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(base_opt, swa_start=swa_start, swa_lr=swa_lr) self.assertEqual(opt._auto_mode, False) with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(base_opt, swa_freq=swa_freq, swa_lr=swa_lr) self.assertEqual(opt._auto_mode, False) with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(base_opt, swa_start=swa_start) self.assertEqual(opt._auto_mode, False) with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(base_opt, swa_freq=swa_freq) self.assertEqual(opt._auto_mode, False) with self.assertWarnsRegex("Some of swa_start, swa_freq is None"): opt = contriboptim.SWA(base_opt, swa_lr=swa_lr) self.assertEqual(opt._auto_mode, False) def test_swa_raises(self): # Tests that SWA raises errors for wrong parameter values x, y, loss_fun, opt = self._define_vars_loss_opt() with self.assertRaisesRegex( ValueError, "Invalid SWA learning rate: -0.0001"): opt = contriboptim.SWA(opt, swa_start=1, swa_freq=2, swa_lr=-1e-4) with self.assertRaisesRegex( ValueError, "Invalid swa_freq: 0"): opt = contriboptim.SWA(opt, swa_start=1, swa_freq=0, swa_lr=1e-4) with self.assertRaisesRegex( ValueError, "Invalid swa_start: -1"): opt = contriboptim.SWA(opt, swa_start=-1, swa_freq=0, swa_lr=1e-4) # bn_update test def _test_bn_update(self, data_tensor, dnn, device, label_tensor=None): class DatasetFromTensors(data.Dataset): def __init__(self, X, y=None): self.X = X self.y = y self.N = self.X.shape[0] def __getitem__(self, index): x = self.X[index] if self.y is None: return x else: y = self.y[index] return x, y def __len__(self): return self.N with_y = label_tensor is not None ds = DatasetFromTensors(data_tensor, y=label_tensor) dl = data.DataLoader(ds, batch_size=5, shuffle=True) preactivation_sum = torch.zeros(dnn.n_features, device=device) preactivation_squared_sum = torch.zeros(dnn.n_features, device=device) total_num = 0 for x in dl: if with_y: x, _ = x x = x.to(device) dnn(x) preactivations = dnn.compute_preactivation(x) if len(preactivations.shape) == 4: preactivations = preactivations.transpose(1, 3) preactivations = preactivations.reshape(-1, dnn.n_features) total_num += preactivations.shape[0] preactivation_sum += torch.sum(preactivations, dim=0) preactivation_squared_sum += torch.sum(preactivations**2, dim=0) preactivation_mean = preactivation_sum / total_num preactivation_var = preactivation_squared_sum / total_num preactivation_var = preactivation_var - preactivation_mean**2 swa = contriboptim.SWA(optim.SGD(dnn.parameters(), lr=1e-3)) swa.bn_update(dl, dnn, device=device) self.assertEqual(preactivation_mean, dnn.bn.running_mean) self.assertEqual(preactivation_var, dnn.bn.running_var, prec=1e-1) def test_bn_update(self): def test(net_cls, x_shape, y_shape, device): x = torch.rand(x_shape, device=device) y = torch.rand(y_shape, device=device) dnn = net_cls().to(device) orig_momentum = dnn.bn.momentum dnn.train() self._test_bn_update(x, dnn, device) self._test_bn_update(x, dnn, device, label_tensor=y) self.assertTrue(dnn.training) # check that bn_update preserves eval mode dnn.eval() self._test_bn_update(x, dnn, device) self.assertFalse(dnn.training) # check that momentum is preserved self.assertEqual(dnn.bn.momentum, orig_momentum) # Test bn_update for fully-connected and convolutional networks with # BatchNorm1d and BatchNorm2d respectively objects = 100 input_features = 5 class DNN(nn.Module): def __init__(self): super(DNN, self).__init__() self.n_features = 100 self.fc1 = nn.Linear(input_features, self.n_features) self.bn = nn.BatchNorm1d(self.n_features) def compute_preactivation(self, x): return self.fc1(x) def forward(self, x): x = self.fc1(x) x = self.bn(x) return x test(DNN, (objects, input_features), objects, 'cpu') if torch.cuda.is_available(): test(DNN, (objects, input_features), objects, 'cuda') # Test bn_update for convolutional network and BatchNorm2d objects = 100 channels = 3 height, width = 5, 5 class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.n_features = 10 self.conv1 = nn.Conv2d(channels, self.n_features, kernel_size=3, padding=1) self.bn = nn.BatchNorm2d(self.n_features, momentum=0.3) def compute_preactivation(self, x): return self.conv1(x) def forward(self, x): x = self.conv1(x) x = self.bn(x) return x test(CNN, (objects, channels, height, width), objects, 'cpu') if torch.cuda.is_available(): test(CNN, (objects, channels, height, width), objects, 'cuda') if __name__ == '__main__': run_tests()
import unittest import torch import torchcontrib import torchcontrib.nn as contrib_nn import torchcontrib.nn.functional as contrib_F from torch.autograd import gradcheck, gradgradcheck from .common import run_tests, TestCase class TestNN(TestCase): def assertGradAndGradgradChecks(self, apply_fn, inputs): # call assert function rather than returning a bool since it's nicer # if we get whether this failed on the gradcheck or the gradgradcheck. self.assertTrue(gradcheck(apply_fn, inputs)) self.assertTrue(gradgradcheck(apply_fn, inputs)) def test_film(self): m = contrib_nn.FiLM() input_1d = torch.randn(4, 10, 2, requires_grad=True) input_2d = torch.randn(4, 10, 2, 2, requires_grad=True) input_3d = torch.randn(4, 10, 2, 2, 2, requires_grad=True) ones = torch.ones(4, 10) zeros = torch.zeros(4, 10) half_ones_half_zeros = torch.cat([torch.ones(4, 5), torch.zeros(4, 5)], 1) half_ones_half_neg_ones = torch.cat([torch.ones(4, 5), torch.full((4, 5), -1)], 1) for inp in [input_1d, input_2d, input_3d]: self.assertGradAndGradgradChecks(lambda x: contrib_F.film(x, ones, ones), (inp,)) output = m(inp, ones, zeros) self.assertEqual(contrib_F.film(inp, ones, zeros), output) self.assertEqual(inp, output) output = m(inp, zeros, ones) self.assertEqual(contrib_F.film(inp, zeros, ones), output) self.assertEqual(torch.ones_like(output), output) output = m(inp, -2 * ones, 3 * ones) self.assertEqual(contrib_F.film(inp, -2 * ones, 3 * ones), output) self.assertEqual((-2 * inp) + 3, output) output = m(inp, half_ones_half_zeros, half_ones_half_neg_ones) self.assertEqual(contrib_F.film(inp, half_ones_half_zeros, half_ones_half_neg_ones), output) self.assertEqual(output.sum(), inp[:, :5].sum()) if __name__ == '__main__': run_tests()
# Pavel: copied without changes from pytorch/test/common.py import sys import os import platform import re import gc import types import inspect import argparse import unittest import warnings import random import contextlib from functools import wraps from itertools import product from copy import deepcopy from numbers import Number import __main__ import errno import torch import torch.cuda from torch._utils_internal import get_writable_path from torch._six import string_classes, inf import torch.backends.cudnn import torch.backends.mkl torch.set_default_tensor_type('torch.DoubleTensor') if torch.cuda.is_available(): torch.backends.cudnn.disable_global_flags() parser = argparse.ArgumentParser(add_help=False) parser.add_argument('--seed', type=int, default=1234) parser.add_argument('--accept', action='store_true') args, remaining = parser.parse_known_args() SEED = args.seed ACCEPT = args.accept UNITTEST_ARGS = [sys.argv[0]] + remaining torch.manual_seed(SEED) def run_tests(argv=UNITTEST_ARGS): unittest.main(argv=argv) PY3 = sys.version_info > (3, 0) PY34 = sys.version_info >= (3, 4) TEST_CUDA = torch.cuda.is_available() TEST_MULTIGPU = TEST_CUDA and torch.cuda.device_count() >= 2 CUDA_DEVICE = TEST_CUDA and torch.device("cuda:0") TEST_CUDNN = TEST_CUDA and torch.backends.cudnn.is_acceptable(torch.tensor(1., device=CUDA_DEVICE)) TEST_CUDNN_VERSION = TEST_CUDNN and torch.backends.cudnn.version() def _check_module_exists(name): r"""Returns if a top-level module with :attr:`name` exists *without** importing it. This is generally safer than try-catch block around a `import X`. It avoids third party libraries breaking assumptions of some of our tests, e.g., setting multiprocessing start method when imported (see librosa/#747, torchvision/#544). """ if not PY3: # Python 2 import imp try: imp.find_module(name) return True except ImportError: return False elif PY34: # Python [3, 3.4) import importlib loader = importlib.find_loader(name) return loader is not None else: # Python >= 3.4 import importlib spec = importlib.util.find_spec(name) return spec is not None TEST_NUMPY = _check_module_exists('numpy') TEST_SCIPY = _check_module_exists('scipy') TEST_MKL = torch.backends.mkl.is_available() # On Py2, importing librosa 0.6.1 triggers a TypeError (if using newest joblib) # see librosa/librosa#729. # TODO: allow Py2 when librosa 0.6.2 releases TEST_LIBROSA = _check_module_exists('librosa') and PY3 NO_MULTIPROCESSING_SPAWN = os.environ.get('NO_MULTIPROCESSING_SPAWN', '0') == '1' if TEST_NUMPY: import numpy def skipIfNoLapack(fn): @wraps(fn) def wrapper(*args, **kwargs): try: fn(*args, **kwargs) except Exception as e: if 'Lapack library not found' in e.args[0]: raise unittest.SkipTest('Compiled without Lapack') raise return wrapper def suppress_warnings(fn): @wraps(fn) def wrapper(*args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter("ignore") fn(*args, **kwargs) return wrapper def get_cpu_type(type_name): module, name = type_name.rsplit('.', 1) assert module == 'torch.cuda' return getattr(torch, name) def get_gpu_type(type_name): if isinstance(type_name, type): type_name = '{}.{}'.format(type_name.__module__, type_name.__name__) module, name = type_name.rsplit('.', 1) assert module == 'torch' return getattr(torch.cuda, name) def to_gpu(obj, type_map={}): if isinstance(obj, torch.Tensor): assert obj.is_leaf t = type_map.get(obj.type(), get_gpu_type(obj.type())) with torch.no_grad(): res = obj.clone().type(t) res.requires_grad = obj.requires_grad return res elif torch.is_storage(obj): return obj.new().resize_(obj.size()).copy_(obj) elif isinstance(obj, list): return [to_gpu(o, type_map) for o in obj] elif isinstance(obj, tuple): return tuple(to_gpu(o, type_map) for o in obj) else: return deepcopy(obj) def get_function_arglist(func): return inspect.getargspec(func).args def set_rng_seed(seed): torch.manual_seed(seed) random.seed(seed) if TEST_NUMPY: numpy.random.seed(seed) @contextlib.contextmanager def freeze_rng_state(): rng_state = torch.get_rng_state() if torch.cuda.is_available(): cuda_rng_state = torch.cuda.get_rng_state() yield if torch.cuda.is_available(): torch.cuda.set_rng_state(cuda_rng_state) torch.set_rng_state(rng_state) def iter_indices(tensor): if tensor.dim() == 0: return range(0) if tensor.dim() == 1: return range(tensor.size(0)) return product(*(range(s) for s in tensor.size())) def is_iterable(obj): try: iter(obj) return True except TypeError: return False class TestCase(unittest.TestCase): precision = 1e-5 def setUp(self): set_rng_seed(SEED) def assertTensorsSlowEqual(self, x, y, prec=None, message=''): max_err = 0 self.assertEqual(x.size(), y.size()) for index in iter_indices(x): max_err = max(max_err, abs(x[index] - y[index])) self.assertLessEqual(max_err, prec, message) def safeToDense(self, t): r = self.safeCoalesce(t) return r.to_dense() def safeCoalesce(self, t): tc = t.coalesce() self.assertEqual(tc.to_dense(), t.to_dense()) self.assertTrue(tc.is_coalesced()) # Our code below doesn't work when nnz is 0, because # then it's a 0D tensor, not a 2D tensor. if t._nnz() == 0: self.assertEqual(t._indices(), tc._indices()) self.assertEqual(t._values(), tc._values()) return tc value_map = {} for idx, val in zip(t._indices().t(), t._values()): idx_tup = tuple(idx.tolist()) if idx_tup in value_map: value_map[idx_tup] += val else: value_map[idx_tup] = val.clone() if isinstance(val, torch.Tensor) else val new_indices = sorted(list(value_map.keys())) new_values = [value_map[idx] for idx in new_indices] if t._values().ndimension() < 2: new_values = t._values().new(new_values) else: new_values = torch.stack(new_values) new_indices = t._indices().new(new_indices).t() tg = t.new(new_indices, new_values, t.size()) self.assertEqual(tc._indices(), tg._indices()) self.assertEqual(tc._values(), tg._values()) if t.is_coalesced(): self.assertEqual(tc._indices(), t._indices()) self.assertEqual(tc._values(), t._values()) return tg def assertEqual(self, x, y, prec=None, message='', allow_inf=False): if isinstance(prec, str) and message == '': message = prec prec = None if prec is None: prec = self.precision if isinstance(x, torch.Tensor) and isinstance(y, Number): self.assertEqual(x.item(), y, prec, message, allow_inf) elif isinstance(y, torch.Tensor) and isinstance(x, Number): self.assertEqual(x, y.item(), prec, message, allow_inf) elif isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): def assertTensorsEqual(a, b): super(TestCase, self).assertEqual(a.size(), b.size(), message) if a.numel() > 0: b = b.type_as(a) b = b.cuda(device=a.get_device()) if a.is_cuda else b.cpu() # check that NaNs are in the same locations nan_mask = a != a self.assertTrue(torch.equal(nan_mask, b != b), message) diff = a - b diff[nan_mask] = 0 # TODO: implement abs on CharTensor if diff.is_signed() and 'CharTensor' not in diff.type(): diff = diff.abs() max_err = diff.max() self.assertLessEqual(max_err, prec, message) super(TestCase, self).assertEqual(x.is_sparse, y.is_sparse, message) if x.is_sparse: x = self.safeCoalesce(x) y = self.safeCoalesce(y) assertTensorsEqual(x._indices(), y._indices()) assertTensorsEqual(x._values(), y._values()) else: assertTensorsEqual(x, y) elif isinstance(x, string_classes) and isinstance(y, string_classes): super(TestCase, self).assertEqual(x, y, message) elif type(x) == set and type(y) == set: super(TestCase, self).assertEqual(x, y, message) elif is_iterable(x) and is_iterable(y): super(TestCase, self).assertEqual(len(x), len(y), message) for x_, y_ in zip(x, y): self.assertEqual(x_, y_, prec, message) elif isinstance(x, bool) and isinstance(y, bool): super(TestCase, self).assertEqual(x, y, message) elif isinstance(x, Number) and isinstance(y, Number): if abs(x) == inf or abs(y) == inf: if allow_inf: super(TestCase, self).assertEqual(x, y, message) else: self.fail("Expected finite numeric values - x={}, y={}".format(x, y)) return super(TestCase, self).assertLessEqual(abs(x - y), prec, message) else: super(TestCase, self).assertEqual(x, y, message) def assertAlmostEqual(self, x, y, places=None, msg=None, delta=None, allow_inf=None): prec = delta if places: prec = 10**(-places) self.assertEqual(x, y, prec, msg, allow_inf) def assertNotEqual(self, x, y, prec=None, message=''): if isinstance(prec, str) and message == '': message = prec prec = None if prec is None: prec = self.precision if isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): if x.size() != y.size(): super(TestCase, self).assertNotEqual(x.size(), y.size()) self.assertGreater(x.numel(), 0) y = y.type_as(x) y = y.cuda(device=x.get_device()) if x.is_cuda else y.cpu() nan_mask = x != x if torch.equal(nan_mask, y != y): diff = x - y if diff.is_signed(): diff = diff.abs() diff[nan_mask] = 0 max_err = diff.max() self.assertGreaterEqual(max_err, prec, message) elif type(x) == str and type(y) == str: super(TestCase, self).assertNotEqual(x, y) elif is_iterable(x) and is_iterable(y): super(TestCase, self).assertNotEqual(x, y) else: try: self.assertGreaterEqual(abs(x - y), prec, message) return except (TypeError, AssertionError): pass super(TestCase, self).assertNotEqual(x, y, message) def assertObjectIn(self, obj, iterable): for elem in iterable: if id(obj) == id(elem): return raise AssertionError("object not found in iterable") # TODO: Support context manager interface # NB: The kwargs forwarding to callable robs the 'subname' parameter. # If you need it, manually apply your callable in a lambda instead. def assertExpectedRaises(self, exc_type, callable, *args, **kwargs): subname = None if 'subname' in kwargs: subname = kwargs['subname'] del kwargs['subname'] try: callable(*args, **kwargs) except exc_type as e: self.assertExpected(str(e), subname) return # Don't put this in the try block; the AssertionError will catch it self.fail(msg="Did not raise when expected to") @contextlib.contextmanager def assertWarns(self, msg=''): r""" As a context manager, test if wrapped code raises a warning. """ with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") # allow any warning to be raised yield self.assertTrue(len(ws) > 0, msg) @contextlib.contextmanager def assertWarnsRegex(self, regex, msg=''): r""" As a context manager, test if wrapped code raises any warning with message that contains the regex pattern :attr:`regex`. """ with warnings.catch_warnings(record=True) as ws: warnings.simplefilter("always") # allow any warning to be raised yield self.assertTrue(len(ws) > 0, msg) found = any(re.search(regex, str(w.message)) is not None for w in ws) self.assertTrue(found, msg) def assertExpected(self, s, subname=None): r""" Test that a string matches the recorded contents of a file derived from the name of this test and subname. This file is placed in the 'expect' directory in the same directory as the test script. You can automatically update the recorded test output using --accept. If you call this multiple times in a single function, you must give a unique subname each time. """ if not (isinstance(s, str) or (sys.version_info[0] == 2 and isinstance(s, unicode))): raise TypeError("assertExpected is strings only") def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] return text # NB: we take __file__ from the module that defined the test # class, so we place the expect directory where the test script # lives, NOT where test/common.py lives. This doesn't matter in # PyTorch where all test scripts are in the same directory as # test/common.py, but it matters in onnx-pytorch module_id = self.__class__.__module__ munged_id = remove_prefix(self.id(), module_id + ".") test_file = os.path.realpath(sys.modules[module_id].__file__) expected_file = os.path.join(os.path.dirname(test_file), "expect", munged_id) if subname: expected_file += "-" + subname expected_file += ".expect" expected = None def accept_output(update_type): print("Accepting {} for {}:\n\n{}".format(update_type, munged_id, s)) with open(expected_file, 'w') as f: f.write(s) try: with open(expected_file) as f: expected = f.read() except IOError as e: if e.errno != errno.ENOENT: raise elif ACCEPT: return accept_output("output") else: raise RuntimeError( ("I got this output for {}:\n\n{}\n\n" "No expect file exists; to accept the current output, run:\n" "python {} {} --accept").format(munged_id, s, __main__.__file__, munged_id)) if ACCEPT: if expected != s: return accept_output("updated output") else: if hasattr(self, "assertMultiLineEqual"): # Python 2.7 only # NB: Python considers lhs "old" and rhs "new". self.assertMultiLineEqual(expected, s) else: self.assertEqual(s, expected) if sys.version_info < (3, 2): # assertRegexpMatches renamed to assertRegex in 3.2 assertRegex = unittest.TestCase.assertRegexpMatches # assertRaisesRegexp renamed to assertRaisesRegex in 3.2 assertRaisesRegex = unittest.TestCase.assertRaisesRegexp def download_file(url, binary=True): if sys.version_info < (3,): from urlparse import urlsplit import urllib2 request = urllib2 error = urllib2 else: from urllib.parse import urlsplit from urllib import request, error filename = os.path.basename(urlsplit(url)[2]) data_dir = get_writable_path(os.path.join(os.path.dirname(__file__), 'data')) path = os.path.join(data_dir, filename) if os.path.exists(path): return path try: data = request.urlopen(url, timeout=15).read() with open(path, 'wb' if binary else 'w') as f: f.write(data) return path except error.URLError: msg = "could not download test file '{}'".format(url) warnings.warn(msg, RuntimeWarning) raise unittest.SkipTest(msg)
from . import nn from . import optim
from .modules import * from . import functional
def film(input, gamma, beta): r"""Applies Feature-wise Linear Modulation to the incoming data. See :class:`~torchcontrib.nn.FiLM` for details. """ if input.dim() < 2: raise ValueError("film expects input to be at least 2-dimensional, but " "got input of size {}".format(tuple(input.size()))) if gamma.dim() != 2 and gamma.size(0) == input.size(0) and gamma.size(1) == input.size(1): raise ValueError("film expects gamma to be a 2-dimensional tensor of " "the same shape as the first two dimensions of input" "gamma of size {} and input of size {}" .format(tuple(gamma.size()), tuple(input.size()))) if beta.dim() != 2 and beta.size(0) == input.size(0) and beta.size(1) == input.size(1): raise ValueError("film expects beta to be a 2-dimensional tensor of " "the same shape as the first two dimensions of input" "beta of size {} and input of size {}" .format(tuple(beta.size()), tuple(input.size()))) view_shape = list(input.size()) for i in range(2, len(view_shape)): view_shape[i] = 1 return gamma.view(view_shape) * input + beta.view(view_shape)
import torch from torch.nn import Module from .. import functional as F class FiLM(Module): r"""Applies Feature-wise Linear Modulation to the incoming data as described in the paper `FiLM: Visual Reasoning with a General Conditioning Layer`_ . .. math:: y_{n,c,*} = \gamma_{n, c} * x_{n,c,*} + \beta_{n,c}, where :math:`\gamma_{n,c}` and :math:`\beta_{n,c}` are scalars and operations are broadcast over any additional dimensions of :math:`x` Shape: - Input: :math:`(N, C, *)` where :math:`*` means any number of additional dimensions - Gammas: :math:`(N, C)` - Betas: :math:`(N, C)` - Output: :math:`(N, C, *)`, same shape as the input Examples:: >>> m = torchcontrib.nn.FiLM() >>> input = e >>> gamma = torch.randn(20) >>> beta = torch.randn(20) >>> output = m(input, gamma, beta) >>> output.size() torch.Size([128, 20, 4, 4]) .. _`FiLM: Visual Reasoning with a General Conditioning Layer`: https://arxiv.org/abs/1709.07871 """ def forward(self, input, gamma, beta): return F.film(input, gamma, beta)
from .linear import FiLM __all__ = ['FiLM']
from collections import defaultdict from itertools import chain from torch.optim import Optimizer import torch import warnings class SWA(Optimizer): def __init__(self, optimizer, swa_start=None, swa_freq=None, swa_lr=None): r"""Implements Stochastic Weight Averaging (SWA). Stochastic Weight Averaging was proposed in `Averaging Weights Leads to Wider Optima and Better Generalization`_ by Pavel Izmailov, Dmitrii Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson (UAI 2018). SWA is implemented as a wrapper class taking optimizer instance as input and applying SWA on top of that optimizer. SWA can be used in two modes: automatic and manual. In the automatic mode SWA running averages are automatically updated every :attr:`swa_freq` steps after :attr:`swa_start` steps of optimization. If :attr:`swa_lr` is provided, the learning rate of the optimizer is reset to :attr:`swa_lr` at every step starting from :attr:`swa_start`. To use SWA in automatic mode provide values for both :attr:`swa_start` and :attr:`swa_freq` arguments. Alternatively, in the manual mode, use :meth:`update_swa` or :meth:`update_swa_group` methods to update the SWA running averages. In the end of training use `swap_swa_sgd` method to set the optimized variables to the computed averages. Args: optimizer (torch.optim.Optimizer): optimizer to use with SWA swa_start (int): number of steps before starting to apply SWA in automatic mode; if None, manual mode is selected (default: None) swa_freq (int): number of steps between subsequent updates of SWA running averages in automatic mode; if None, manual mode is selected (default: None) swa_lr (float): learning rate to use starting from step swa_start in automatic mode; if None, learning rate is not changed (default: None) Examples: >>> # automatic mode >>> base_opt = torch.optim.SGD(model.parameters(), lr=0.1) >>> opt = torchcontrib.optim.SWA( >>> base_opt, swa_start=10, swa_freq=5, swa_lr=0.05) >>> for _ in range(100): >>> opt.zero_grad() >>> loss_fn(model(input), target).backward() >>> opt.step() >>> opt.swap_swa_sgd() >>> # manual mode >>> opt = torchcontrib.optim.SWA(base_opt) >>> for i in range(100): >>> opt.zero_grad() >>> loss_fn(model(input), target).backward() >>> opt.step() >>> if i > 10 and i % 5 == 0: >>> opt.update_swa() >>> opt.swap_swa_sgd() .. note:: SWA does not support parameter-specific values of :attr:`swa_start`, :attr:`swa_freq` or :attr:`swa_lr`. In automatic mode SWA uses the same :attr:`swa_start`, :attr:`swa_freq` and :attr:`swa_lr` for all parameter groups. If needed, use manual mode with :meth:`update_swa_group` to use different update schedules for different parameter groups. .. note:: Call :meth:`swap_swa_sgd` in the end of training to use the computed running averages. .. note:: If you are using SWA to optimize the parameters of a Neural Network containing Batch Normalization layers, you need to update the :attr:`running_mean` and :attr:`running_var` statistics of the Batch Normalization module. You can do so by using `torchcontrib.optim.swa.bn_update` utility. .. note:: See the blogpost https://pytorch.org/blog/stochastic-weight-averaging-in-pytorch/ for an extended description of this SWA implementation. .. note:: The repo https://github.com/izmailovpavel/contrib_swa_examples contains examples of using this SWA implementation. .. _Averaging Weights Leads to Wider Optima and Better Generalization: https://arxiv.org/abs/1803.05407 .. _Improving Consistency-Based Semi-Supervised Learning with Weight Averaging: https://arxiv.org/abs/1806.05594 """ self._auto_mode, (self.swa_start, self.swa_freq) = \ self._check_params(self, swa_start, swa_freq) self.swa_lr = swa_lr if self._auto_mode: if swa_start < 0: raise ValueError("Invalid swa_start: {}".format(swa_start)) if swa_freq < 1: raise ValueError("Invalid swa_freq: {}".format(swa_freq)) else: if self.swa_lr is not None: warnings.warn( "Some of swa_start, swa_freq is None, ignoring swa_lr") # If not in auto mode make all swa parameters None self.swa_lr = None self.swa_start = None self.swa_freq = None if self.swa_lr is not None and self.swa_lr < 0: raise ValueError("Invalid SWA learning rate: {}".format(swa_lr)) self.optimizer = optimizer self.defaults = self.optimizer.defaults self.param_groups = self.optimizer.param_groups self.state = defaultdict(dict) self.opt_state = self.optimizer.state for group in self.param_groups: group['n_avg'] = 0 group['step_counter'] = 0 @staticmethod def _check_params(self, swa_start, swa_freq): params = [swa_start, swa_freq] params_none = [param is None for param in params] if not all(params_none) and any(params_none): warnings.warn( "Some of swa_start, swa_freq is None, ignoring other") for i, param in enumerate(params): if param is not None and not isinstance(param, int): params[i] = int(param) warnings.warn("Casting swa_start, swa_freq to int") return not any(params_none), params def _reset_lr_to_swa(self): if self.swa_lr is None: return for param_group in self.param_groups: if param_group['step_counter'] >= self.swa_start: param_group['lr'] = self.swa_lr def update_swa_group(self, group): r"""Updates the SWA running averages for the given parameter group. Arguments: param_group (dict): Specifies for what parameter group SWA running averages should be updated Examples: >>> # automatic mode >>> base_opt = torch.optim.SGD([{'params': [x]}, >>> {'params': [y], 'lr': 1e-3}], lr=1e-2, momentum=0.9) >>> opt = torchcontrib.optim.SWA(base_opt) >>> for i in range(100): >>> opt.zero_grad() >>> loss_fn(model(input), target).backward() >>> opt.step() >>> if i > 10 and i % 5 == 0: >>> # Update SWA for the second parameter group >>> opt.update_swa_group(opt.param_groups[1]) >>> opt.swap_swa_sgd() """ for p in group['params']: param_state = self.state[p] if 'swa_buffer' not in param_state: param_state['swa_buffer'] = torch.zeros_like(p.data) buf = param_state['swa_buffer'] virtual_decay = 1 / float(group["n_avg"] + 1) diff = (p.data - buf) * virtual_decay buf.add_(diff) group["n_avg"] += 1 def update_swa(self): r"""Updates the SWA running averages of all optimized parameters. """ for group in self.param_groups: self.update_swa_group(group) def swap_swa_sgd(self): r"""Swaps the values of the optimized variables and swa buffers. It's meant to be called in the end of training to use the collected swa running averages. It can also be used to evaluate the running averages during training; to continue training `swap_swa_sgd` should be called again. """ for group in self.param_groups: for p in group['params']: param_state = self.state[p] if 'swa_buffer' not in param_state: # If swa wasn't applied we don't swap params warnings.warn( "SWA wasn't applied to param {}; skipping it".format(p)) continue buf = param_state['swa_buffer'] tmp = torch.empty_like(p.data) tmp.copy_(p.data) p.data.copy_(buf) buf.copy_(tmp) def step(self, closure=None): r"""Performs a single optimization step. In automatic mode also updates SWA running averages. """ self._reset_lr_to_swa() loss = self.optimizer.step(closure) for group in self.param_groups: group["step_counter"] += 1 steps = group["step_counter"] if self._auto_mode: if steps > self.swa_start and steps % self.swa_freq == 0: self.update_swa_group(group) return loss def state_dict(self): r"""Returns the state of SWA as a :class:`dict`. It contains three entries: * opt_state - a dict holding current optimization state of the base optimizer. Its content differs between optimizer classes. * swa_state - a dict containing current state of SWA. For each optimized variable it contains swa_buffer keeping the running average of the variable * param_groups - a dict containing all parameter groups """ opt_state_dict = self.optimizer.state_dict() swa_state = {(id(k) if isinstance(k, torch.Tensor) else k): v for k, v in self.state.items()} opt_state = opt_state_dict["state"] param_groups = opt_state_dict["param_groups"] return {"opt_state": opt_state, "swa_state": swa_state, "param_groups": param_groups} def load_state_dict(self, state_dict): r"""Loads the optimizer state. Args: state_dict (dict): SWA optimizer state. Should be an object returned from a call to `state_dict`. """ swa_state_dict = {"state": state_dict["swa_state"], "param_groups": state_dict["param_groups"]} opt_state_dict = {"state": state_dict["opt_state"], "param_groups": state_dict["param_groups"]} super(SWA, self).load_state_dict(swa_state_dict) self.optimizer.load_state_dict(opt_state_dict) self.opt_state = self.optimizer.state def add_param_group(self, param_group): r"""Add a param group to the :class:`Optimizer` s `param_groups`. This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the :class:`Optimizer` as training progresses. Args: param_group (dict): Specifies what Tensors should be optimized along with group specific optimization options. """ param_group['n_avg'] = 0 param_group['step_counter'] = 0 self.optimizer.add_param_group(param_group) @staticmethod def bn_update(loader, model, device=None): r"""Updates BatchNorm running_mean, running_var buffers in the model. It performs one pass over data in `loader` to estimate the activation statistics for BatchNorm layers in the model. Args: loader (torch.utils.data.DataLoader): dataset loader to compute the activation statistics on. Each data batch should be either a tensor, or a list/tuple whose first element is a tensor containing data. model (torch.nn.Module): model for which we seek to update BatchNorm statistics. device (torch.device, optional): If set, data will be trasferred to :attr:`device` before being passed into :attr:`model`. """ if not _check_bn(model): return was_training = model.training model.train() momenta = {} model.apply(_reset_bn) model.apply(lambda module: _get_momenta(module, momenta)) n = 0 for input in loader: if isinstance(input, (list, tuple)): input = input[0] b = input.size(0) momentum = b / float(n + b) for module in momenta.keys(): module.momentum = momentum if device is not None: input = input.to(device) model(input) n += b model.apply(lambda module: _set_momenta(module, momenta)) model.train(was_training) # BatchNorm utils def _check_bn_apply(module, flag): if issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm): flag[0] = True def _check_bn(model): flag = [False] model.apply(lambda module: _check_bn_apply(module, flag)) return flag[0] def _reset_bn(module): if issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm): module.running_mean = torch.zeros_like(module.running_mean) module.running_var = torch.ones_like(module.running_var) def _get_momenta(module, momenta): if issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm): momenta[module] = module.momentum def _set_momenta(module, momenta): if issubclass(module.__class__, torch.nn.modules.batchnorm._BatchNorm): module.momentum = momenta[module]
from .swa import SWA
VERSION = "0.27.9"
class ApacAIError(Exception): def __init__( self, message=None, http_body=None, http_status=None, json_body=None, headers=None, code=None, ): super(ApacAIError, self).__init__(message) if http_body and hasattr(http_body, "decode"): try: http_body = http_body.decode("utf-8") except BaseException: http_body = ( "<Could not decode body as utf-8. " "Please contact us through our help center at help.apacai.com.>" ) self._message = message self.http_body = http_body self.http_status = http_status self.json_body = json_body self.headers = headers or {} self.code = code self.request_id = self.headers.get("request-id", None) self.error = self.construct_error_object() self.organization = self.headers.get("apacai-organization", None) def __str__(self): msg = self._message or "<empty message>" if self.request_id is not None: return "Request {0}: {1}".format(self.request_id, msg) else: return msg # Returns the underlying `Exception` (base class) message, which is usually # the raw message returned by APACAI's API. This was previously available # in python2 via `error.message`. Unlike `str(error)`, it omits "Request # req_..." from the beginning of the string. @property def user_message(self): return self._message def __repr__(self): return "%s(message=%r, http_status=%r, request_id=%r)" % ( self.__class__.__name__, self._message, self.http_status, self.request_id, ) def construct_error_object(self): if ( self.json_body is None or not isinstance(self.json_body, dict) or "error" not in self.json_body or not isinstance(self.json_body["error"], dict) ): return None return apacai.api_resources.error_object.ErrorObject.construct_from( self.json_body["error"] ) class APIError(ApacAIError): pass class TryAgain(ApacAIError): pass class Timeout(ApacAIError): pass class APIConnectionError(ApacAIError): def __init__( self, message, http_body=None, http_status=None, json_body=None, headers=None, code=None, should_retry=False, ): super(APIConnectionError, self).__init__( message, http_body, http_status, json_body, headers, code ) self.should_retry = should_retry class InvalidRequestError(ApacAIError): def __init__( self, message, param, code=None, http_body=None, http_status=None, json_body=None, headers=None, ): super(InvalidRequestError, self).__init__( message, http_body, http_status, json_body, headers, code ) self.param = param def __repr__(self): return "%s(message=%r, param=%r, code=%r, http_status=%r, " "request_id=%r)" % ( self.__class__.__name__, self._message, self.param, self.code, self.http_status, self.request_id, ) def __reduce__(self): return type(self), ( self._message, self.param, self.code, self.http_body, self.http_status, self.json_body, self.headers, ) class AuthenticationError(ApacAIError): pass class PermissionError(ApacAIError): pass class RateLimitError(ApacAIError): pass class ServiceUnavailableError(ApacAIError): pass class InvalidAPIType(ApacAIError): pass class SignatureVerificationError(ApacAIError): def __init__(self, message, sig_header, http_body=None): super(SignatureVerificationError, self).__init__(message, http_body) self.sig_header = sig_header def __reduce__(self): return type(self), ( self._message, self.sig_header, self.http_body, )
APACAI_LOG = os.environ.get("APACAI_LOG") logger = logging.getLogger("apacai") __all__ = [ "log_info", "log_debug", "log_warn", "logfmt", ] api_key_to_header = ( lambda api, key: {"Authorization": f"Bearer {key}"} if api in (ApiType.OPEN_AI, ApiType.AZURE_AD) else {"api-key": f"{key}"} ) class ApiType(Enum): AZURE = 1 OPEN_AI = 2 AZURE_AD = 3 @staticmethod def from_str(label): if label.lower() == "azure": return ApiType.AZURE elif label.lower() in ("azure_ad", "azuread"): return ApiType.AZURE_AD elif label.lower() in ("open_ai", "apacai"): return ApiType.OPEN_AI else: raise apacai.error.InvalidAPIType( "The API type provided in invalid. Please select one of the supported API types: 'azure', 'azure_ad', 'open_ai'" ) def _console_log_level(): if apacai.log in ["debug", "info"]: return apacai.log elif APACAI_LOG in ["debug", "info"]: return APACAI_LOG else: return None def log_debug(message, **params): msg = logfmt(dict(message=message, **params)) if _console_log_level() == "debug": print(msg, file=sys.stderr) logger.debug(msg) def log_info(message, **params): msg = logfmt(dict(message=message, **params)) if _console_log_level() in ["debug", "info"]: print(msg, file=sys.stderr) logger.info(msg) def log_warn(message, **params): msg = logfmt(dict(message=message, **params)) print(msg, file=sys.stderr) logger.warn(msg) def logfmt(props): def fmt(key, val): # Handle case where val is a bytes or bytesarray if hasattr(val, "decode"): val = val.decode("utf-8") # Check if val is already a string to avoid re-encoding into ascii. if not isinstance(val, str): val = str(val) if re.search(r"\s", val): val = repr(val) # key should already be a string if re.search(r"\s", key): key = repr(key) return "{key}={val}".format(key=key, val=val) return " ".join([fmt(key, val) for key, val in sorted(props.items())]) def get_object_classes(): # This is here to avoid a circular dependency from apacai.object_classes import OBJECT_CLASSES return OBJECT_CLASSES def convert_to_apacai_object( resp, api_key=None, api_version=None, organization=None, engine=None, plain_old_data=False, ): # If we get a ApacAIResponse, we'll want to return a ApacAIObject. response_ms: Optional[int] = None if isinstance(resp, apacai.apacai_response.ApacAIResponse): organization = resp.organization response_ms = resp.response_ms resp = resp.data if plain_old_data: return resp elif isinstance(resp, list): return [ convert_to_apacai_object( i, api_key, api_version, organization, engine=engine ) for i in resp ] elif isinstance(resp, dict) and not isinstance( resp, apacai.apacai_object.ApacAIObject ): resp = resp.copy() klass_name = resp.get("object") if isinstance(klass_name, str): klass = get_object_classes().get( klass_name, apacai.apacai_object.ApacAIObject ) else: klass = apacai.apacai_object.ApacAIObject return klass.construct_from( resp, api_key=api_key, api_version=api_version, organization=organization, response_ms=response_ms, engine=engine, ) else: return resp def convert_to_dict(obj): """Converts a ApacAIObject back to a regular dict. Nested ApacAIObjects are also converted back to regular dicts. :param obj: The ApacAIObject to convert. :returns: The ApacAIObject as a dict. """ if isinstance(obj, list): return [convert_to_dict(i) for i in obj] # This works by virtue of the fact that ApacAIObjects _are_ dicts. The dict # comprehension returns a regular dict and recursively applies the # conversion to each value. elif isinstance(obj, dict): return {k: convert_to_dict(v) for k, v in obj.items()} else: return obj def merge_dicts(x, y): z = x.copy() z.update(y) return z def default_api_key() -> str: if apacai.api_key_path: with open(apacai.api_key_path, "rt") as k: api_key = k.read().strip() if not api_key.startswith("sk-"): raise ValueError(f"Malformed API key in {apacai.api_key_path}.") return api_key elif apacai.api_key is not None: return apacai.api_key else: raise apacai.error.AuthenticationError( "No API key provided. You can set your API key in code using 'apacai.api_key = <API-KEY>', or you can set the environment variable APACAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the apacai module at it with 'apacai.api_key_path = <PATH>'. You can generate API keys in the APACAI web interface. See https://platform.apacai.com/account/api-keys for details." )
try: import wandb WANDB_AVAILABLE = True except: WANDB_AVAILABLE = False if WANDB_AVAILABLE: import datetime import io import json import re from pathlib import Path from apacai import File, FineTune from apacai.datalib.numpy_helper import numpy as np from apacai.datalib.pandas_helper import pandas as pd class WandbLogger: """ Log fine-tunes to [Weights & Biases](https://wandb.me/apacai-docs) """ if not WANDB_AVAILABLE: print("Logging requires wandb to be installed. Run `pip install wandb`.") else: _wandb_api = None _logged_in = False @classmethod def sync( cls, id=None, n_fine_tunes=None, project="GPT-3", entity=None, force=False, **kwargs_wandb_init, ): """ Sync fine-tunes to Weights & Biases. :param id: The id of the fine-tune (optional) :param n_fine_tunes: Number of most recent fine-tunes to log when an id is not provided. By default, every fine-tune is synced. :param project: Name of the project where you're sending runs. By default, it is "GPT-3". :param entity: Username or team name where you're sending runs. By default, your default entity is used, which is usually your username. :param force: Forces logging and overwrite existing wandb run of the same fine-tune. """ if not WANDB_AVAILABLE: return if id: fine_tune = FineTune.retrieve(id=id) fine_tune.pop("events", None) fine_tunes = [fine_tune] else: # get list of fine_tune to log fine_tunes = FineTune.list() if not fine_tunes or fine_tunes.get("data") is None: print("No fine-tune has been retrieved") return fine_tunes = fine_tunes["data"][ -n_fine_tunes if n_fine_tunes is not None else None : ] # log starting from oldest fine_tune show_individual_warnings = ( False if id is None and n_fine_tunes is None else True ) fine_tune_logged = [ cls._log_fine_tune( fine_tune, project, entity, force, show_individual_warnings, **kwargs_wandb_init, ) for fine_tune in fine_tunes ] if not show_individual_warnings and not any(fine_tune_logged): print("No new successful fine-tunes were found") return "🎉 wandb sync completed successfully" @classmethod def _log_fine_tune( cls, fine_tune, project, entity, force, show_individual_warnings, **kwargs_wandb_init, ): fine_tune_id = fine_tune.get("id") status = fine_tune.get("status") # check run completed successfully if status != "succeeded": if show_individual_warnings: print( f'Fine-tune {fine_tune_id} has the status "{status}" and will not be logged' ) return # check results are present try: results_id = fine_tune["result_files"][0]["id"] results = File.download(id=results_id).decode("utf-8") except: if show_individual_warnings: print(f"Fine-tune {fine_tune_id} has no results and will not be logged") return # check run has not been logged already run_path = f"{project}/{fine_tune_id}" if entity is not None: run_path = f"{entity}/{run_path}" wandb_run = cls._get_wandb_run(run_path) if wandb_run: wandb_status = wandb_run.summary.get("status") if show_individual_warnings: if wandb_status == "succeeded": print( f"Fine-tune {fine_tune_id} has already been logged successfully at {wandb_run.url}" ) if not force: print( 'Use "--force" in the CLI or "force=True" in python if you want to overwrite previous run' ) else: print( f"A run for fine-tune {fine_tune_id} was previously created but didn't end successfully" ) if wandb_status != "succeeded" or force: print( f"A new wandb run will be created for fine-tune {fine_tune_id} and previous run will be overwritten" ) if wandb_status == "succeeded" and not force: return # start a wandb run wandb.init( job_type="fine-tune", config=cls._get_config(fine_tune), project=project, entity=entity, name=fine_tune_id, id=fine_tune_id, **kwargs_wandb_init, ) # log results df_results = pd.read_csv(io.StringIO(results)) for _, row in df_results.iterrows(): metrics = {k: v for k, v in row.items() if not np.isnan(v)} step = metrics.pop("step") if step is not None: step = int(step) wandb.log(metrics, step=step) fine_tuned_model = fine_tune.get("fine_tuned_model") if fine_tuned_model is not None: wandb.summary["fine_tuned_model"] = fine_tuned_model # training/validation files and fine-tune details cls._log_artifacts(fine_tune, project, entity) # mark run as complete wandb.summary["status"] = "succeeded" wandb.finish() return True @classmethod def _ensure_logged_in(cls): if not cls._logged_in: if wandb.login(): cls._logged_in = True else: raise Exception("You need to log in to wandb") @classmethod def _get_wandb_run(cls, run_path): cls._ensure_logged_in() try: if cls._wandb_api is None: cls._wandb_api = wandb.Api() return cls._wandb_api.run(run_path) except Exception: return None @classmethod def _get_wandb_artifact(cls, artifact_path): cls._ensure_logged_in() try: if cls._wandb_api is None: cls._wandb_api = wandb.Api() return cls._wandb_api.artifact(artifact_path) except Exception: return None @classmethod def _get_config(cls, fine_tune): config = dict(fine_tune) for key in ("training_files", "validation_files", "result_files"): if config.get(key) and len(config[key]): config[key] = config[key][0] if config.get("created_at"): config["created_at"] = datetime.datetime.fromtimestamp(config["created_at"]) return config @classmethod def _log_artifacts(cls, fine_tune, project, entity): # training/validation files training_file = ( fine_tune["training_files"][0] if fine_tune.get("training_files") and len(fine_tune["training_files"]) else None ) validation_file = ( fine_tune["validation_files"][0] if fine_tune.get("validation_files") and len(fine_tune["validation_files"]) else None ) for file, prefix, artifact_type in ( (training_file, "train", "training_files"), (validation_file, "valid", "validation_files"), ): if file is not None: cls._log_artifact_inputs(file, prefix, artifact_type, project, entity) # fine-tune details fine_tune_id = fine_tune.get("id") artifact = wandb.Artifact( "fine_tune_details", type="fine_tune_details", metadata=fine_tune, ) with artifact.new_file( "fine_tune_details.json", mode="w", encoding="utf-8" ) as f: json.dump(fine_tune, f, indent=2) wandb.run.log_artifact( artifact, aliases=["latest", fine_tune_id], ) @classmethod def _log_artifact_inputs(cls, file, prefix, artifact_type, project, entity): file_id = file["id"] filename = Path(file["filename"]).name stem = Path(file["filename"]).stem # get input artifact artifact_name = f"{prefix}-{filename}" # sanitize name to valid wandb artifact name artifact_name = re.sub(r"[^a-zA-Z0-9_\-.]", "_", artifact_name) artifact_alias = file_id artifact_path = f"{project}/{artifact_name}:{artifact_alias}" if entity is not None: artifact_path = f"{entity}/{artifact_path}" artifact = cls._get_wandb_artifact(artifact_path) # create artifact if file not already logged previously if artifact is None: # get file content try: file_content = File.download(id=file_id).decode("utf-8") except: print( f"File {file_id} could not be retrieved. Make sure you are allowed to download training/validation files" ) return artifact = wandb.Artifact(artifact_name, type=artifact_type, metadata=file) with artifact.new_file(filename, mode="w", encoding="utf-8") as f: f.write(file_content) # create a Table try: table, n_items = cls._make_table(file_content) artifact.add(table, stem) wandb.config.update({f"n_{prefix}": n_items}) artifact.metadata["items"] = n_items except: print(f"File {file_id} could not be read as a valid JSON file") else: # log number of items wandb.config.update({f"n_{prefix}": artifact.metadata.get("items")}) wandb.run.use_artifact(artifact, aliases=["latest", artifact_alias]) @classmethod def _make_table(cls, file_content): df = pd.read_json(io.StringIO(file_content), orient="records", lines=True) return wandb.Table(dataframe=df), len(df)
class Remediation(NamedTuple): name: str immediate_msg: Optional[str] = None necessary_msg: Optional[str] = None necessary_fn: Optional[Callable[[Any], Any]] = None optional_msg: Optional[str] = None optional_fn: Optional[Callable[[Any], Any]] = None error_msg: Optional[str] = None def num_examples_validator(df): """ This validator will only print out the number of examples and recommend to the user to increase the number of examples if less than 100. """ MIN_EXAMPLES = 100 optional_suggestion = ( "" if len(df) >= MIN_EXAMPLES else ". In general, we recommend having at least a few hundred examples. We've found that performance tends to linearly increase for every doubling of the number of examples" ) immediate_msg = ( f"\n- Your file contains {len(df)} prompt-completion pairs{optional_suggestion}" ) return Remediation(name="num_examples", immediate_msg=immediate_msg) def necessary_column_validator(df, necessary_column): """ This validator will ensure that the necessary column is present in the dataframe. """ def lower_case_column(df, column): cols = [c for c in df.columns if str(c).lower() == column] df.rename(columns={cols[0]: column.lower()}, inplace=True) return df immediate_msg = None necessary_fn = None necessary_msg = None error_msg = None if necessary_column not in df.columns: if necessary_column in [str(c).lower() for c in df.columns]: def lower_case_column_creator(df): return lower_case_column(df, necessary_column) necessary_fn = lower_case_column_creator immediate_msg = ( f"\n- The `{necessary_column}` column/key should be lowercase" ) necessary_msg = f"Lower case column name to `{necessary_column}`" else: error_msg = f"`{necessary_column}` column/key is missing. Please make sure you name your columns/keys appropriately, then retry" return Remediation( name="necessary_column", immediate_msg=immediate_msg, necessary_msg=necessary_msg, necessary_fn=necessary_fn, error_msg=error_msg, ) def additional_column_validator(df, fields=["prompt", "completion"]): """ This validator will remove additional columns from the dataframe. """ additional_columns = [] necessary_msg = None immediate_msg = None necessary_fn = None if len(df.columns) > 2: additional_columns = [c for c in df.columns if c not in fields] warn_message = "" for ac in additional_columns: dups = [c for c in additional_columns if ac in c] if len(dups) > 0: warn_message += f"\n WARNING: Some of the additional columns/keys contain `{ac}` in their name. These will be ignored, and the column/key `{ac}` will be used instead. This could also result from a duplicate column/key in the provided file." immediate_msg = f"\n- The input file should contain exactly two columns/keys per row. Additional columns/keys present are: {additional_columns}{warn_message}" necessary_msg = f"Remove additional columns/keys: {additional_columns}" def necessary_fn(x): return x[fields] return Remediation( name="additional_column", immediate_msg=immediate_msg, necessary_msg=necessary_msg, necessary_fn=necessary_fn, ) def non_empty_field_validator(df, field="completion"): """ This validator will ensure that no completion is empty. """ necessary_msg = None necessary_fn = None immediate_msg = None if df[field].apply(lambda x: x == "").any() or df[field].isnull().any(): empty_rows = (df[field] == "") | (df[field].isnull()) empty_indexes = df.reset_index().index[empty_rows].tolist() immediate_msg = f"\n- `{field}` column/key should not contain empty strings. These are rows: {empty_indexes}" def necessary_fn(x): return x[x[field] != ""].dropna(subset=[field]) necessary_msg = f"Remove {len(empty_indexes)} rows with empty {field}s" return Remediation( name=f"empty_{field}", immediate_msg=immediate_msg, necessary_msg=necessary_msg, necessary_fn=necessary_fn, ) def duplicated_rows_validator(df, fields=["prompt", "completion"]): """ This validator will suggest to the user to remove duplicate rows if they exist. """ duplicated_rows = df.duplicated(subset=fields) duplicated_indexes = df.reset_index().index[duplicated_rows].tolist() immediate_msg = None optional_msg = None optional_fn = None if len(duplicated_indexes) > 0: immediate_msg = f"\n- There are {len(duplicated_indexes)} duplicated {'-'.join(fields)} sets. These are rows: {duplicated_indexes}" optional_msg = f"Remove {len(duplicated_indexes)} duplicate rows" def optional_fn(x): return x.drop_duplicates(subset=fields) return Remediation( name="duplicated_rows", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, ) def long_examples_validator(df): """ This validator will suggest to the user to remove examples that are too long. """ immediate_msg = None optional_msg = None optional_fn = None ft_type = infer_task_type(df) if ft_type != "open-ended generation": def get_long_indexes(d): long_examples = d.apply( lambda x: len(x.prompt) + len(x.completion) > 10000, axis=1 ) return d.reset_index().index[long_examples].tolist() long_indexes = get_long_indexes(df) if len(long_indexes) > 0: immediate_msg = f"\n- There are {len(long_indexes)} examples that are very long. These are rows: {long_indexes}\nFor conditional generation, and for classification the examples shouldn't be longer than 2048 tokens." optional_msg = f"Remove {len(long_indexes)} long examples" def optional_fn(x): long_indexes_to_drop = get_long_indexes(x) if long_indexes != long_indexes_to_drop: sys.stdout.write( f"The indices of the long examples has changed as a result of a previously applied recommendation.\nThe {len(long_indexes_to_drop)} long examples to be dropped are now at the following indices: {long_indexes_to_drop}\n" ) return x.drop(long_indexes_to_drop) return Remediation( name="long_examples", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, ) def common_prompt_suffix_validator(df): """ This validator will suggest to add a common suffix to the prompt if one doesn't already exist in case of classification or conditional generation. """ error_msg = None immediate_msg = None optional_msg = None optional_fn = None # Find a suffix which is not contained within the prompt otherwise suggested_suffix = "\n\n### =>\n\n" suffix_options = [ " ->", "\n\n###\n\n", "\n\n===\n\n", "\n\n---\n\n", "\n\n===>\n\n", "\n\n--->\n\n", ] for suffix_option in suffix_options: if suffix_option == " ->": if df.prompt.str.contains("\n").any(): continue if df.prompt.str.contains(suffix_option, regex=False).any(): continue suggested_suffix = suffix_option break display_suggested_suffix = suggested_suffix.replace("\n", "\\n") ft_type = infer_task_type(df) if ft_type == "open-ended generation": return Remediation(name="common_suffix") def add_suffix(x, suffix): x["prompt"] += suffix return x common_suffix = get_common_xfix(df.prompt, xfix="suffix") if (df.prompt == common_suffix).all(): error_msg = f"All prompts are identical: `{common_suffix}`\nConsider leaving the prompts blank if you want to do open-ended generation, otherwise ensure prompts are different" return Remediation(name="common_suffix", error_msg=error_msg) if common_suffix != "": common_suffix_new_line_handled = common_suffix.replace("\n", "\\n") immediate_msg = ( f"\n- All prompts end with suffix `{common_suffix_new_line_handled}`" ) if len(common_suffix) > 10: immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`" if ( df.prompt.str[: -len(common_suffix)] .str.contains(common_suffix, regex=False) .any() ): immediate_msg += f"\n WARNING: Some of your prompts contain the suffix `{common_suffix}` more than once. We strongly suggest that you review your prompts and add a unique suffix" else: immediate_msg = "\n- Your data does not contain a common separator at the end of your prompts. Having a separator string appended to the end of the prompt makes it clearer to the fine-tuned model where the completion should begin. See https://platform.apacai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples. If you intend to do open-ended generation, then you should leave the prompts empty" if common_suffix == "": optional_msg = ( f"Add a suffix separator `{display_suggested_suffix}` to all prompts" ) def optional_fn(x): return add_suffix(x, suggested_suffix) return Remediation( name="common_completion_suffix", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, error_msg=error_msg, ) def common_prompt_prefix_validator(df): """ This validator will suggest to remove a common prefix from the prompt if a long one exist. """ MAX_PREFIX_LEN = 12 immediate_msg = None optional_msg = None optional_fn = None common_prefix = get_common_xfix(df.prompt, xfix="prefix") if common_prefix == "": return Remediation(name="common_prefix") def remove_common_prefix(x, prefix): x["prompt"] = x["prompt"].str[len(prefix) :] return x if (df.prompt == common_prefix).all(): # already handled by common_suffix_validator return Remediation(name="common_prefix") if common_prefix != "": immediate_msg = f"\n- All prompts start with prefix `{common_prefix}`" if MAX_PREFIX_LEN < len(common_prefix): immediate_msg += ". Fine-tuning doesn't require the instruction specifying the task, or a few-shot example scenario. Most of the time you should only add the input data into the prompt, and the desired output into the completion" optional_msg = f"Remove prefix `{common_prefix}` from all prompts" def optional_fn(x): return remove_common_prefix(x, common_prefix) return Remediation( name="common_prompt_prefix", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, ) def common_completion_prefix_validator(df): """ This validator will suggest to remove a common prefix from the completion if a long one exist. """ MAX_PREFIX_LEN = 5 common_prefix = get_common_xfix(df.completion, xfix="prefix") ws_prefix = len(common_prefix) > 0 and common_prefix[0] == " " if len(common_prefix) < MAX_PREFIX_LEN: return Remediation(name="common_prefix") def remove_common_prefix(x, prefix, ws_prefix): x["completion"] = x["completion"].str[len(prefix) :] if ws_prefix: # keep the single whitespace as prefix x["completion"] = " " + x["completion"] return x if (df.completion == common_prefix).all(): # already handled by common_suffix_validator return Remediation(name="common_prefix") immediate_msg = f"\n- All completions start with prefix `{common_prefix}`. Most of the time you should only add the output data into the completion, without any prefix" optional_msg = f"Remove prefix `{common_prefix}` from all completions" def optional_fn(x): return remove_common_prefix(x, common_prefix, ws_prefix) return Remediation( name="common_completion_prefix", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, ) def common_completion_suffix_validator(df): """ This validator will suggest to add a common suffix to the completion if one doesn't already exist in case of classification or conditional generation. """ error_msg = None immediate_msg = None optional_msg = None optional_fn = None ft_type = infer_task_type(df) if ft_type == "open-ended generation" or ft_type == "classification": return Remediation(name="common_suffix") common_suffix = get_common_xfix(df.completion, xfix="suffix") if (df.completion == common_suffix).all(): error_msg = f"All completions are identical: `{common_suffix}`\nEnsure completions are different, otherwise the model will just repeat `{common_suffix}`" return Remediation(name="common_suffix", error_msg=error_msg) # Find a suffix which is not contained within the completion otherwise suggested_suffix = " [END]" suffix_options = [ "\n", ".", " END", "***", "+++", "&&&", "$$$", "@@@", "%%%", ] for suffix_option in suffix_options: if df.completion.str.contains(suffix_option, regex=False).any(): continue suggested_suffix = suffix_option break display_suggested_suffix = suggested_suffix.replace("\n", "\\n") def add_suffix(x, suffix): x["completion"] += suffix return x if common_suffix != "": common_suffix_new_line_handled = common_suffix.replace("\n", "\\n") immediate_msg = ( f"\n- All completions end with suffix `{common_suffix_new_line_handled}`" ) if len(common_suffix) > 10: immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`" if ( df.completion.str[: -len(common_suffix)] .str.contains(common_suffix, regex=False) .any() ): immediate_msg += f"\n WARNING: Some of your completions contain the suffix `{common_suffix}` more than once. We suggest that you review your completions and add a unique ending" else: immediate_msg = "\n- Your data does not contain a common ending at the end of your completions. Having a common ending string appended to the end of the completion makes it clearer to the fine-tuned model where the completion should end. See https://platform.apacai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples." if common_suffix == "": optional_msg = ( f"Add a suffix ending `{display_suggested_suffix}` to all completions" ) def optional_fn(x): return add_suffix(x, suggested_suffix) return Remediation( name="common_completion_suffix", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, error_msg=error_msg, ) def completions_space_start_validator(df): """ This validator will suggest to add a space at the start of the completion if it doesn't already exist. This helps with tokenization. """ def add_space_start(x): x["completion"] = x["completion"].apply( lambda x: ("" if x[0] == " " else " ") + x ) return x optional_msg = None optional_fn = None immediate_msg = None if df.completion.str[:1].nunique() != 1 or df.completion.values[0][0] != " ": immediate_msg = "\n- The completion should start with a whitespace character (` `). This tends to produce better results due to the tokenization we use. See https://platform.apacai.com/docs/guides/fine-tuning/preparing-your-dataset for more details" optional_msg = "Add a whitespace character to the beginning of the completion" optional_fn = add_space_start return Remediation( name="completion_space_start", immediate_msg=immediate_msg, optional_msg=optional_msg, optional_fn=optional_fn, ) def lower_case_validator(df, column): """ This validator will suggest to lowercase the column values, if more than a third of letters are uppercase. """ def lower_case(x): x[column] = x[column].str.lower() return x count_upper = ( df[column] .apply(lambda x: sum(1 for c in x if c.isalpha() and c.isupper())) .sum() ) count_lower = ( df[column] .apply(lambda x: sum(1 for c in x if c.isalpha() and c.islower())) .sum() ) if count_upper * 2 > count_lower: return Remediation( name="lower_case", immediate_msg=f"\n- More than a third of your `{column}` column/key is uppercase. Uppercase {column}s tends to perform worse than a mixture of case encountered in normal language. We recommend to lower case the data if that makes sense in your domain. See https://platform.apacai.com/docs/guides/fine-tuning/preparing-your-dataset for more details", optional_msg=f"Lowercase all your data in column/key `{column}`", optional_fn=lower_case, ) def read_any_format(fname, fields=["prompt", "completion"]): """ This function will read a file saved in .csv, .json, .txt, .xlsx or .tsv format using pandas. - for .xlsx it will read the first sheet - for .txt it will assume completions and split on newline """ assert_has_pandas() remediation = None necessary_msg = None immediate_msg = None error_msg = None df = None if os.path.isfile(fname): try: if fname.lower().endswith(".csv") or fname.lower().endswith(".tsv"): file_extension_str, separator = ( ("CSV", ",") if fname.lower().endswith(".csv") else ("TSV", "\t") ) immediate_msg = f"\n- Based on your file extension, your file is formatted as a {file_extension_str} file" necessary_msg = ( f"Your format `{file_extension_str}` will be converted to `JSONL`" ) df = pd.read_csv(fname, sep=separator, dtype=str).fillna("") elif fname.lower().endswith(".xlsx"): immediate_msg = "\n- Based on your file extension, your file is formatted as an Excel file" necessary_msg = "Your format `XLSX` will be converted to `JSONL`" xls = pd.ExcelFile(fname) sheets = xls.sheet_names if len(sheets) > 1: immediate_msg += "\n- Your Excel file contains more than one sheet. Please either save as csv or ensure all data is present in the first sheet. WARNING: Reading only the first sheet..." df = pd.read_excel(fname, dtype=str).fillna("") elif fname.lower().endswith(".txt"): immediate_msg = ( "\n- Based on your file extension, you provided a text file" ) necessary_msg = "Your format `TXT` will be converted to `JSONL`" with open(fname, "r") as f: content = f.read() df = pd.DataFrame( [["", line] for line in content.split("\n")], columns=fields, dtype=str, ).fillna("") elif fname.lower().endswith(".jsonl"): df = pd.read_json(fname, lines=True, dtype=str).fillna("") if len(df) == 1: # this is NOT what we expect for a .jsonl file immediate_msg = "\n- Your JSONL file appears to be in a JSON format. Your file will be converted to JSONL format" necessary_msg = "Your format `JSON` will be converted to `JSONL`" df = pd.read_json(fname, dtype=str).fillna("") else: pass # this is what we expect for a .jsonl file elif fname.lower().endswith(".json"): try: # to handle case where .json file is actually a .jsonl file df = pd.read_json(fname, lines=True, dtype=str).fillna("") if len(df) == 1: # this code path corresponds to a .json file that has one line df = pd.read_json(fname, dtype=str).fillna("") else: # this is NOT what we expect for a .json file immediate_msg = "\n- Your JSON file appears to be in a JSONL format. Your file will be converted to JSONL format" necessary_msg = ( "Your format `JSON` will be converted to `JSONL`" ) except ValueError: # this code path corresponds to a .json file that has multiple lines (i.e. it is indented) df = pd.read_json(fname, dtype=str).fillna("") else: error_msg = "Your file must have one of the following extensions: .CSV, .TSV, .XLSX, .TXT, .JSON or .JSONL" if "." in fname: error_msg += f" Your file `{fname}` ends with the extension `.{fname.split('.')[-1]}` which is not supported." else: error_msg += f" Your file `{fname}` is missing a file extension." except (ValueError, TypeError): file_extension_str = fname.split(".")[-1].upper() error_msg = f"Your file `{fname}` does not appear to be in valid {file_extension_str} format. Please ensure your file is formatted as a valid {file_extension_str} file." else: error_msg = f"File {fname} does not exist." remediation = Remediation( name="read_any_format", necessary_msg=necessary_msg, immediate_msg=immediate_msg, error_msg=error_msg, ) return df, remediation def format_inferrer_validator(df): """ This validator will infer the likely fine-tuning format of the data, and display it to the user if it is classification. It will also suggest to use ada and explain train/validation split benefits. """ ft_type = infer_task_type(df) immediate_msg = None if ft_type == "classification": immediate_msg = f"\n- Based on your data it seems like you're trying to fine-tune a model for {ft_type}\n- For classification, we recommend you try one of the faster and cheaper models, such as `ada`\n- For classification, you can estimate the expected model performance by keeping a held out dataset, which is not used for training" return Remediation(name="num_examples", immediate_msg=immediate_msg) def apply_necessary_remediation(df, remediation): """ This function will apply a necessary remediation to a dataframe, or print an error message if one exists. """ if remediation.error_msg is not None: sys.stderr.write( f"\n\nERROR in {remediation.name} validator: {remediation.error_msg}\n\nAborting..." ) sys.exit(1) if remediation.immediate_msg is not None: sys.stdout.write(remediation.immediate_msg) if remediation.necessary_fn is not None: df = remediation.necessary_fn(df) return df def accept_suggestion(input_text, auto_accept): sys.stdout.write(input_text) if auto_accept: sys.stdout.write("Y\n") return True return input().lower() != "n" def apply_optional_remediation(df, remediation, auto_accept): """ This function will apply an optional remediation to a dataframe, based on the user input. """ optional_applied = False input_text = f"- [Recommended] {remediation.optional_msg} [Y/n]: " if remediation.optional_msg is not None: if accept_suggestion(input_text, auto_accept): df = remediation.optional_fn(df) optional_applied = True if remediation.necessary_msg is not None: sys.stdout.write(f"- [Necessary] {remediation.necessary_msg}\n") return df, optional_applied def estimate_fine_tuning_time(df): """ Estimate the time it'll take to fine-tune the dataset """ ft_format = infer_task_type(df) expected_time = 1.0 if ft_format == "classification": num_examples = len(df) expected_time = num_examples * 1.44 else: size = df.memory_usage(index=True).sum() expected_time = size * 0.0515 def format_time(time): if time < 60: return f"{round(time, 2)} seconds" elif time < 3600: return f"{round(time / 60, 2)} minutes" elif time < 86400: return f"{round(time / 3600, 2)} hours" else: return f"{round(time / 86400, 2)} days" time_string = format_time(expected_time + 140) sys.stdout.write( f"Once your model starts training, it'll approximately take {time_string} to train a `curie` model, and less for `ada` and `babbage`. Queue will approximately take half an hour per job ahead of you.\n" ) def get_outfnames(fname, split): suffixes = ["_train", "_valid"] if split else [""] i = 0 while True: index_suffix = f" ({i})" if i > 0 else "" candidate_fnames = [ os.path.splitext(fname)[0] + "_prepared" + suffix + index_suffix + ".jsonl" for suffix in suffixes ] if not any(os.path.isfile(f) for f in candidate_fnames): return candidate_fnames i += 1 def get_classification_hyperparams(df): n_classes = df.completion.nunique() pos_class = None if n_classes == 2: pos_class = df.completion.value_counts().index[0] return n_classes, pos_class def write_out_file(df, fname, any_remediations, auto_accept): """ This function will write out a dataframe to a file, if the user would like to proceed, and also offer a fine-tuning command with the newly created file. For classification it will optionally ask the user if they would like to split the data into train/valid files, and modify the suggested command to include the valid set. """ ft_format = infer_task_type(df) common_prompt_suffix = get_common_xfix(df.prompt, xfix="suffix") common_completion_suffix = get_common_xfix(df.completion, xfix="suffix") split = False input_text = "- [Recommended] Would you like to split into training and validation set? [Y/n]: " if ft_format == "classification": if accept_suggestion(input_text, auto_accept): split = True additional_params = "" common_prompt_suffix_new_line_handled = common_prompt_suffix.replace("\n", "\\n") common_completion_suffix_new_line_handled = common_completion_suffix.replace( "\n", "\\n" ) optional_ending_string = ( f' Make sure to include `stop=["{common_completion_suffix_new_line_handled}"]` so that the generated texts ends at the expected place.' if len(common_completion_suffix_new_line_handled) > 0 else "" ) input_text = "\n\nYour data will be written to a new JSONL file. Proceed [Y/n]: " if not any_remediations and not split: sys.stdout.write( f'\nYou can use your file for fine-tuning:\n> apacai api fine_tunes.create -t "{fname}"{additional_params}\n\nAfter you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `{common_prompt_suffix_new_line_handled}` for the model to start generating completions, rather than continuing with the prompt.{optional_ending_string}\n' ) estimate_fine_tuning_time(df) elif accept_suggestion(input_text, auto_accept): fnames = get_outfnames(fname, split) if split: assert len(fnames) == 2 and "train" in fnames[0] and "valid" in fnames[1] MAX_VALID_EXAMPLES = 1000 n_train = max(len(df) - MAX_VALID_EXAMPLES, int(len(df) * 0.8)) df_train = df.sample(n=n_train, random_state=42) df_valid = df.drop(df_train.index) df_train[["prompt", "completion"]].to_json( fnames[0], lines=True, orient="records", force_ascii=False ) df_valid[["prompt", "completion"]].to_json( fnames[1], lines=True, orient="records", force_ascii=False ) n_classes, pos_class = get_classification_hyperparams(df) additional_params += " --compute_classification_metrics" if n_classes == 2: additional_params += f' --classification_positive_class "{pos_class}"' else: additional_params += f" --classification_n_classes {n_classes}" else: assert len(fnames) == 1 df[["prompt", "completion"]].to_json( fnames[0], lines=True, orient="records", force_ascii=False ) # Add -v VALID_FILE if we split the file into train / valid files_string = ("s" if split else "") + " to `" + ("` and `".join(fnames)) valid_string = f' -v "{fnames[1]}"' if split else "" separator_reminder = ( "" if len(common_prompt_suffix_new_line_handled) == 0 else f"After you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `{common_prompt_suffix_new_line_handled}` for the model to start generating completions, rather than continuing with the prompt." ) sys.stdout.write( f'\nWrote modified file{files_string}`\nFeel free to take a look!\n\nNow use that file when fine-tuning:\n> apacai api fine_tunes.create -t "{fnames[0]}"{valid_string}{additional_params}\n\n{separator_reminder}{optional_ending_string}\n' ) estimate_fine_tuning_time(df) else: sys.stdout.write("Aborting... did not write the file\n") def infer_task_type(df): """ Infer the likely fine-tuning task type from the data """ CLASSIFICATION_THRESHOLD = 3 # min_average instances of each class if sum(df.prompt.str.len()) == 0: return "open-ended generation" if len(df.completion.unique()) < len(df) / CLASSIFICATION_THRESHOLD: return "classification" return "conditional generation" def get_common_xfix(series, xfix="suffix"): """ Finds the longest common suffix or prefix of all the values in a series """ common_xfix = "" while True: common_xfixes = ( series.str[-(len(common_xfix) + 1) :] if xfix == "suffix" else series.str[: len(common_xfix) + 1] ) # first few or last few characters if ( common_xfixes.nunique() != 1 ): # we found the character at which we don't have a unique xfix anymore break elif ( common_xfix == common_xfixes.values[0] ): # the entire first row is a prefix of every other row break else: # the first or last few characters are still common across all rows - let's try to add one more common_xfix = common_xfixes.values[0] return common_xfix def get_validators(): return [ num_examples_validator, lambda x: necessary_column_validator(x, "prompt"), lambda x: necessary_column_validator(x, "completion"), additional_column_validator, non_empty_field_validator, format_inferrer_validator, duplicated_rows_validator, long_examples_validator, lambda x: lower_case_validator(x, "prompt"), lambda x: lower_case_validator(x, "completion"), common_prompt_suffix_validator, common_prompt_prefix_validator, common_completion_prefix_validator, common_completion_suffix_validator, completions_space_start_validator, ] def apply_validators( df, fname, remediation, validators, auto_accept, write_out_file_func, ): optional_remediations = [] if remediation is not None: optional_remediations.append(remediation) for validator in validators: remediation = validator(df) if remediation is not None: optional_remediations.append(remediation) df = apply_necessary_remediation(df, remediation) any_optional_or_necessary_remediations = any( [ remediation for remediation in optional_remediations if remediation.optional_msg is not None or remediation.necessary_msg is not None ] ) any_necessary_applied = any( [ remediation for remediation in optional_remediations if remediation.necessary_msg is not None ] ) any_optional_applied = False if any_optional_or_necessary_remediations: sys.stdout.write( "\n\nBased on the analysis we will perform the following actions:\n" ) for remediation in optional_remediations: df, optional_applied = apply_optional_remediation( df, remediation, auto_accept ) any_optional_applied = any_optional_applied or optional_applied else: sys.stdout.write("\n\nNo remediations found.\n") any_optional_or_necessary_applied = any_optional_applied or any_necessary_applied write_out_file_func(df, fname, any_optional_or_necessary_applied, auto_accept)
class CancelledError(Exception): def __init__(self, msg): self.msg = msg Exception.__init__(self, msg) def __str__(self): return self.msg __repr__ = __str__ class BufferReader(io.BytesIO): def __init__(self, buf=b"", desc=None): self._len = len(buf) io.BytesIO.__init__(self, buf) self._progress = 0 self._callback = progress(len(buf), desc=desc) def __len__(self): return self._len def read(self, n=-1): chunk = io.BytesIO.read(self, n) self._progress += len(chunk) if self._callback: try: self._callback(self._progress) except Exception as e: # catches exception from the callback raise CancelledError("The upload was cancelled: {}".format(e)) return chunk def progress(total, desc): import tqdm # type: ignore meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc) def incr(progress): meter.n = progress if progress == total: meter.close() else: meter.refresh() return incr def MB(i): return int(i // 1024**2)
#!/usr/bin/env python logger = logging.getLogger() formatter = logging.Formatter("[%(asctime)s] %(message)s") handler = logging.StreamHandler(sys.stderr) handler.setFormatter(formatter) logger.addHandler(handler) def main(): parser = argparse.ArgumentParser(description=None) parser.add_argument( "-V", "--version", action="version", version="%(prog)s " + version.VERSION, ) parser.add_argument( "-v", "--verbose", action="count", dest="verbosity", default=0, help="Set verbosity.", ) parser.add_argument("-b", "--api-base", help="What API base url to use.") parser.add_argument("-k", "--api-key", help="What API key to use.") parser.add_argument("-p", "--proxy", nargs='+', help="What proxy to use.") parser.add_argument( "-o", "--organization", help="Which organization to run as (will use your default organization if not specified)", ) def help(args): parser.print_help() parser.set_defaults(func=help) subparsers = parser.add_subparsers() sub_api = subparsers.add_parser("api", help="Direct API calls") sub_tools = subparsers.add_parser("tools", help="Client side tools for convenience") sub_wandb = subparsers.add_parser("wandb", help="Logging with Weights & Biases") api_register(sub_api) tools_register(sub_tools) wandb_register(sub_wandb) args = parser.parse_args() if args.verbosity == 1: logger.setLevel(logging.INFO) elif args.verbosity >= 2: logger.setLevel(logging.DEBUG) apacai.debug = True if args.api_key is not None: apacai.api_key = args.api_key if args.api_base is not None: apacai.api_base = args.api_base if args.organization is not None: apacai.organization = args.organization if args.proxy is not None: apacai.proxy = {} for proxy in args.proxy: if proxy.startswith('https'): apacai.proxy['https'] = proxy elif proxy.startswith('http'): apacai.proxy['http'] = proxy try: args.func(args) except apacai.error.ApacAIError as e: display_error(e) return 1 except KeyboardInterrupt: sys.stderr.write("\n") return 1 return 0 if __name__ == "__main__": sys.exit(main())
OBJECT_CLASSES = { "engine": api_resources.Engine, "experimental.completion_config": CompletionConfig, "file": api_resources.File, "fine-tune": api_resources.FineTune, "model": api_resources.Model, "deployment": api_resources.Deployment, }
# APACAI Python bindings. # # Originally forked from the MIT-licensed Stripe Python bindings. if "pkg_resources" not in sys.modules: # workaround for the following: # https://github.com/benoitc/gunicorn/pull/2539 sys.modules["pkg_resources"] = object() # type: ignore[assignment] import aiohttp del sys.modules["pkg_resources"] Audio, ChatCompletion, Completion, Customer, Deployment, Edit, Embedding, Engine, ErrorObject, File, FineTune, Image, Model, Moderation, ) if TYPE_CHECKING: import requests from aiohttp import ClientSession api_key = os.environ.get("APACAI_API_KEY") # Path of a file with an API key, whose contents can change. Supercedes # `api_key` if set. The main use case is volume-mounted Kubernetes secrets, # which are updated automatically. api_key_path: Optional[str] = os.environ.get("APACAI_API_KEY_PATH") organization = os.environ.get("APACAI_ORGANIZATION") api_base = os.environ.get("APACAI_API_BASE", "https://api.apacai.com/v1") api_type = os.environ.get("APACAI_API_TYPE", "open_ai") api_version = os.environ.get( "APACAI_API_VERSION", ("2023-05-15" if api_type in ("azure", "azure_ad", "azuread") else None), ) verify_ssl_certs = True # No effect. Certificates are always verified. proxy = None app_info = None enable_telemetry = False # Ignored; the telemetry feature was removed. ca_bundle_path = None # No longer used, feature was removed debug = False log = None # Set to either 'debug' or 'info', controls console logging requestssession: Optional[ Union["requests.Session", Callable[[], "requests.Session"]] ] = None # Provide a requests.Session or Session factory. aiosession: ContextVar[Optional["ClientSession"]] = ContextVar( "aiohttp-session", default=None ) # Acts as a global aiohttp ClientSession that reuses connections. # This is user-supplied; otherwise, a session is remade for each request. __version__ = VERSION __all__ = [ "APIError", "Audio", "ChatCompletion", "Completion", "Customer", "Edit", "Image", "Deployment", "Embedding", "Engine", "ErrorObject", "File", "FineTune", "InvalidRequestError", "Model", "Moderation", "ApacAIError", "api_base", "api_key", "api_type", "api_key_path", "api_version", "app_info", "ca_bundle_path", "debug", "enable_telemetry", "log", "organization", "proxy", "verify_ssl_certs", ]
AsyncGenerator, AsyncIterator, Callable, Dict, Iterator, Optional, Tuple, Union, overload, ) if sys.version_info >= (3, 8): from typing import Literal else: from typing_extensions import Literal TIMEOUT_SECS = 600 MAX_SESSION_LIFETIME_SECS = 180 MAX_CONNECTION_RETRIES = 2 # Has one attribute per thread, 'session'. _thread_context = threading.local() def _build_api_url(url, query): scheme, netloc, path, base_query, fragment = urlsplit(url) if base_query: query = "%s&%s" % (base_query, query) return urlunsplit((scheme, netloc, path, query, fragment)) def _requests_proxies_arg(proxy) -> Optional[Dict[str, str]]: """Returns a value suitable for the 'proxies' argument to 'requests.request.""" if proxy is None: return None elif isinstance(proxy, str): return {"http": proxy, "https": proxy} elif isinstance(proxy, dict): return proxy.copy() else: raise ValueError( "'apacai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys." ) def _aiohttp_proxies_arg(proxy) -> Optional[str]: """Returns a value suitable for the 'proxies' argument to 'aiohttp.ClientSession.request.""" if proxy is None: return None elif isinstance(proxy, str): return proxy elif isinstance(proxy, dict): return proxy["https"] if "https" in proxy else proxy["http"] else: raise ValueError( "'apacai.proxy' must be specified as either a string URL or a dict with string URL under the https and/or http keys." ) def _make_session() -> requests.Session: if apacai.requestssession: if isinstance(apacai.requestssession, requests.Session): return apacai.requestssession return apacai.requestssession() if not apacai.verify_ssl_certs: warnings.warn("verify_ssl_certs is ignored; apacai always verifies.") s = requests.Session() proxies = _requests_proxies_arg(apacai.proxy) if proxies: s.proxies = proxies s.mount( "https://", requests.adapters.HTTPAdapter(max_retries=MAX_CONNECTION_RETRIES), ) return s def parse_stream_helper(line: bytes) -> Optional[str]: if line: if line.strip() == b"data: [DONE]": # return here will cause GeneratorExit exception in urllib3 # and it will close http connection with TCP Reset return None if line.startswith(b"data: "): line = line[len(b"data: "):] return line.decode("utf-8") else: return None return None def parse_stream(rbody: Iterator[bytes]) -> Iterator[str]: for line in rbody: _line = parse_stream_helper(line) if _line is not None: yield _line async def parse_stream_async(rbody: aiohttp.StreamReader): async for line in rbody: _line = parse_stream_helper(line) if _line is not None: yield _line class APIRequestor: def __init__( self, key=None, api_base=None, api_type=None, api_version=None, organization=None, ): self.api_base = api_base or apacai.api_base self.api_key = key or util.default_api_key() self.api_type = ( ApiType.from_str(api_type) if api_type else ApiType.from_str(apacai.api_type) ) self.api_version = api_version or apacai.api_version self.organization = organization or apacai.organization @classmethod def format_app_info(cls, info): str = info["name"] if info["version"]: str += "/%s" % (info["version"],) if info["url"]: str += " (%s)" % (info["url"],) return str def _check_polling_response(self, response: ApacAIResponse, predicate: Callable[[ApacAIResponse], bool]): if not predicate(response): return error_data = response.data['error'] message = error_data.get('message', 'Operation failed') code = error_data.get('code') raise error.ApacAIError(message=message, code=code) def _poll( self, method, url, until, failed, params = None, headers = None, interval = None, delay = None ) -> Tuple[Iterator[ApacAIResponse], bool, str]: if delay: time.sleep(delay) response, b, api_key = self.request(method, url, params, headers) self._check_polling_response(response, failed) start_time = time.time() while not until(response): if time.time() - start_time > TIMEOUT_SECS: raise error.Timeout("Operation polling timed out.") time.sleep(interval or response.retry_after or 10) response, b, api_key = self.request(method, url, params, headers) self._check_polling_response(response, failed) response.data = response.data['result'] return response, b, api_key async def _apoll( self, method, url, until, failed, params = None, headers = None, interval = None, delay = None ) -> Tuple[Iterator[ApacAIResponse], bool, str]: if delay: await asyncio.sleep(delay) response, b, api_key = await self.arequest(method, url, params, headers) self._check_polling_response(response, failed) start_time = time.time() while not until(response): if time.time() - start_time > TIMEOUT_SECS: raise error.Timeout("Operation polling timed out.") await asyncio.sleep(interval or response.retry_after or 10) response, b, api_key = await self.arequest(method, url, params, headers) self._check_polling_response(response, failed) response.data = response.data['result'] return response, b, api_key @overload def request( self, method, url, params, headers, files, stream: Literal[True], request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[Iterator[ApacAIResponse], bool, str]: pass @overload def request( self, method, url, params=..., headers=..., files=..., *, stream: Literal[True], request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[Iterator[ApacAIResponse], bool, str]: pass @overload def request( self, method, url, params=..., headers=..., files=..., stream: Literal[False] = ..., request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[ApacAIResponse, bool, str]: pass @overload def request( self, method, url, params=..., headers=..., files=..., stream: bool = ..., request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[Union[ApacAIResponse, Iterator[ApacAIResponse]], bool, str]: pass def request( self, method, url, params=None, headers=None, files=None, stream: bool = False, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ) -> Tuple[Union[ApacAIResponse, Iterator[ApacAIResponse]], bool, str]: result = self.request_raw( method.lower(), url, params=params, supplied_headers=headers, files=files, stream=stream, request_id=request_id, request_timeout=request_timeout, ) resp, got_stream = self._interpret_response(result, stream) return resp, got_stream, self.api_key @overload async def arequest( self, method, url, params, headers, files, stream: Literal[True], request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[AsyncGenerator[ApacAIResponse, None], bool, str]: pass @overload async def arequest( self, method, url, params=..., headers=..., files=..., *, stream: Literal[True], request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[AsyncGenerator[ApacAIResponse, None], bool, str]: pass @overload async def arequest( self, method, url, params=..., headers=..., files=..., stream: Literal[False] = ..., request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[ApacAIResponse, bool, str]: pass @overload async def arequest( self, method, url, params=..., headers=..., files=..., stream: bool = ..., request_id: Optional[str] = ..., request_timeout: Optional[Union[float, Tuple[float, float]]] = ..., ) -> Tuple[Union[ApacAIResponse, AsyncGenerator[ApacAIResponse, None]], bool, str]: pass async def arequest( self, method, url, params=None, headers=None, files=None, stream: bool = False, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ) -> Tuple[Union[ApacAIResponse, AsyncGenerator[ApacAIResponse, None]], bool, str]: ctx = aiohttp_session() session = await ctx.__aenter__() try: result = await self.arequest_raw( method.lower(), url, session, params=params, supplied_headers=headers, files=files, request_id=request_id, request_timeout=request_timeout, ) resp, got_stream = await self._interpret_async_response(result, stream) except Exception: await ctx.__aexit__(None, None, None) raise if got_stream: async def wrap_resp(): assert isinstance(resp, AsyncGenerator) try: async for r in resp: yield r finally: await ctx.__aexit__(None, None, None) return wrap_resp(), got_stream, self.api_key else: await ctx.__aexit__(None, None, None) return resp, got_stream, self.api_key def handle_error_response(self, rbody, rcode, resp, rheaders, stream_error=False): try: error_data = resp["error"] except (KeyError, TypeError): raise error.APIError( "Invalid response object from API: %r (HTTP response code " "was %d)" % (rbody, rcode), rbody, rcode, resp, ) if "internal_message" in error_data: error_data["message"] += "\n\n" + error_data["internal_message"] util.log_info( "APACAI API error received", error_code=error_data.get("code"), error_type=error_data.get("type"), error_message=error_data.get("message"), error_param=error_data.get("param"), stream_error=stream_error, ) # Rate limits were previously coded as 400's with code 'rate_limit' if rcode == 429: return error.RateLimitError( error_data.get("message"), rbody, rcode, resp, rheaders ) elif rcode in [400, 404, 415]: return error.InvalidRequestError( error_data.get("message"), error_data.get("param"), error_data.get("code"), rbody, rcode, resp, rheaders, ) elif rcode == 401: return error.AuthenticationError( error_data.get("message"), rbody, rcode, resp, rheaders ) elif rcode == 403: return error.PermissionError( error_data.get("message"), rbody, rcode, resp, rheaders ) elif rcode == 409: return error.TryAgain( error_data.get("message"), rbody, rcode, resp, rheaders ) elif stream_error: # TODO: we will soon attach status codes to stream errors parts = [error_data.get("message"), "(Error occurred while streaming.)"] message = " ".join([p for p in parts if p is not None]) return error.APIError(message, rbody, rcode, resp, rheaders) else: return error.APIError( f"{error_data.get('message')} {rbody} {rcode} {resp} {rheaders}", rbody, rcode, resp, rheaders, ) def request_headers( self, method: str, extra, request_id: Optional[str] ) -> Dict[str, str]: user_agent = "APACAI/v1 PythonBindings/%s" % (version.VERSION,) if apacai.app_info: user_agent += " " + self.format_app_info(apacai.app_info) uname_without_node = " ".join( v for k, v in platform.uname()._asdict().items() if k != "node" ) ua = { "bindings_version": version.VERSION, "httplib": "requests", "lang": "python", "lang_version": platform.python_version(), "platform": platform.platform(), "publisher": "apacai", "uname": uname_without_node, } if apacai.app_info: ua["application"] = apacai.app_info headers = { "X-APACAI-Client-User-Agent": json.dumps(ua), "User-Agent": user_agent, } headers.update(util.api_key_to_header(self.api_type, self.api_key)) if self.organization: headers["APACAI-Organization"] = self.organization if self.api_version is not None and self.api_type == ApiType.OPEN_AI: headers["APACAI-Version"] = self.api_version if request_id is not None: headers["X-Request-Id"] = request_id if apacai.debug: headers["APACAI-Debug"] = "true" headers.update(extra) return headers def _validate_headers( self, supplied_headers: Optional[Dict[str, str]] ) -> Dict[str, str]: headers: Dict[str, str] = {} if supplied_headers is None: return headers if not isinstance(supplied_headers, dict): raise TypeError("Headers must be a dictionary") for k, v in supplied_headers.items(): if not isinstance(k, str): raise TypeError("Header keys must be strings") if not isinstance(v, str): raise TypeError("Header values must be strings") headers[k] = v # NOTE: It is possible to do more validation of the headers, but a request could always # be made to the API manually with invalid headers, so we need to handle them server side. return headers def _prepare_request_raw( self, url, supplied_headers, method, params, files, request_id: Optional[str], ) -> Tuple[str, Dict[str, str], Optional[bytes]]: abs_url = "%s%s" % (self.api_base, url) headers = self._validate_headers(supplied_headers) data = None if method == "get" or method == "delete": if params: encoded_params = urlencode( [(k, v) for k, v in params.items() if v is not None] ) abs_url = _build_api_url(abs_url, encoded_params) elif method in {"post", "put"}: if params and files: data = params if params and not files: data = json.dumps(params).encode() headers["Content-Type"] = "application/json" else: raise error.APIConnectionError( "Unrecognized HTTP method %r. This may indicate a bug in the " "APACAI bindings. Please contact us through our help center at help.apacai.com for " "assistance." % (method,) ) headers = self.request_headers(method, headers, request_id) util.log_debug("Request to APACAI API", method=method, path=abs_url) util.log_debug("Post details", data=data, api_version=self.api_version) return abs_url, headers, data def request_raw( self, method, url, *, params=None, supplied_headers: Optional[Dict[str, str]] = None, files=None, stream: bool = False, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ) -> requests.Response: abs_url, headers, data = self._prepare_request_raw( url, supplied_headers, method, params, files, request_id ) if not hasattr(_thread_context, "session"): _thread_context.session = _make_session() _thread_context.session_create_time = time.time() elif ( time.time() - getattr(_thread_context, "session_create_time", 0) >= MAX_SESSION_LIFETIME_SECS ): _thread_context.session.close() _thread_context.session = _make_session() _thread_context.session_create_time = time.time() try: result = _thread_context.session.request( method, abs_url, headers=headers, data=data, files=files, stream=stream, timeout=request_timeout if request_timeout else TIMEOUT_SECS, proxies=_thread_context.session.proxies, ) except requests.exceptions.Timeout as e: raise error.Timeout("Request timed out: {}".format(e)) from e except requests.exceptions.RequestException as e: raise error.APIConnectionError( "Error communicating with APACAI: {}".format(e) ) from e util.log_debug( "APACAI API response", path=abs_url, response_code=result.status_code, processing_ms=result.headers.get("APACAI-Processing-Ms"), request_id=result.headers.get("X-Request-Id"), ) # Don't read the whole stream for debug logging unless necessary. if apacai.log == "debug": util.log_debug( "API response body", body=result.content, headers=result.headers ) return result async def arequest_raw( self, method, url, session, *, params=None, supplied_headers: Optional[Dict[str, str]] = None, files=None, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ) -> aiohttp.ClientResponse: abs_url, headers, data = self._prepare_request_raw( url, supplied_headers, method, params, files, request_id ) if isinstance(request_timeout, tuple): timeout = aiohttp.ClientTimeout( connect=request_timeout[0], total=request_timeout[1], ) else: timeout = aiohttp.ClientTimeout( total=request_timeout if request_timeout else TIMEOUT_SECS ) if files: # TODO: Use `aiohttp.MultipartWriter` to create the multipart form data here. # For now we use the private `requests` method that is known to have worked so far. data, content_type = requests.models.RequestEncodingMixin._encode_files( # type: ignore files, data ) headers["Content-Type"] = content_type request_kwargs = { "method": method, "url": abs_url, "headers": headers, "data": data, "proxy": _aiohttp_proxies_arg(apacai.proxy), "timeout": timeout, } try: result = await session.request(**request_kwargs) util.log_info( "APACAI API response", path=abs_url, response_code=result.status, processing_ms=result.headers.get("APACAI-Processing-Ms"), request_id=result.headers.get("X-Request-Id"), ) # Don't read the whole stream for debug logging unless necessary. if apacai.log == "debug": util.log_debug( "API response body", body=result.content, headers=result.headers ) return result except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e: raise error.Timeout("Request timed out") from e except aiohttp.ClientError as e: raise error.APIConnectionError("Error communicating with APACAI") from e def _interpret_response( self, result: requests.Response, stream: bool ) -> Tuple[Union[ApacAIResponse, Iterator[ApacAIResponse]], bool]: """Returns the response(s) and a bool indicating whether it is a stream.""" if stream and "text/event-stream" in result.headers.get("Content-Type", ""): return ( self._interpret_response_line( line, result.status_code, result.headers, stream=True ) for line in parse_stream(result.iter_lines()) ), True else: return ( self._interpret_response_line( result.content.decode("utf-8"), result.status_code, result.headers, stream=False, ), False, ) async def _interpret_async_response( self, result: aiohttp.ClientResponse, stream: bool ) -> Tuple[Union[ApacAIResponse, AsyncGenerator[ApacAIResponse, None]], bool]: """Returns the response(s) and a bool indicating whether it is a stream.""" if stream and "text/event-stream" in result.headers.get("Content-Type", ""): return ( self._interpret_response_line( line, result.status, result.headers, stream=True ) async for line in parse_stream_async(result.content) ), True else: try: await result.read() except (aiohttp.ServerTimeoutError, asyncio.TimeoutError) as e: raise error.Timeout("Request timed out") from e except aiohttp.ClientError as e: util.log_warn(e, body=result.content) return ( self._interpret_response_line( (await result.read()).decode("utf-8"), result.status, result.headers, stream=False, ), False, ) def _interpret_response_line( self, rbody: str, rcode: int, rheaders, stream: bool ) -> ApacAIResponse: # HTTP 204 response code does not have any content in the body. if rcode == 204: return ApacAIResponse(None, rheaders) if rcode == 503: raise error.ServiceUnavailableError( "The server is overloaded or not ready yet.", rbody, rcode, headers=rheaders, ) try: if 'text/plain' in rheaders.get('Content-Type', ''): data = rbody else: data = json.loads(rbody) except (JSONDecodeError, UnicodeDecodeError) as e: raise error.APIError( f"HTTP code {rcode} from API ({rbody})", rbody, rcode, headers=rheaders ) from e resp = ApacAIResponse(data, rheaders) # In the future, we might add a "status" parameter to errors # to better handle the "error while streaming" case. stream_error = stream and "error" in resp.data if stream_error or not 200 <= rcode < 300: raise self.handle_error_response( rbody, rcode, resp.data, rheaders, stream_error=stream_error ) return resp @asynccontextmanager async def aiohttp_session() -> AsyncIterator[aiohttp.ClientSession]: user_set_session = apacai.aiosession.get() if user_set_session: yield user_set_session else: async with aiohttp.ClientSession() as session: yield session
apply_necessary_remediation, apply_validators, get_validators, read_any_format, write_out_file, ) class bcolors: HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" ENDC = "\033[0m" BOLD = "\033[1m" UNDERLINE = "\033[4m" def organization_info(obj): organization = getattr(obj, "organization", None) if organization is not None: return "[organization={}] ".format(organization) else: return "" def display(obj): sys.stderr.write(organization_info(obj)) sys.stderr.flush() print(obj) def display_error(e): extra = ( " (HTTP status code: {})".format(e.http_status) if e.http_status is not None else "" ) sys.stderr.write( "{}{}Error:{} {}{}\n".format( organization_info(e), bcolors.FAIL, bcolors.ENDC, e, extra ) ) class Engine: @classmethod def get(cls, args): engine = apacai.Engine.retrieve(id=args.id) display(engine) @classmethod def update(cls, args): engine = apacai.Engine.modify(args.id, replicas=args.replicas) display(engine) @classmethod def generate(cls, args): warnings.warn( "Engine.generate is deprecated, use Completion.create", DeprecationWarning ) if args.completions and args.completions > 1 and args.stream: raise ValueError("Can't stream multiple completions with apacai CLI") kwargs = {} if args.model is not None: kwargs["model"] = args.model resp = apacai.Engine(id=args.id).generate( completions=args.completions, context=args.context, length=args.length, stream=args.stream, temperature=args.temperature, top_p=args.top_p, logprobs=args.logprobs, stop=args.stop, **kwargs, ) if not args.stream: resp = [resp] for part in resp: completions = len(part["data"]) for c_idx, c in enumerate(part["data"]): if completions > 1: sys.stdout.write("===== Completion {} =====\n".format(c_idx)) sys.stdout.write("".join(c["text"])) if completions > 1: sys.stdout.write("\n") sys.stdout.flush() @classmethod def list(cls, args): engines = apacai.Engine.list() display(engines) class ChatCompletion: @classmethod def create(cls, args): if args.n is not None and args.n > 1 and args.stream: raise ValueError( "Can't stream chat completions with n>1 with the current CLI" ) messages = [ {"role": role, "content": content} for role, content in args.message ] resp = apacai.ChatCompletion.create( # Required model=args.model, engine=args.engine, messages=messages, # Optional n=args.n, max_tokens=args.max_tokens, temperature=args.temperature, top_p=args.top_p, stop=args.stop, stream=args.stream, ) if not args.stream: resp = [resp] for part in resp: choices = part["choices"] for c_idx, c in enumerate(sorted(choices, key=lambda s: s["index"])): if len(choices) > 1: sys.stdout.write("===== Chat Completion {} =====\n".format(c_idx)) if args.stream: delta = c["delta"] if "content" in delta: sys.stdout.write(delta["content"]) else: sys.stdout.write(c["message"]["content"]) if len(choices) > 1: # not in streams sys.stdout.write("\n") sys.stdout.flush() class Completion: @classmethod def create(cls, args): if args.n is not None and args.n > 1 and args.stream: raise ValueError("Can't stream completions with n>1 with the current CLI") if args.engine and args.model: warnings.warn( "In most cases, you should not be specifying both engine and model." ) resp = apacai.Completion.create( engine=args.engine, model=args.model, n=args.n, max_tokens=args.max_tokens, logprobs=args.logprobs, prompt=args.prompt, stream=args.stream, temperature=args.temperature, top_p=args.top_p, stop=args.stop, echo=True, ) if not args.stream: resp = [resp] for part in resp: choices = part["choices"] for c_idx, c in enumerate(sorted(choices, key=lambda s: s["index"])): if len(choices) > 1: sys.stdout.write("===== Completion {} =====\n".format(c_idx)) sys.stdout.write(c["text"]) if len(choices) > 1: sys.stdout.write("\n") sys.stdout.flush() class Deployment: @classmethod def get(cls, args): resp = apacai.Deployment.retrieve(id=args.id) print(resp) @classmethod def delete(cls, args): model = apacai.Deployment.delete(args.id) print(model) @classmethod def list(cls, args): models = apacai.Deployment.list() print(models) @classmethod def create(cls, args): models = apacai.Deployment.create( model=args.model, scale_settings={"scale_type": args.scale_type} ) print(models) class Model: @classmethod def get(cls, args): resp = apacai.Model.retrieve(id=args.id) print(resp) @classmethod def delete(cls, args): model = apacai.Model.delete(args.id) print(model) @classmethod def list(cls, args): models = apacai.Model.list() print(models) class File: @classmethod def create(cls, args): with open(args.file, "rb") as file_reader: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") resp = apacai.File.create( file=buffer_reader, purpose=args.purpose, user_provided_filename=args.file, ) print(resp) @classmethod def get(cls, args): resp = apacai.File.retrieve(id=args.id) print(resp) @classmethod def delete(cls, args): file = apacai.File.delete(args.id) print(file) @classmethod def list(cls, args): file = apacai.File.list() print(file) class Image: @classmethod def create(cls, args): resp = apacai.Image.create( prompt=args.prompt, size=args.size, n=args.num_images, response_format=args.response_format, ) print(resp) @classmethod def create_variation(cls, args): with open(args.image, "rb") as file_reader: buffer_reader = BufferReader(file_reader.read(), desc="Upload progress") resp = apacai.Image.create_variation( image=buffer_reader, size=args.size, n=args.num_images, response_format=args.response_format, ) print(resp) @classmethod def create_edit(cls, args): with open(args.image, "rb") as file_reader: image_reader = BufferReader(file_reader.read(), desc="Upload progress") mask_reader = None if args.mask is not None: with open(args.mask, "rb") as file_reader: mask_reader = BufferReader(file_reader.read(), desc="Upload progress") resp = apacai.Image.create_edit( image=image_reader, mask=mask_reader, prompt=args.prompt, size=args.size, n=args.num_images, response_format=args.response_format, ) print(resp) class Audio: @classmethod def transcribe(cls, args): with open(args.file, "rb") as r: file_reader = BufferReader(r.read(), desc="Upload progress") resp = apacai.Audio.transcribe_raw( # Required model=args.model, file=file_reader, filename=args.file, # Optional response_format=args.response_format, language=args.language, temperature=args.temperature, prompt=args.prompt, ) print(resp) @classmethod def translate(cls, args): with open(args.file, "rb") as r: file_reader = BufferReader(r.read(), desc="Upload progress") resp = apacai.Audio.translate_raw( # Required model=args.model, file=file_reader, filename=args.file, # Optional response_format=args.response_format, language=args.language, temperature=args.temperature, prompt=args.prompt, ) print(resp) class FineTune: @classmethod def list(cls, args): resp = apacai.FineTune.list() print(resp) @classmethod def _is_url(cls, file: str): return file.lower().startswith("http") @classmethod def _download_file_from_public_url(cls, url: str) -> Optional[bytes]: resp = requests.get(url) if resp.status_code == 200: return resp.content else: return None @classmethod def _maybe_upload_file( cls, file: Optional[str] = None, content: Optional[bytes] = None, user_provided_file: Optional[str] = None, check_if_file_exists: bool = True, ): # Exactly one of `file` or `content` must be provided if (file is None) == (content is None): raise ValueError("Exactly one of `file` or `content` must be provided") if content is None: assert file is not None with open(file, "rb") as f: content = f.read() if check_if_file_exists: bytes = len(content) matching_files = apacai.File.find_matching_files( name=user_provided_file or f.name, bytes=bytes, purpose="fine-tune" ) if len(matching_files) > 0: file_ids = [f["id"] for f in matching_files] sys.stdout.write( "Found potentially duplicated files with name '{name}', purpose 'fine-tune' and size {size} bytes\n".format( name=os.path.basename(matching_files[0]["filename"]), size=matching_files[0]["bytes"] if "bytes" in matching_files[0] else matching_files[0]["size"], ) ) sys.stdout.write("\n".join(file_ids)) while True: sys.stdout.write( "\nEnter file ID to reuse an already uploaded file, or an empty string to upload this file anyway: " ) inp = sys.stdin.readline().strip() if inp in file_ids: sys.stdout.write( "Reusing already uploaded file: {id}\n".format(id=inp) ) return inp elif inp == "": break else: sys.stdout.write( "File id '{id}' is not among the IDs of the potentially duplicated files\n".format( id=inp ) ) buffer_reader = BufferReader(content, desc="Upload progress") resp = apacai.File.create( file=buffer_reader, purpose="fine-tune", user_provided_filename=user_provided_file or file, ) sys.stdout.write( "Uploaded file from {file}: {id}\n".format( file=user_provided_file or file, id=resp["id"] ) ) return resp["id"] @classmethod def _get_or_upload(cls, file, check_if_file_exists=True): try: # 1. If it's a valid file, use it apacai.File.retrieve(file) return file except apacai.error.InvalidRequestError: pass if os.path.isfile(file): # 2. If it's a file on the filesystem, upload it return cls._maybe_upload_file( file=file, check_if_file_exists=check_if_file_exists ) if cls._is_url(file): # 3. If it's a URL, download it temporarily content = cls._download_file_from_public_url(file) if content is not None: return cls._maybe_upload_file( content=content, check_if_file_exists=check_if_file_exists, user_provided_file=file, ) return file @classmethod def create(cls, args): create_args = { "training_file": cls._get_or_upload( args.training_file, args.check_if_files_exist ), } if args.validation_file: create_args["validation_file"] = cls._get_or_upload( args.validation_file, args.check_if_files_exist ) for hparam in ( "model", "suffix", "n_epochs", "batch_size", "learning_rate_multiplier", "prompt_loss_weight", "compute_classification_metrics", "classification_n_classes", "classification_positive_class", "classification_betas", ): attr = getattr(args, hparam) if attr is not None: create_args[hparam] = attr resp = apacai.FineTune.create(**create_args) if args.no_follow: print(resp) return sys.stdout.write( "Created fine-tune: {job_id}\n" "Streaming events until fine-tuning is complete...\n\n" "(Ctrl-C will interrupt the stream, but not cancel the fine-tune)\n".format( job_id=resp["id"] ) ) cls._stream_events(resp["id"]) @classmethod def get(cls, args): resp = apacai.FineTune.retrieve(id=args.id) print(resp) @classmethod def results(cls, args): fine_tune = apacai.FineTune.retrieve(id=args.id) if "result_files" not in fine_tune or len(fine_tune["result_files"]) == 0: raise apacai.error.InvalidRequestError( f"No results file available for fine-tune {args.id}", "id" ) result_file = apacai.FineTune.retrieve(id=args.id)["result_files"][0] resp = apacai.File.download(id=result_file["id"]) print(resp.decode("utf-8")) @classmethod def events(cls, args): if args.stream: raise apacai.error.ApacAIError( message=( "The --stream parameter is deprecated, use fine_tunes.follow " "instead:\n\n" " apacai api fine_tunes.follow -i {id}\n".format(id=args.id) ), ) resp = apacai.FineTune.list_events(id=args.id) # type: ignore print(resp) @classmethod def follow(cls, args): cls._stream_events(args.id) @classmethod def _stream_events(cls, job_id): def signal_handler(sig, frame): status = apacai.FineTune.retrieve(job_id).status sys.stdout.write( "\nStream interrupted. Job is still {status}.\n" "To resume the stream, run:\n\n" " apacai api fine_tunes.follow -i {job_id}\n\n" "To cancel your job, run:\n\n" " apacai api fine_tunes.cancel -i {job_id}\n\n".format( status=status, job_id=job_id ) ) sys.exit(0) signal.signal(signal.SIGINT, signal_handler) events = apacai.FineTune.stream_events(job_id) # TODO(rachel): Add a nifty spinner here. try: for event in events: sys.stdout.write( "[%s] %s" % ( datetime.datetime.fromtimestamp(event["created_at"]), event["message"], ) ) sys.stdout.write("\n") sys.stdout.flush() except Exception: sys.stdout.write( "\nStream interrupted (client disconnected).\n" "To resume the stream, run:\n\n" " apacai api fine_tunes.follow -i {job_id}\n\n".format(job_id=job_id) ) return resp = apacai.FineTune.retrieve(id=job_id) status = resp["status"] if status == "succeeded": sys.stdout.write("\nJob complete! Status: succeeded 🎉") sys.stdout.write( "\nTry out your fine-tuned model:\n\n" "apacai api completions.create -m {model} -p <YOUR_PROMPT>".format( model=resp["fine_tuned_model"] ) ) elif status == "failed": sys.stdout.write( "\nJob failed. Please contact us through our help center at help.apacai.com if you need assistance." ) sys.stdout.write("\n") @classmethod def cancel(cls, args): resp = apacai.FineTune.cancel(id=args.id) print(resp) @classmethod def delete(cls, args): resp = apacai.FineTune.delete(sid=args.id) print(resp) @classmethod def prepare_data(cls, args): sys.stdout.write("Analyzing...\n") fname = args.file auto_accept = args.quiet df, remediation = read_any_format(fname) apply_necessary_remediation(None, remediation) validators = get_validators() apply_validators( df, fname, remediation, validators, auto_accept, write_out_file_func=write_out_file, ) class WandbLogger: @classmethod def sync(cls, args): import apacai.wandb_logger resp = apacai.wandb_logger.WandbLogger.sync( id=args.id, n_fine_tunes=args.n_fine_tunes, project=args.project, entity=args.entity, force=args.force, ) print(resp) def tools_register(parser): subparsers = parser.add_subparsers( title="Tools", help="Convenience client side tools" ) def help(args): parser.print_help() parser.set_defaults(func=help) sub = subparsers.add_parser("fine_tunes.prepare_data") sub.add_argument( "-f", "--file", required=True, help="JSONL, JSON, CSV, TSV, TXT or XLSX file containing prompt-completion examples to be analyzed." "This should be the local file path.", ) sub.add_argument( "-q", "--quiet", required=False, action="store_true", help="Auto accepts all suggestions, without asking for user input. To be used within scripts.", ) sub.set_defaults(func=FineTune.prepare_data) def api_register(parser): # Engine management subparsers = parser.add_subparsers(help="All API subcommands") def help(args): parser.print_help() parser.set_defaults(func=help) sub = subparsers.add_parser("engines.list") sub.set_defaults(func=Engine.list) sub = subparsers.add_parser("engines.get") sub.add_argument("-i", "--id", required=True) sub.set_defaults(func=Engine.get) sub = subparsers.add_parser("engines.update") sub.add_argument("-i", "--id", required=True) sub.add_argument("-r", "--replicas", type=int) sub.set_defaults(func=Engine.update) sub = subparsers.add_parser("engines.generate") sub.add_argument("-i", "--id", required=True) sub.add_argument( "--stream", help="Stream tokens as they're ready.", action="store_true" ) sub.add_argument("-c", "--context", help="An optional context to generate from") sub.add_argument("-l", "--length", help="How many tokens to generate", type=int) sub.add_argument( "-t", "--temperature", help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. Mutually exclusive with `top_p`.""", type=float, ) sub.add_argument( "-p", "--top_p", help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. Mutually exclusive with `temperature`.""", type=float, ) sub.add_argument( "-n", "--completions", help="How many parallel completions to run on this context", type=int, ) sub.add_argument( "--logprobs", help="Include the log probabilites on the `logprobs` most likely tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is supplied, the API will always return the logprob of the generated token, so there may be up to `logprobs+1` elements in the response.", type=int, ) sub.add_argument( "--stop", help="A stop sequence at which to stop generating tokens." ) sub.add_argument( "-m", "--model", required=False, help="A model (most commonly a model ID) to generate from. Defaults to the engine's default model.", ) sub.set_defaults(func=Engine.generate) # Chat Completions sub = subparsers.add_parser("chat_completions.create") sub._action_groups.pop() req = sub.add_argument_group("required arguments") opt = sub.add_argument_group("optional arguments") req.add_argument( "-g", "--message", action="append", nargs=2, metavar=("ROLE", "CONTENT"), help="A message in `{role} {content}` format. Use this argument multiple times to add multiple messages.", required=True, ) group = opt.add_mutually_exclusive_group() group.add_argument( "-e", "--engine", help="The engine to use. See https://learn.microsoft.com/en-us/azure/cognitive-services/apacai/chatgpt-quickstart?pivots=programming-language-python for more about what engines are available.", ) group.add_argument( "-m", "--model", help="The model to use.", ) opt.add_argument( "-n", "--n", help="How many completions to generate for the conversation.", type=int, ) opt.add_argument( "-M", "--max-tokens", help="The maximum number of tokens to generate.", type=int ) opt.add_argument( "-t", "--temperature", help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. Mutually exclusive with `top_p`.""", type=float, ) opt.add_argument( "-P", "--top_p", help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. Mutually exclusive with `temperature`.""", type=float, ) opt.add_argument( "--stop", help="A stop sequence at which to stop generating tokens for the message.", ) opt.add_argument( "--stream", help="Stream messages as they're ready.", action="store_true" ) sub.set_defaults(func=ChatCompletion.create) # Completions sub = subparsers.add_parser("completions.create") sub.add_argument( "-e", "--engine", help="The engine to use. See https://platform.apacai.com/docs/engines for more about what engines are available.", ) sub.add_argument( "-m", "--model", help="The model to use. At most one of `engine` or `model` should be specified.", ) sub.add_argument( "--stream", help="Stream tokens as they're ready.", action="store_true" ) sub.add_argument("-p", "--prompt", help="An optional prompt to complete from") sub.add_argument( "-M", "--max-tokens", help="The maximum number of tokens to generate", type=int ) sub.add_argument( "-t", "--temperature", help="""What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. Mutually exclusive with `top_p`.""", type=float, ) sub.add_argument( "-P", "--top_p", help="""An alternative to sampling with temperature, called nucleus sampling, where the considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%% probability mass are considered. Mutually exclusive with `temperature`.""", type=float, ) sub.add_argument( "-n", "--n", help="How many sub-completions to generate for each prompt.", type=int, ) sub.add_argument( "--logprobs", help="Include the log probabilites on the `logprobs` most likely tokens, as well the chosen tokens. So for example, if `logprobs` is 10, the API will return a list of the 10 most likely tokens. If `logprobs` is 0, only the chosen tokens will have logprobs returned.", type=int, ) sub.add_argument( "--stop", help="A stop sequence at which to stop generating tokens." ) sub.set_defaults(func=Completion.create) # Deployments sub = subparsers.add_parser("deployments.list") sub.set_defaults(func=Deployment.list) sub = subparsers.add_parser("deployments.get") sub.add_argument("-i", "--id", required=True, help="The deployment ID") sub.set_defaults(func=Deployment.get) sub = subparsers.add_parser("deployments.delete") sub.add_argument("-i", "--id", required=True, help="The deployment ID") sub.set_defaults(func=Deployment.delete) sub = subparsers.add_parser("deployments.create") sub.add_argument("-m", "--model", required=True, help="The model ID") sub.add_argument( "-s", "--scale_type", required=True, help="The scale type. Either 'manual' or 'standard'", ) sub.set_defaults(func=Deployment.create) # Models sub = subparsers.add_parser("models.list") sub.set_defaults(func=Model.list) sub = subparsers.add_parser("models.get") sub.add_argument("-i", "--id", required=True, help="The model ID") sub.set_defaults(func=Model.get) sub = subparsers.add_parser("models.delete") sub.add_argument("-i", "--id", required=True, help="The model ID") sub.set_defaults(func=Model.delete) # Files sub = subparsers.add_parser("files.create") sub.add_argument( "-f", "--file", required=True, help="File to upload", ) sub.add_argument( "-p", "--purpose", help="Why are you uploading this file? (see https://platform.apacai.com/docs/api-reference/ for purposes)", required=True, ) sub.set_defaults(func=File.create) sub = subparsers.add_parser("files.get") sub.add_argument("-i", "--id", required=True, help="The files ID") sub.set_defaults(func=File.get) sub = subparsers.add_parser("files.delete") sub.add_argument("-i", "--id", required=True, help="The files ID") sub.set_defaults(func=File.delete) sub = subparsers.add_parser("files.list") sub.set_defaults(func=File.list) # Finetune sub = subparsers.add_parser("fine_tunes.list") sub.set_defaults(func=FineTune.list) sub = subparsers.add_parser("fine_tunes.create") sub.add_argument( "-t", "--training_file", required=True, help="JSONL file containing prompt-completion examples for training. This can " "be the ID of a file uploaded through the APACAI API (e.g. file-abcde12345), " 'a local file path, or a URL that starts with "http".', ) sub.add_argument( "-v", "--validation_file", help="JSONL file containing prompt-completion examples for validation. This can " "be the ID of a file uploaded through the APACAI API (e.g. file-abcde12345), " 'a local file path, or a URL that starts with "http".', ) sub.add_argument( "--no_check_if_files_exist", dest="check_if_files_exist", action="store_false", help="If this argument is set and training_file or validation_file are file paths, immediately upload them. If this argument is not set, check if they may be duplicates of already uploaded files before uploading, based on file name and file size.", ) sub.add_argument( "-m", "--model", help="The model to start fine-tuning from", ) sub.add_argument( "--suffix", help="If set, this argument can be used to customize the generated fine-tuned model name." "All punctuation and whitespace in `suffix` will be replaced with a " "single dash, and the string will be lower cased. The max " "length of `suffix` is 40 chars. " "The generated name will match the form `{base_model}:ft-{org-title}:{suffix}-{timestamp}`. " 'For example, `apacai api fine_tunes.create -t test.jsonl -m ada --suffix "custom model name" ' "could generate a model with the name " "ada:ft-your-org:custom-model-name-2022-02-15-04-21-04", ) sub.add_argument( "--no_follow", action="store_true", help="If set, returns immediately after creating the job. Otherwise, streams events and waits for the job to complete.", ) sub.add_argument( "--n_epochs", type=int, help="The number of epochs to train the model for. An epoch refers to one " "full cycle through the training dataset.", ) sub.add_argument( "--batch_size", type=int, help="The batch size to use for training. The batch size is the number of " "training examples used to train a single forward and backward pass.", ) sub.add_argument( "--learning_rate_multiplier", type=float, help="The learning rate multiplier to use for training. The fine-tuning " "learning rate is determined by the original learning rate used for " "pretraining multiplied by this value.", ) sub.add_argument( "--prompt_loss_weight", type=float, help="The weight to use for the prompt loss. The optimum value here depends " "depends on your use case. This determines how much the model prioritizes " "learning from prompt tokens vs learning from completion tokens.", ) sub.add_argument( "--compute_classification_metrics", action="store_true", help="If set, we calculate classification-specific metrics such as accuracy " "and F-1 score using the validation set at the end of every epoch.", ) sub.set_defaults(compute_classification_metrics=None) sub.add_argument( "--classification_n_classes", type=int, help="The number of classes in a classification task. This parameter is " "required for multiclass classification.", ) sub.add_argument( "--classification_positive_class", help="The positive class in binary classification. This parameter is needed " "to generate precision, recall and F-1 metrics when doing binary " "classification.", ) sub.add_argument( "--classification_betas", type=float, nargs="+", help="If this is provided, we calculate F-beta scores at the specified beta " "values. The F-beta score is a generalization of F-1 score. This is only " "used for binary classification.", ) sub.set_defaults(func=FineTune.create) sub = subparsers.add_parser("fine_tunes.get") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") sub.set_defaults(func=FineTune.get) sub = subparsers.add_parser("fine_tunes.results") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") sub.set_defaults(func=FineTune.results) sub = subparsers.add_parser("fine_tunes.events") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") # TODO(rachel): Remove this in 1.0 sub.add_argument( "-s", "--stream", action="store_true", help="[DEPRECATED] If set, events will be streamed until the job is done. Otherwise, " "displays the event history to date.", ) sub.set_defaults(func=FineTune.events) sub = subparsers.add_parser("fine_tunes.follow") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") sub.set_defaults(func=FineTune.follow) sub = subparsers.add_parser("fine_tunes.cancel") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") sub.set_defaults(func=FineTune.cancel) sub = subparsers.add_parser("fine_tunes.delete") sub.add_argument("-i", "--id", required=True, help="The id of the fine-tune job") sub.set_defaults(func=FineTune.delete) # Image sub = subparsers.add_parser("image.create") sub.add_argument("-p", "--prompt", type=str, required=True) sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument( "-s", "--size", type=str, default="1024x1024", help="Size of the output image" ) sub.add_argument("--response-format", type=str, default="url") sub.set_defaults(func=Image.create) sub = subparsers.add_parser("image.create_edit") sub.add_argument("-p", "--prompt", type=str, required=True) sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument( "-I", "--image", type=str, required=True, help="Image to modify. Should be a local path and a PNG encoded image.", ) sub.add_argument( "-s", "--size", type=str, default="1024x1024", help="Size of the output image" ) sub.add_argument("--response-format", type=str, default="url") sub.add_argument( "-M", "--mask", type=str, required=False, help="Path to a mask image. It should be the same size as the image you're editing and a RGBA PNG image. The Alpha channel acts as the mask.", ) sub.set_defaults(func=Image.create_edit) sub = subparsers.add_parser("image.create_variation") sub.add_argument("-n", "--num-images", type=int, default=1) sub.add_argument( "-I", "--image", type=str, required=True, help="Image to modify. Should be a local path and a PNG encoded image.", ) sub.add_argument( "-s", "--size", type=str, default="1024x1024", help="Size of the output image" ) sub.add_argument("--response-format", type=str, default="url") sub.set_defaults(func=Image.create_variation) # Audio # transcriptions sub = subparsers.add_parser("audio.transcribe") # Required sub.add_argument("-m", "--model", type=str, default="whisper-1") sub.add_argument("-f", "--file", type=str, required=True) # Optional sub.add_argument("--response-format", type=str) sub.add_argument("--language", type=str) sub.add_argument("-t", "--temperature", type=float) sub.add_argument("--prompt", type=str) sub.set_defaults(func=Audio.transcribe) # translations sub = subparsers.add_parser("audio.translate") # Required sub.add_argument("-m", "--model", type=str, default="whisper-1") sub.add_argument("-f", "--file", type=str, required=True) # Optional sub.add_argument("--response-format", type=str) sub.add_argument("--language", type=str) sub.add_argument("-t", "--temperature", type=float) sub.add_argument("--prompt", type=str) sub.set_defaults(func=Audio.translate) def wandb_register(parser): subparsers = parser.add_subparsers( title="wandb", help="Logging with Weights & Biases" ) def help(args): parser.print_help() parser.set_defaults(func=help) sub = subparsers.add_parser("sync") sub.add_argument("-i", "--id", help="The id of the fine-tune job (optional)") sub.add_argument( "-n", "--n_fine_tunes", type=int, default=None, help="Number of most recent fine-tunes to log when an id is not provided. By default, every fine-tune is synced.", ) sub.add_argument( "--project", default="GPT-3", help="""Name of the project where you're sending runs. By default, it is "GPT-3".""", ) sub.add_argument( "--entity", help="Username or team name where you're sending runs. By default, your default entity is used, which is usually your username.", ) sub.add_argument( "--force", action="store_true", help="Forces logging and overwrite existing wandb run of the same fine-tune.", ) sub.set_defaults(force=False) sub.set_defaults(func=WandbLogger.sync)
class ApacAIResponse: def __init__(self, data, headers): self._headers = headers self.data = data @property def request_id(self) -> Optional[str]: return self._headers.get("request-id") @property def retry_after(self) -> Optional[int]: try: return int(self._headers.get("retry-after")) except TypeError: return None @property def operation_location(self) -> Optional[str]: return self._headers.get("operation-location") @property def organization(self) -> Optional[str]: return self._headers.get("APACAI-Organization") @property def response_ms(self) -> Optional[int]: h = self._headers.get("APACAI-Processing-Ms") return None if h is None else round(float(h))
@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) def get_embedding(text: str, engine="text-similarity-davinci-001", **kwargs) -> List[float]: # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") return apacai.Embedding.create(input=[text], engine=engine, **kwargs)["data"][0]["embedding"] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embedding( text: str, engine="text-similarity-davinci-001", **kwargs ) -> List[float]: # replace newlines, which can negatively affect performance. text = text.replace("\n", " ") return (await apacai.Embedding.acreate(input=[text], engine=engine, **kwargs))["data"][0][ "embedding" ] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) def get_embeddings( list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs ) -> List[List[float]]: assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] data = apacai.Embedding.create(input=list_of_text, engine=engine, **kwargs).data return [d["embedding"] for d in data] @retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(6)) async def aget_embeddings( list_of_text: List[str], engine="text-similarity-babbage-001", **kwargs ) -> List[List[float]]: assert len(list_of_text) <= 2048, "The batch size should not be larger than 2048." # replace newlines, which can negatively affect performance. list_of_text = [text.replace("\n", " ") for text in list_of_text] data = (await apacai.Embedding.acreate(input=list_of_text, engine=engine, **kwargs)).data return [d["embedding"] for d in data] def cosine_similarity(a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) def plot_multiclass_precision_recall( y_score, y_true_untransformed, class_list, classifier_name ): """ Precision-Recall plotting for a multiclass problem. It plots average precision-recall, per class precision recall and reference f1 contours. Code slightly modified, but heavily based on https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html """ n_classes = len(class_list) y_true = pd.concat( [(y_true_untransformed == class_list[i]) for i in range(n_classes)], axis=1 ).values # For each class precision = dict() recall = dict() average_precision = dict() for i in range(n_classes): precision[i], recall[i], _ = precision_recall_curve(y_true[:, i], y_score[:, i]) average_precision[i] = average_precision_score(y_true[:, i], y_score[:, i]) # A "micro-average": quantifying score on all classes jointly precision_micro, recall_micro, _ = precision_recall_curve( y_true.ravel(), y_score.ravel() ) average_precision_micro = average_precision_score(y_true, y_score, average="micro") print( str(classifier_name) + " - Average precision score over all classes: {0:0.2f}".format( average_precision_micro ) ) # setup plot details plt.figure(figsize=(9, 10)) f_scores = np.linspace(0.2, 0.8, num=4) lines = [] labels = [] for f_score in f_scores: x = np.linspace(0.01, 1) y = f_score * x / (2 * x - f_score) (l,) = plt.plot(x[y >= 0], y[y >= 0], color="gray", alpha=0.2) plt.annotate("f1={0:0.1f}".format(f_score), xy=(0.9, y[45] + 0.02)) lines.append(l) labels.append("iso-f1 curves") (l,) = plt.plot(recall_micro, precision_micro, color="gold", lw=2) lines.append(l) labels.append( "average Precision-recall (auprc = {0:0.2f})" "".format(average_precision_micro) ) for i in range(n_classes): (l,) = plt.plot(recall[i], precision[i], lw=2) lines.append(l) labels.append( "Precision-recall for class `{0}` (auprc = {1:0.2f})" "".format(class_list[i], average_precision[i]) ) fig = plt.gcf() fig.subplots_adjust(bottom=0.25) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel("Recall") plt.ylabel("Precision") plt.title(f"{classifier_name}: Precision-Recall curve for each class") plt.legend(lines, labels) def distances_from_embeddings( query_embedding: List[float], embeddings: List[List[float]], distance_metric="cosine", ) -> List[List]: """Return the distances between a query embedding and a list of embeddings.""" distance_metrics = { "cosine": spatial.distance.cosine, "L1": spatial.distance.cityblock, "L2": spatial.distance.euclidean, "Linf": spatial.distance.chebyshev, } distances = [ distance_metrics[distance_metric](query_embedding, embedding) for embedding in embeddings ] return distances def indices_of_nearest_neighbors_from_distances(distances) -> np.ndarray: """Return a list of indices of nearest neighbors from a list of distances.""" return np.argsort(distances) def pca_components_from_embeddings( embeddings: List[List[float]], n_components=2 ) -> np.ndarray: """Return the PCA components of a list of embeddings.""" pca = PCA(n_components=n_components) array_of_embeddings = np.array(embeddings) return pca.fit_transform(array_of_embeddings) def tsne_components_from_embeddings( embeddings: List[List[float]], n_components=2, **kwargs ) -> np.ndarray: """Returns t-SNE components of a list of embeddings.""" # use better defaults if not specified if "init" not in kwargs.keys(): kwargs["init"] = "pca" if "learning_rate" not in kwargs.keys(): kwargs["learning_rate"] = "auto" tsne = TSNE(n_components=n_components, **kwargs) array_of_embeddings = np.array(embeddings) return tsne.fit_transform(array_of_embeddings) def chart_from_components( components: np.ndarray, labels: Optional[List[str]] = None, strings: Optional[List[str]] = None, x_title="Component 0", y_title="Component 1", mark_size=5, **kwargs, ): """Return an interactive 2D chart of embedding components.""" empty_list = ["" for _ in components] data = pd.DataFrame( { x_title: components[:, 0], y_title: components[:, 1], "label": labels if labels else empty_list, "string": ["<br>".join(tr.wrap(string, width=30)) for string in strings] if strings else empty_list, } ) chart = px.scatter( data, x=x_title, y=y_title, color="label" if labels else None, symbol="label" if labels else None, hover_data=["string"] if strings else None, **kwargs, ).update_traces(marker=dict(size=mark_size)) return chart def chart_from_components_3D( components: np.ndarray, labels: Optional[List[str]] = None, strings: Optional[List[str]] = None, x_title: str = "Component 0", y_title: str = "Component 1", z_title: str = "Compontent 2", mark_size: int = 5, **kwargs, ): """Return an interactive 3D chart of embedding components.""" empty_list = ["" for _ in components] data = pd.DataFrame( { x_title: components[:, 0], y_title: components[:, 1], z_title: components[:, 2], "label": labels if labels else empty_list, "string": ["<br>".join(tr.wrap(string, width=30)) for string in strings] if strings else empty_list, } ) chart = px.scatter_3d( data, x=x_title, y=y_title, z=z_title, color="label" if labels else None, symbol="label" if labels else None, hover_data=["string"] if strings else None, **kwargs, ).update_traces(marker=dict(size=mark_size)) return chart
class ApacAIObject(dict): api_base_override = None def __init__( self, id=None, api_key=None, api_version=None, api_type=None, organization=None, response_ms: Optional[int] = None, api_base=None, engine=None, **params, ): super(ApacAIObject, self).__init__() if response_ms is not None and not isinstance(response_ms, int): raise TypeError(f"response_ms is a {type(response_ms).__name__}.") self._response_ms = response_ms self._retrieve_params = params object.__setattr__(self, "api_key", api_key) object.__setattr__(self, "api_version", api_version) object.__setattr__(self, "api_type", api_type) object.__setattr__(self, "organization", organization) object.__setattr__(self, "api_base_override", api_base) object.__setattr__(self, "engine", engine) if id: self["id"] = id @property def response_ms(self) -> Optional[int]: return self._response_ms def __setattr__(self, k, v): if k[0] == "_" or k in self.__dict__: return super(ApacAIObject, self).__setattr__(k, v) self[k] = v return None def __getattr__(self, k): if k[0] == "_": raise AttributeError(k) try: return self[k] except KeyError as err: raise AttributeError(*err.args) def __delattr__(self, k): if k[0] == "_" or k in self.__dict__: return super(ApacAIObject, self).__delattr__(k) else: del self[k] def __setitem__(self, k, v): if v == "": raise ValueError( "You cannot set %s to an empty string. " "We interpret empty strings as None in requests." "You may set %s.%s = None to delete the property" % (k, str(self), k) ) super(ApacAIObject, self).__setitem__(k, v) def __delitem__(self, k): raise NotImplementedError("del is not supported") # Custom unpickling method that uses `update` to update the dictionary # without calling __setitem__, which would fail if any value is an empty # string def __setstate__(self, state): self.update(state) # Custom pickling method to ensure the instance is pickled as a custom # class and not as a dict, otherwise __setstate__ would not be called when # unpickling. def __reduce__(self): reduce_value = ( type(self), # callable ( # args self.get("id", None), self.api_key, self.api_version, self.api_type, self.organization, ), dict(self), # state ) return reduce_value @classmethod def construct_from( cls, values, api_key: Optional[str] = None, api_version=None, organization=None, engine=None, response_ms: Optional[int] = None, ): instance = cls( values.get("id"), api_key=api_key, api_version=api_version, organization=organization, engine=engine, response_ms=response_ms, ) instance.refresh_from( values, api_key=api_key, api_version=api_version, organization=organization, response_ms=response_ms, ) return instance def refresh_from( self, values, api_key=None, api_version=None, api_type=None, organization=None, response_ms: Optional[int] = None, ): self.api_key = api_key or getattr(values, "api_key", None) self.api_version = api_version or getattr(values, "api_version", None) self.api_type = api_type or getattr(values, "api_type", None) self.organization = organization or getattr(values, "organization", None) self._response_ms = response_ms or getattr(values, "_response_ms", None) # Wipe old state before setting new. self.clear() for k, v in values.items(): super(ApacAIObject, self).__setitem__( k, util.convert_to_apacai_object(v, api_key, api_version, organization) ) self._previous = values @classmethod def api_base(cls): return None def request( self, method, url, params=None, headers=None, stream=False, plain_old_data=False, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ): if params is None: params = self._retrieve_params requestor = api_requestor.APIRequestor( key=self.api_key, api_base=self.api_base_override or self.api_base(), api_type=self.api_type, api_version=self.api_version, organization=self.organization, ) response, stream, api_key = requestor.request( method, url, params=params, stream=stream, headers=headers, request_id=request_id, request_timeout=request_timeout, ) if stream: assert not isinstance(response, ApacAIResponse) # must be an iterator return ( util.convert_to_apacai_object( line, api_key, self.api_version, self.organization, plain_old_data=plain_old_data, ) for line in response ) else: return util.convert_to_apacai_object( response, api_key, self.api_version, self.organization, plain_old_data=plain_old_data, ) async def arequest( self, method, url, params=None, headers=None, stream=False, plain_old_data=False, request_id: Optional[str] = None, request_timeout: Optional[Union[float, Tuple[float, float]]] = None, ): if params is None: params = self._retrieve_params requestor = api_requestor.APIRequestor( key=self.api_key, api_base=self.api_base_override or self.api_base(), api_type=self.api_type, api_version=self.api_version, organization=self.organization, ) response, stream, api_key = await requestor.arequest( method, url, params=params, stream=stream, headers=headers, request_id=request_id, request_timeout=request_timeout, ) if stream: assert not isinstance(response, ApacAIResponse) # must be an iterator return ( util.convert_to_apacai_object( line, api_key, self.api_version, self.organization, plain_old_data=plain_old_data, ) for line in response ) else: return util.convert_to_apacai_object( response, api_key, self.api_version, self.organization, plain_old_data=plain_old_data, ) def __repr__(self): ident_parts = [type(self).__name__] obj = self.get("object") if isinstance(obj, str): ident_parts.append(obj) if isinstance(self.get("id"), str): ident_parts.append("id=%s" % (self.get("id"),)) unicode_repr = "<%s at %s> JSON: %s" % ( " ".join(ident_parts), hex(id(self)), str(self), ) return unicode_repr def __str__(self): obj = self.to_dict_recursive() return json.dumps(obj, indent=2) def to_dict(self): return dict(self) def to_dict_recursive(self): d = dict(self) for k, v in d.items(): if isinstance(v, ApacAIObject): d[k] = v.to_dict_recursive() elif isinstance(v, list): d[k] = [ e.to_dict_recursive() if isinstance(e, ApacAIObject) else e for e in v ] return d @property def apacai_id(self): return self.id @property def typed_api_type(self): return ( ApiType.from_str(self.api_type) if self.api_type else ApiType.from_str(apacai.api_type) ) # This class overrides __setitem__ to throw exceptions on inputs that it # doesn't like. This can cause problems when we try to copy an object # wholesale because some data that's returned from the API may not be valid # if it was set to be set manually. Here we override the class' copy # arguments so that we can bypass these possible exceptions on __setitem__. def __copy__(self): copied = ApacAIObject( self.get("id"), self.api_key, api_version=self.api_version, api_type=self.api_type, organization=self.organization, ) copied._retrieve_params = self._retrieve_params for k, v in self.items(): # Call parent's __setitem__ to avoid checks that we've added in the # overridden version that can throw exceptions. super(ApacAIObject, copied).__setitem__(k, v) return copied # This class overrides __setitem__ to throw exceptions on inputs that it # doesn't like. This can cause problems when we try to copy an object # wholesale because some data that's returned from the API may not be valid # if it was set to be set manually. Here we override the class' copy # arguments so that we can bypass these possible exceptions on __setitem__. def __deepcopy__(self, memo): copied = self.__copy__() memo[id(self)] = copied for k, v in self.items(): # Call parent's __setitem__ to avoid checks that we've added in the # overridden version that can throw exceptions. super(ApacAIObject, copied).__setitem__(k, deepcopy(v, memo)) return copied
try: import pandas except ImportError: pandas = None HAS_PANDAS = bool(pandas) PANDAS_INSTRUCTIONS = INSTRUCTIONS.format(library="pandas") def assert_has_pandas(): if not HAS_PANDAS: raise MissingDependencyError(PANDAS_INSTRUCTIONS)
""" This module helps make data libraries like `numpy` and `pandas` optional dependencies. The libraries add up to 130MB+, which makes it challenging to deploy applications using this library in environments with code size constraints, like AWS Lambda. This module serves as an import proxy and provides a few utilities for dealing with the optionality. Since the primary use case of this library (talking to the APACAI API) doesn't generally require data libraries, it's safe to make them optional. The rare case when data libraries are needed in the client is handled through assertions with instructive error messages. See also `setup.py`. """
INSTRUCTIONS = """ APACAI error: missing `{library}` This feature requires additional dependencies: $ pip install apacai[datalib] """ NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") class MissingDependencyError(Exception): pass
try: import numpy except ImportError: numpy = None HAS_NUMPY = bool(numpy) NUMPY_INSTRUCTIONS = INSTRUCTIONS.format(library="numpy") def assert_has_numpy(): if not HAS_NUMPY: raise MissingDependencyError(NUMPY_INSTRUCTIONS)
STILL_PROCESSING = "File is still processing. Check back later." def test_file_cli() -> None: contents = json.dumps({"prompt": "1 + 3 =", "completion": "4"}) + "\n" with NamedTemporaryFile(suffix=".jsonl", mode="wb") as train_file: train_file.write(contents.encode("utf-8")) train_file.flush() create_output = subprocess.check_output( ["apacai", "api", "files.create", "-f", train_file.name, "-p", "fine-tune"] ) file_obj = json.loads(create_output) assert file_obj["bytes"] == len(contents) file_id: str = file_obj["id"] assert file_id.startswith("file-") start_time = time.time() while True: delete_result = subprocess.run( ["apacai", "api", "files.delete", "-i", file_id], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8", ) if delete_result.returncode == 0: break elif STILL_PROCESSING in delete_result.stderr: time.sleep(0.5) if start_time + 60 < time.time(): raise RuntimeError("timed out waiting for file to become available") continue else: raise RuntimeError( f"delete failed: stdout={delete_result.stdout} stderr={delete_result.stderr}" )
# FILE TESTS def test_file_upload(): result = apacai.File.create( file=io.StringIO( json.dumps({"prompt": "test file data", "completion": "tada"}) ), purpose="fine-tune", ) assert result.purpose == "fine-tune" assert "id" in result result = apacai.File.retrieve(id=result.id) assert result.status == "uploaded" # CHAT COMPLETION TESTS def test_chat_completions(): result = apacai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello!"}] ) assert len(result.choices) == 1 def test_chat_completions_multiple(): result = apacai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello!"}], n=5 ) assert len(result.choices) == 5 def test_chat_completions_streaming(): result = None events = apacai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hello!"}], stream=True, ) for result in events: assert len(result.choices) == 1 # COMPLETION TESTS def test_completions(): result = apacai.Completion.create(prompt="This was a test", n=5, engine="ada") assert len(result.choices) == 5 def test_completions_multiple_prompts(): result = apacai.Completion.create( prompt=["This was a test", "This was another test"], n=5, engine="ada" ) assert len(result.choices) == 10 def test_completions_model(): result = apacai.Completion.create(prompt="This was a test", n=5, model="ada") assert len(result.choices) == 5 assert result.model.startswith("ada") def test_timeout_raises_error(): # A query that should take awhile to return with pytest.raises(error.Timeout): apacai.Completion.create( prompt="test" * 1000, n=10, model="ada", max_tokens=100, request_timeout=0.01, ) def test_timeout_does_not_error(): # A query that should be fast apacai.Completion.create( prompt="test", model="ada", request_timeout=10, ) def test_user_session(): with requests.Session() as session: apacai.requestssession = session completion = apacai.Completion.create( prompt="hello world", model="ada", ) assert completion def test_user_session_factory(): def factory(): session = requests.Session() session.mount( "https://", requests.adapters.HTTPAdapter(max_retries=4), ) return session apacai.requestssession = factory completion = apacai.Completion.create( prompt="hello world", model="ada", ) assert completion
EXCEPTION_TEST_CASES = [ apacai.InvalidRequestError( "message", "param", code=400, http_body={"test": "test1"}, http_status="fail", json_body={"text": "iono some text"}, headers={"request-id": "asasd"}, ), apacai.error.AuthenticationError(), apacai.error.PermissionError(), apacai.error.RateLimitError(), apacai.error.ServiceUnavailableError(), apacai.error.SignatureVerificationError("message", "sig_header?"), apacai.error.APIConnectionError("message!", should_retry=True), apacai.error.TryAgain(), apacai.error.Timeout(), apacai.error.APIError( message="message", code=400, http_body={"test": "test1"}, http_status="fail", json_body={"text": "iono some text"}, headers={"request-id": "asasd"}, ), apacai.error.ApacAIError(), ] class TestExceptions: @pytest.mark.parametrize("error", EXCEPTION_TEST_CASES) def test_exceptions_are_pickleable(self, error) -> None: assert error.__repr__() == pickle.loads(pickle.dumps(error)).__repr__()
@pytest.fixture(scope="function") def api_key_file(): saved_path = apacai.api_key_path try: with NamedTemporaryFile(prefix="apacai-api-key", mode="wt") as tmp: apacai.api_key_path = tmp.name yield tmp finally: apacai.api_key_path = saved_path def test_apacai_api_key_path(api_key_file) -> None: print("sk-foo", file=api_key_file) api_key_file.flush() assert util.default_api_key() == "sk-foo" def test_apacai_api_key_path_with_malformed_key(api_key_file) -> None: print("malformed-api-key", file=api_key_file) api_key_file.flush() with pytest.raises(ValueError, match="Malformed API key"): util.default_api_key() def test_key_order_apacai_object_rendering() -> None: sample_response = { "id": "chatcmpl-7NaPEA6sgX7LnNPyKPbRlsyqLbr5V", "object": "chat.completion", "created": 1685855844, "model": "gpt-3.5-turbo-0301", "usage": {"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97}, "choices": [ { "message": { "role": "assistant", "content": "The 2020 World Series was played at Globe Life Field in Arlington, Texas. It was the first time that the World Series was played at a neutral site because of the COVID-19 pandemic.", }, "finish_reason": "stop", "index": 0, } ], } oai_object = util.convert_to_apacai_object(sample_response) # The `__str__` method was sorting while dumping to json assert list(json.loads(str(oai_object)).keys()) == list(sample_response.keys())
@pytest.mark.url def test_completions_url_composition_azure() -> None: url = Completion.class_url("test_engine", "azure", "2021-11-01-preview") assert ( url == "/apacai/deployments/test_engine/completions?api-version=2021-11-01-preview" ) @pytest.mark.url def test_completions_url_composition_azure_ad() -> None: url = Completion.class_url("test_engine", "azure_ad", "2021-11-01-preview") assert ( url == "/apacai/deployments/test_engine/completions?api-version=2021-11-01-preview" ) @pytest.mark.url def test_completions_url_composition_default() -> None: url = Completion.class_url("test_engine") assert url == "/engines/test_engine/completions" @pytest.mark.url def test_completions_url_composition_open_ai() -> None: url = Completion.class_url("test_engine", "open_ai") assert url == "/engines/test_engine/completions" @pytest.mark.url def test_completions_url_composition_invalid_type() -> None: with pytest.raises(Exception): url = Completion.class_url("test_engine", "invalid") @pytest.mark.url def test_completions_url_composition_instance_url_azure() -> None: completion = Completion( id="test_id", engine="test_engine", api_type="azure", api_version="2021-11-01-preview", ) url = completion.instance_url() assert ( url == "/apacai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview" ) @pytest.mark.url def test_completions_url_composition_instance_url_azure_ad() -> None: completion = Completion( id="test_id", engine="test_engine", api_type="azure_ad", api_version="2021-11-01-preview", ) url = completion.instance_url() assert ( url == "/apacai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview" ) @pytest.mark.url def test_completions_url_composition_instance_url_azure_no_version() -> None: completion = Completion( id="test_id", engine="test_engine", api_type="azure", api_version=None ) with pytest.raises(Exception): completion.instance_url() @pytest.mark.url def test_completions_url_composition_instance_url_default() -> None: completion = Completion(id="test_id", engine="test_engine") url = completion.instance_url() assert url == "/engines/test_engine/completions/test_id" @pytest.mark.url def test_completions_url_composition_instance_url_open_ai() -> None: completion = Completion( id="test_id", engine="test_engine", api_type="open_ai", api_version="2021-11-01-preview", ) url = completion.instance_url() assert url == "/engines/test_engine/completions/test_id" @pytest.mark.url def test_completions_url_composition_instance_url_invalid() -> None: completion = Completion(id="test_id", engine="test_engine", api_type="invalid") with pytest.raises(Exception): url = completion.instance_url() @pytest.mark.url def test_completions_url_composition_instance_url_timeout_azure() -> None: completion = Completion( id="test_id", engine="test_engine", api_type="azure", api_version="2021-11-01-preview", ) completion["timeout"] = 12 url = completion.instance_url() assert ( url == "/apacai/deployments/test_engine/completions/test_id?api-version=2021-11-01-preview&timeout=12" ) @pytest.mark.url def test_completions_url_composition_instance_url_timeout_apacai() -> None: completion = Completion(id="test_id", engine="test_engine", api_type="open_ai") completion["timeout"] = 12 url = completion.instance_url() assert url == "/engines/test_engine/completions/test_id?timeout=12" @pytest.mark.url def test_engine_search_url_composition_azure() -> None: engine = Engine(id="test_id", api_type="azure", api_version="2021-11-01-preview") assert engine.api_type == "azure" assert engine.typed_api_type == ApiType.AZURE url = engine.instance_url("test_operation") assert ( url == "/apacai/deployments/test_id/test_operation?api-version=2021-11-01-preview" ) @pytest.mark.url def test_engine_search_url_composition_azure_ad() -> None: engine = Engine(id="test_id", api_type="azure_ad", api_version="2021-11-01-preview") assert engine.api_type == "azure_ad" assert engine.typed_api_type == ApiType.AZURE_AD url = engine.instance_url("test_operation") assert ( url == "/apacai/deployments/test_id/test_operation?api-version=2021-11-01-preview" ) @pytest.mark.url def test_engine_search_url_composition_azure_no_version() -> None: engine = Engine(id="test_id", api_type="azure", api_version=None) assert engine.api_type == "azure" assert engine.typed_api_type == ApiType.AZURE with pytest.raises(Exception): engine.instance_url("test_operation") @pytest.mark.url def test_engine_search_url_composition_azure_no_operation() -> None: engine = Engine(id="test_id", api_type="azure", api_version="2021-11-01-preview") assert engine.api_type == "azure" assert engine.typed_api_type == ApiType.AZURE assert ( engine.instance_url() == "/apacai/engines/test_id?api-version=2021-11-01-preview" ) @pytest.mark.url def test_engine_search_url_composition_default() -> None: engine = Engine(id="test_id") assert engine.api_type == None assert engine.typed_api_type == ApiType.OPEN_AI url = engine.instance_url() assert url == "/engines/test_id" @pytest.mark.url def test_engine_search_url_composition_open_ai() -> None: engine = Engine(id="test_id", api_type="open_ai") assert engine.api_type == "open_ai" assert engine.typed_api_type == ApiType.OPEN_AI url = engine.instance_url() assert url == "/engines/test_id" @pytest.mark.url def test_engine_search_url_composition_invalid_type() -> None: engine = Engine(id="test_id", api_type="invalid") assert engine.api_type == "invalid" with pytest.raises(Exception): assert engine.typed_api_type == ApiType.OPEN_AI @pytest.mark.url def test_engine_search_url_composition_invalid_search() -> None: engine = Engine(id="test_id", api_type="invalid") assert engine.api_type == "invalid" with pytest.raises(Exception): engine.search()
@pytest.mark.skipif(not HAS_PANDAS, reason=PANDAS_INSTRUCTIONS) @pytest.mark.skipif(not HAS_NUMPY, reason=NUMPY_INSTRUCTIONS) def test_long_examples_validator() -> None: """ Ensures that long_examples_validator() handles previously applied recommendations, namely dropped duplicates, without resulting in a KeyError. """ # data short_prompt = "a prompt " long_prompt = short_prompt * 500 short_completion = "a completion " long_completion = short_completion * 500 # the order of these matters unprepared_training_data = [ {"prompt": long_prompt, "completion": long_completion}, # 1 of 2 duplicates {"prompt": short_prompt, "completion": short_completion}, {"prompt": long_prompt, "completion": long_completion}, # 2 of 2 duplicates ] with NamedTemporaryFile(suffix=".jsonl", mode="w") as training_data: print(training_data.name) for prompt_completion_row in unprepared_training_data: training_data.write(json.dumps(prompt_completion_row) + "\n") training_data.flush() prepared_data_cmd_output = subprocess.run( [f"apacai tools fine_tunes.prepare_data -f {training_data.name}"], stdout=subprocess.PIPE, text=True, input="y\ny\ny\ny\ny", # apply all recommendations, one at a time stderr=subprocess.PIPE, encoding="utf-8", shell=True, ) # validate data was prepared successfully assert prepared_data_cmd_output.stderr == "" # validate get_long_indexes() applied during optional_fn() call in long_examples_validator() assert "indices of the long examples has changed" in prepared_data_cmd_output.stdout return prepared_data_cmd_output.stdout
@pytest.mark.requestor def test_requestor_sets_request_id(mocker: MockerFixture) -> None: # Fake out 'requests' and confirm that the X-Request-Id header is set. got_headers = {} def fake_request(self, *args, **kwargs): nonlocal got_headers got_headers = kwargs["headers"] r = requests.Response() r.status_code = 200 r.headers["content-type"] = "application/json" r._content = json.dumps({}).encode("utf-8") return r mocker.patch("requests.sessions.Session.request", fake_request) fake_request_id = "1234" Model.retrieve("xxx", request_id=fake_request_id) # arbitrary API resource got_request_id = got_headers.get("X-Request-Id") assert got_request_id == fake_request_id @pytest.mark.requestor def test_requestor_open_ai_headers() -> None: api_requestor = APIRequestor(key="test_key", api_type="open_ai") headers = {"Test_Header": "Unit_Test_Header"} headers = api_requestor.request_headers( method="get", extra=headers, request_id="test_id" ) assert "Test_Header" in headers assert headers["Test_Header"] == "Unit_Test_Header" assert "Authorization" in headers assert headers["Authorization"] == "Bearer test_key" @pytest.mark.requestor def test_requestor_azure_headers() -> None: api_requestor = APIRequestor(key="test_key", api_type="azure") headers = {"Test_Header": "Unit_Test_Header"} headers = api_requestor.request_headers( method="get", extra=headers, request_id="test_id" ) assert "Test_Header" in headers assert headers["Test_Header"] == "Unit_Test_Header" assert "api-key" in headers assert headers["api-key"] == "test_key" @pytest.mark.requestor def test_requestor_azure_ad_headers() -> None: api_requestor = APIRequestor(key="test_key", api_type="azure_ad") headers = {"Test_Header": "Unit_Test_Header"} headers = api_requestor.request_headers( method="get", extra=headers, request_id="test_id" ) assert "Test_Header" in headers assert headers["Test_Header"] == "Unit_Test_Header" assert "Authorization" in headers assert headers["Authorization"] == "Bearer test_key" @pytest.mark.requestor def test_requestor_cycle_sessions(mocker: MockerFixture) -> None: # HACK: we need to purge the _thread_context to not interfere # with other tests from apacai.api_requestor import _thread_context delattr(_thread_context, "session") api_requestor = APIRequestor(key="test_key", api_type="azure_ad") mock_session = mocker.MagicMock() mocker.patch("apacai.api_requestor._make_session", lambda: mock_session) # We don't call `session.close()` if not enough time has elapsed api_requestor.request_raw("get", "http://example.com") mock_session.request.assert_called() api_requestor.request_raw("get", "http://example.com") mock_session.close.assert_not_called() mocker.patch("apacai.api_requestor.MAX_SESSION_LIFETIME_SECS", 0) # Due to 0 lifetime, the original session will be closed before the next call # and a new session will be created mock_session_2 = mocker.MagicMock() mocker.patch("apacai.api_requestor._make_session", lambda: mock_session_2) api_requestor.request_raw("get", "http://example.com") mock_session.close.assert_called() mock_session_2.request.assert_called() delattr(_thread_context, "session")
pytestmark = [pytest.mark.asyncio] # FILE TESTS async def test_file_upload(): result = await apacai.File.acreate( file=io.StringIO( json.dumps({"prompt": "test file data", "completion": "tada"}) ), purpose="fine-tune", ) assert result.purpose == "fine-tune" assert "id" in result result = await apacai.File.aretrieve(id=result.id) assert result.status == "uploaded" # COMPLETION TESTS async def test_completions(): result = await apacai.Completion.acreate( prompt="This was a test", n=5, engine="ada" ) assert len(result.choices) == 5 async def test_completions_multiple_prompts(): result = await apacai.Completion.acreate( prompt=["This was a test", "This was another test"], n=5, engine="ada" ) assert len(result.choices) == 10 async def test_completions_model(): result = await apacai.Completion.acreate(prompt="This was a test", n=5, model="ada") assert len(result.choices) == 5 assert result.model.startswith("ada") async def test_timeout_raises_error(): # A query that should take awhile to return with pytest.raises(error.Timeout): await apacai.Completion.acreate( prompt="test" * 1000, n=10, model="ada", max_tokens=100, request_timeout=0.01, ) async def test_timeout_does_not_error(): # A query that should be fast await apacai.Completion.acreate( prompt="test", model="ada", request_timeout=10, ) async def test_completions_stream_finishes_global_session(): async with ClientSession() as session: apacai.aiosession.set(session) # A query that should be fast parts = [] async for part in await apacai.Completion.acreate( prompt="test", model="ada", request_timeout=3, stream=True ): parts.append(part) assert len(parts) > 1 async def test_completions_stream_finishes_local_session(): # A query that should be fast parts = [] async for part in await apacai.Completion.acreate( prompt="test", model="ada", request_timeout=3, stream=True ): parts.append(part) assert len(parts) > 1
class ChatCompletion(EngineAPIResource): engine_required = False OBJECT_NAME = "chat.completions" @classmethod def create(cls, *args, **kwargs): """ Creates a new chat completion for the provided messages and parameters. See https://platform.apacai.com/docs/api-reference/chat/create for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) while True: try: return super().create(*args, **kwargs) except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e) @classmethod async def acreate(cls, *args, **kwargs): """ Creates a new chat completion for the provided messages and parameters. See https://platform.apacai.com/docs/api-reference/chat/create for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) while True: try: return await super().acreate(*args, **kwargs) except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e)
DeletableAPIResource, ListableAPIResource, CreateableAPIResource, ) class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource): OBJECT_NAME = "deployments" @classmethod def _check_create(cls, *args, **kwargs): typed_api_type, _ = cls._get_api_type_and_version( kwargs.get("api_type", None), None ) if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): raise APIError( "Deployment operations are only available for the Azure API type." ) if kwargs.get("model", None) is None: raise InvalidRequestError( "Must provide a 'model' parameter to create a Deployment.", param="model", ) scale_settings = kwargs.get("scale_settings", None) if scale_settings is None: raise InvalidRequestError( "Must provide a 'scale_settings' parameter to create a Deployment.", param="scale_settings", ) if "scale_type" not in scale_settings or ( scale_settings["scale_type"].lower() == "manual" and "capacity" not in scale_settings ): raise InvalidRequestError( "The 'scale_settings' parameter contains invalid or incomplete values.", param="scale_settings", ) @classmethod def create(cls, *args, **kwargs): """ Creates a new deployment for the provided prompt and parameters. """ cls._check_create(*args, **kwargs) return super().create(*args, **kwargs) @classmethod def acreate(cls, *args, **kwargs): """ Creates a new deployment for the provided prompt and parameters. """ cls._check_create(*args, **kwargs) return super().acreate(*args, **kwargs) @classmethod def _check_list(cls, *args, **kwargs): typed_api_type, _ = cls._get_api_type_and_version( kwargs.get("api_type", None), None ) if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): raise APIError( "Deployment operations are only available for the Azure API type." ) @classmethod def list(cls, *args, **kwargs): cls._check_list(*args, **kwargs) return super().list(*args, **kwargs) @classmethod def alist(cls, *args, **kwargs): cls._check_list(*args, **kwargs) return super().alist(*args, **kwargs) @classmethod def _check_delete(cls, *args, **kwargs): typed_api_type, _ = cls._get_api_type_and_version( kwargs.get("api_type", None), None ) if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): raise APIError( "Deployment operations are only available for the Azure API type." ) @classmethod def delete(cls, *args, **kwargs): cls._check_delete(*args, **kwargs) return super().delete(*args, **kwargs) @classmethod def adelete(cls, *args, **kwargs): cls._check_delete(*args, **kwargs) return super().adelete(*args, **kwargs) @classmethod def _check_retrieve(cls, *args, **kwargs): typed_api_type, _ = cls._get_api_type_and_version( kwargs.get("api_type", None), None ) if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD): raise APIError( "Deployment operations are only available for the Azure API type." ) @classmethod def retrieve(cls, *args, **kwargs): cls._check_retrieve(*args, **kwargs) return super().retrieve(*args, **kwargs) @classmethod def aretrieve(cls, *args, **kwargs): cls._check_retrieve(*args, **kwargs) return super().aretrieve(*args, **kwargs)
class ErrorObject(ApacAIObject): def refresh_from( self, values, api_key=None, api_version=None, api_type=None, organization=None, response_ms: Optional[int] = None, ): # Unlike most other API resources, the API will omit attributes in # error objects when they have a null value. We manually set default # values here to facilitate generic error handling. values = merge_dicts({"message": None, "type": None}, values) return super(ErrorObject, self).refresh_from( values=values, api_key=api_key, api_version=api_version, api_type=api_type, organization=organization, response_ms=response_ms, )
class Completion(EngineAPIResource): OBJECT_NAME = "completions" @classmethod def create(cls, *args, **kwargs): """ Creates a new completion for the provided prompt and parameters. See https://platform.apacai.com/docs/api-reference/completions/create for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) while True: try: return super().create(*args, **kwargs) except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e) @classmethod async def acreate(cls, *args, **kwargs): """ Creates a new completion for the provided prompt and parameters. See https://platform.apacai.com/docs/api-reference/completions/create for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) while True: try: return await super().acreate(*args, **kwargs) except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e)
CreateableAPIResource, ListableAPIResource, nested_resource_class_methods, ) @nested_resource_class_methods("event", operations=["list"]) class FineTune(ListableAPIResource, CreateableAPIResource, DeletableAPIResource): OBJECT_NAME = "fine-tunes" @classmethod def _prepare_cancel( cls, id, api_key=None, api_type=None, request_id=None, api_version=None, **params, ): base = cls.class_url() extn = quote_plus(id) typed_api_type, api_version = cls._get_api_type_and_version( api_type, api_version ) if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): url = "/%s%s/%s/cancel?api-version=%s" % ( cls.azure_api_prefix, base, extn, api_version, ) elif typed_api_type == ApiType.OPEN_AI: url = "%s/%s/cancel" % (base, extn) else: raise error.InvalidAPIType("Unsupported API type %s" % api_type) instance = cls(id, api_key, **params) return instance, url @classmethod def cancel( cls, id, api_key=None, api_type=None, request_id=None, api_version=None, **params, ): instance, url = cls._prepare_cancel( id, api_key, api_type, request_id, api_version, **params, ) return instance.request("post", url, request_id=request_id) @classmethod def acancel( cls, id, api_key=None, api_type=None, request_id=None, api_version=None, **params, ): instance, url = cls._prepare_cancel( id, api_key, api_type, request_id, api_version, **params, ) return instance.arequest("post", url, request_id=request_id) @classmethod def _prepare_stream_events( cls, id, api_key=None, api_base=None, api_type=None, request_id=None, api_version=None, organization=None, **params, ): base = cls.class_url() extn = quote_plus(id) requestor = api_requestor.APIRequestor( api_key, api_base=api_base, api_type=api_type, api_version=api_version, organization=organization, ) typed_api_type, api_version = cls._get_api_type_and_version( api_type, api_version ) if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD): url = "/%s%s/%s/events?stream=true&api-version=%s" % ( cls.azure_api_prefix, base, extn, api_version, ) elif typed_api_type == ApiType.OPEN_AI: url = "%s/%s/events?stream=true" % (base, extn) else: raise error.InvalidAPIType("Unsupported API type %s" % api_type) return requestor, url @classmethod def stream_events( cls, id, api_key=None, api_base=None, api_type=None, request_id=None, api_version=None, organization=None, **params, ): requestor, url = cls._prepare_stream_events( id, api_key, api_base, api_type, request_id, api_version, organization, **params, ) response, _, api_key = requestor.request( "get", url, params, stream=True, request_id=request_id ) assert not isinstance(response, ApacAIResponse) # must be an iterator return ( util.convert_to_apacai_object( line, api_key, api_version, organization, ) for line in response ) @classmethod async def astream_events( cls, id, api_key=None, api_base=None, api_type=None, request_id=None, api_version=None, organization=None, **params, ): requestor, url = cls._prepare_stream_events( id, api_key, api_base, api_type, request_id, api_version, organization, **params, ) response, _, api_key = await requestor.arequest( "get", url, params, stream=True, request_id=request_id ) assert not isinstance(response, ApacAIResponse) # must be an iterator return ( util.convert_to_apacai_object( line, api_key, api_version, organization, ) async for line in response )
class Embedding(EngineAPIResource): OBJECT_NAME = "embeddings" @classmethod def create(cls, *args, **kwargs): """ Creates a new embedding for the provided input and parameters. See https://platform.apacai.com/docs/api-reference/embeddings for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) user_provided_encoding_format = kwargs.get("encoding_format", None) # If encoding format was not explicitly specified, we opaquely use base64 for performance if not user_provided_encoding_format: kwargs["encoding_format"] = "base64" while True: try: response = super().create(*args, **kwargs) # If a user specifies base64, we'll just return the encoded string. # This is only for the default case. if not user_provided_encoding_format: for data in response.data: # If an engine isn't using this optimization, don't do anything if type(data["embedding"]) == str: assert_has_numpy() data["embedding"] = np.frombuffer( base64.b64decode(data["embedding"]), dtype="float32" ).tolist() return response except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e) @classmethod async def acreate(cls, *args, **kwargs): """ Creates a new embedding for the provided input and parameters. See https://platform.apacai.com/docs/api-reference/embeddings for a list of valid parameters. """ start = time.time() timeout = kwargs.pop("timeout", None) user_provided_encoding_format = kwargs.get("encoding_format", None) # If encoding format was not explicitly specified, we opaquely use base64 for performance if not user_provided_encoding_format: kwargs["encoding_format"] = "base64" while True: try: response = await super().acreate(*args, **kwargs) # If a user specifies base64, we'll just return the encoded string. # This is only for the default case. if not user_provided_encoding_format: for data in response.data: # If an engine isn't using this optimization, don't do anything if type(data["embedding"]) == str: data["embedding"] = np.frombuffer( base64.b64decode(data["embedding"]), dtype="float32" ).tolist() return response except TryAgain as e: if timeout is not None and time.time() > start + timeout: raise util.log_info("Waiting for model to warm up", error=e)