/usr/local/lib64/python3.6/site-packages/torch/include/caffe2/operators
NameSizeModeActions
abs_op.h7050644editdlrm
accumulate_op.h10730644editdlrm
accuracy_op.h6520644editdlrm
acos_op.h7110644editdlrm
activation_ops_cudnn.h41220644editdlrm
affine_channel_op.h34500644editdlrm
alias_with_name.h12340644editdlrm
apmeter_op.h10270644editdlrm
arg_ops.h23190644editdlrm
asin_op.h7110644editdlrm
assert_op.h13350644editdlrm
async_net_barrier_op.h9040644editdlrm
atan_op.h7110644editdlrm
batch_box_cox_op.h22870644editdlrm
batch_bucketize_op.h7200644editdlrm
batch_gather_ops.h52640644editdlrm
batch_matmul_op.h96020644editdlrm
batch_moments_op.h33640644editdlrm
batch_permutation_op.h9540644editdlrm
batch_sparse_to_dense_op.h61470644editdlrm
bbox_transform_op.h26680644editdlrm
bisect_percentile_op.h49210644editdlrm
boolean_mask_ops.h26650644editdlrm
boolean_unmask_ops.h3780644editdlrm
box_with_nms_limit_op.h49600644editdlrm
bucketize_op.h13610644editdlrm
byte_weight_dequant_op.h17220644editdlrm
cast_op.h13930644editdlrm
cbrt_op.h7230644editdlrm
cc_bmm_bg_op.h38940644editdlrm
ceil_op.h7820644editdlrm
channel_backprop_stats_op.h7370644editdlrm
channel_shuffle_op.h19020644editdlrm
channel_stats_op.h18070644editdlrm
clip_op.h16390644editdlrm
collect_and_distribute_fpn_rpn_proposals_op.h68750644editdlrm
concat_split_op.h118500644editdlrm
conditional_op.h4870644editdlrm
conv_op.h31250644editdlrm
conv_op_cache_cudnn.h19350644editdlrm
conv_op_impl.h287290644editdlrm
conv_op_shared.h6720644editdlrm
conv_pool_op_base.h321090644editdlrm
conv_transpose_op.h17270644editdlrm
conv_transpose_op_impl.h182640644editdlrm
conv_transpose_op_mobile.h14700644editdlrm
conv_transpose_op_mobile_impl.h195870644editdlrm
conv_transpose_unpool_op_base.h103030644editdlrm
copy_op.h12960644editdlrm
copy_rows_to_tensor_op.h25990644editdlrm
cosh_op.h7110644editdlrm
cosine_embedding_criterion_op.h11270644editdlrm
cos_op.h7050644editdlrm
counter_ops.h45960644editdlrm
create_scope_op.h52320644editdlrm
cross_entropy_op.h44200644editdlrm
ctc_beam_search_decoder_op.h11020644editdlrm
ctc_greedy_decoder_op.h8170644editdlrm
cube_op.h7230644editdlrm
dataset_ops.h55010644editdlrm
data_couple.h4640644editdlrm
deform_conv_op.h35430644editdlrm
deform_conv_op_impl.h131710644editdlrm
dense_vector_to_id_list_op.h17970644editdlrm
distance_op.h84190644editdlrm
do_op.h69810644editdlrm
dropout_op.h15160644editdlrm
elementwise_add_op.h20240644editdlrm
elementwise_div_op.h12240644editdlrm
elementwise_linear_op.h11700644editdlrm
elementwise_logical_ops.h50830644editdlrm
elementwise_mul_op.h12240644editdlrm
elementwise_ops.h191150644editdlrm
elementwise_ops_utils.h10080644editdlrm
elementwise_op_test.h92370644editdlrm
elementwise_sub_op.h20250644editdlrm
elu_op.h8750644editdlrm
enforce_finite_op.h23030644editdlrm
ensure_clipped_op.h16080644editdlrm
ensure_cpu_output_op.h14650644editdlrm
erf_op.h7510644editdlrm
expand_op.h38770644editdlrm
expand_squeeze_dims_op.h34510644editdlrm
exp_op.h4250644editdlrm
fc_inference.h7750644editdlrm
feature_maps_ops.h324370644editdlrm
feed_blob_op.h8020644editdlrm
filler_op.h184310644editdlrm
find_duplicate_elements_op.h15630644editdlrm
find_op.h20550644editdlrm
flatten_op.h15250644editdlrm
flexible_top_k.h9360644editdlrm
floor_op.h7880644editdlrm
free_op.h7770644editdlrm
fully_connected_op.h93510644editdlrm
fused_rowwise_8bit_conversion_ops.h66010644editdlrm
fused_rowwise_nbitfake_conversion_ops.h43750644editdlrm
fused_rowwise_nbit_conversion_ops.h87230644editdlrm
fused_rowwise_random_quantization_ops.h26070644editdlrm
gather_fused_8bit_rowwise_op.h21790644editdlrm
gather_op.h75050644editdlrm
gather_ranges_to_dense_op.h81880644editdlrm
gelu_op.h14520644editdlrm
generate_proposals_op.h62560644editdlrm
generate_proposals_op_util_boxes.h143090644editdlrm
generate_proposals_op_util_nms.h262140644editdlrm
generate_proposals_op_util_nms_gpu.h21280644editdlrm
given_tensor_byte_string_to_uint8_fill_op.h21500644editdlrm
given_tensor_fill_op.h30020644editdlrm
glu_op.h14580644editdlrm
group_norm_op.h89670644editdlrm
gru_unit_op.h66260644editdlrm
half_float_ops.h27320644editdlrm
hard_sigmoid_op.h9940644editdlrm
heatmap_max_keypoint_op.h9390644editdlrm
histogram_op.h24210644editdlrm
h_softmax_op.h49540644editdlrm
if_op.h17640644editdlrm
im2col_op.h89430644editdlrm
index_hash_ops.h22320644editdlrm
index_ops.h31550644editdlrm
inference_lstm_op.h98810644editdlrm
instance_norm_op.h74410644editdlrm
integral_image_op.h9230644editdlrm
is_empty_op.h5580644editdlrm
jsd_op.h7210644editdlrm
key_split_ops.h14000644editdlrm
layer_norm_op.h80980644editdlrm
leaky_relu_op.h11110644editdlrm
lengths_pad_op.h25740644editdlrm
lengths_reducer_fused_8bit_rowwise_ops.h55320644editdlrm
lengths_reducer_fused_nbit_rowwise_ops.h234650644editdlrm
lengths_reducer_ops.h233150644editdlrm
lengths_reducer_rowwise_8bit_ops.h61800644editdlrm
lengths_tile_op.h5820644editdlrm
lengths_top_k_op.h13580644editdlrm
length_split_op.h22590644editdlrm
listwise_l2r_op.h16770644editdlrm
load_save_op.h140910644editdlrm
load_save_op_util.h16420644editdlrm
locally_connected_op.h38720644editdlrm
locally_connected_op_impl.h264950644editdlrm
locally_connected_op_util.h13320644editdlrm
local_response_normalization_op.h28040644editdlrm
log1p_op.h7170644editdlrm
logit_op.h11290644editdlrm
log_op.h4310644editdlrm
loss_op.h10580644editdlrm
lpnorm_op.h12790644editdlrm
lstm_unit_op.h67330644editdlrm
lstm_utils.h94240644editdlrm
map_ops.h80110644editdlrm
margin_ranking_criterion_op.h11130644editdlrm
matmul_op.h28430644editdlrm
max_pool_with_index_gpu.h11550644editdlrm
mean_op.h32520644editdlrm
merge_id_lists_op.h25700644editdlrm
minmax_ops.h38290644editdlrm
mish_op.h7940644editdlrm
mod_op.h9840644editdlrm
moments_op.h40510644editdlrm
multi_class_accuracy_op.h5390644editdlrm
negate_gradient_op.h5660644editdlrm
negative_op.h4510644editdlrm
ngram_ops.h26440644editdlrm
normalize_l1_op.h10750644editdlrm
normalize_op.h30130644editdlrm
no_default_engine_op.h10630644editdlrm
numpy_tile_op.h36430644editdlrm
one_hot_ops.h25620644editdlrm
onnx_while_op.h106550644editdlrm
operator_fallback_gpu.h41550644editdlrm
op_utils_cudnn.h21120644editdlrm
order_switch_ops.h21490644editdlrm
pack_rnn_sequence_op.h30740644editdlrm
pack_segments.h27290644editdlrm
pad_op.h29020644editdlrm
partition_ops.h99580644editdlrm
percentile_op.h10090644editdlrm
perplexity_op.h4470644editdlrm
piecewise_linear_transform_op.h82810644editdlrm
pool_op.h85250644editdlrm
pool_op_util.h11050644editdlrm
pow_op.h46770644editdlrm
prefetch_op.h46610644editdlrm
prelu_op.h10670644editdlrm
prepend_dim_op.h27600644editdlrm
quantile_op.h41200644editdlrm
quant_decode_op.h53700644editdlrm
rank_loss_op.h8200644editdlrm
reciprocal_op.h7210644editdlrm
reducer_functors.h245560644editdlrm
reduce_front_back_max_ops.h43990644editdlrm
reduce_front_back_sum_mean_ops.h53370644editdlrm
reduce_ops.h99620644editdlrm
reduction_ops.h59440644editdlrm
relu_n_op.h9900644editdlrm
relu_op.h6240644editdlrm
remove_data_blocks_op.h26510644editdlrm
replace_nan_op.h11700644editdlrm
reshape_op.h57230644editdlrm
resize_3d_op.h26770644editdlrm
resize_op.h23070644editdlrm
reverse_packed_segs_op.h27720644editdlrm
rmac_regions_op.h7080644editdlrm
rms_norm_op.h29680644editdlrm
roi_align_gradient_op.h14860644editdlrm
roi_align_op.h28570644editdlrm
roi_align_rotated_gradient_op.h13690644editdlrm
roi_align_rotated_op.h16360644editdlrm
roi_pool_op.h25030644editdlrm
rowmul_op.h19470644editdlrm
rsqrt_op.h7290644editdlrm
scale_blobs_op.h14580644editdlrm
scale_op.h10190644editdlrm
segment_reduction_op.h710220644editdlrm
self_binning_histogram_op.h62580644editdlrm
selu_op.h15450644editdlrm
sequence_ops.h82640644editdlrm
shape_op.h16380644editdlrm
sigmoid_op.h6390644editdlrm
sinh_op.h7110644editdlrm
sinusoid_position_encoding_op.h28340644editdlrm
sin_op.h7050644editdlrm
slice_op.h100710644editdlrm
softmax_op.h11740644editdlrm
softmax_utils.h4470644editdlrm
softmax_with_loss_op.h28830644editdlrm
softplus_op.h7810644editdlrm
softsign_op.h6750644editdlrm
space_batch_op.h68480644editdlrm
sparse_dropout_with_replacement_op.h11220644editdlrm
sparse_itemwise_dropout_with_replacement_op.h11630644editdlrm
sparse_lp_regularizer_op.h11300644editdlrm
sparse_normalize_op.h8340644editdlrm
sparse_to_dense_mask_op.h100510644editdlrm
sparse_to_dense_op.h39770644editdlrm
spatial_batch_norm_op.h151750644editdlrm
spatial_softmax_with_loss_op.h21820644editdlrm
sqrt_op.h4480644editdlrm
sqr_op.h4310644editdlrm
square_root_divide_op.h18570644editdlrm
stats_put_ops.h28130644editdlrm
stop_gradient.h5480644editdlrm
string_ops.h20670644editdlrm
stump_func_op.h21120644editdlrm
summarize_op.h18750644editdlrm
swish_op.h7720644editdlrm
tanh_op.h7230644editdlrm
tan_op.h7050644editdlrm
tensor_protos_db_input.h36330644editdlrm
text_file_reader_utils.h29000644editdlrm
thresholded_relu_op.h11370644editdlrm
tile_op.h87410644editdlrm
top_k.h10610644editdlrm
transpose_op.h20820644editdlrm
tt_linear_op.h65010644editdlrm
unique_ops.h16660644editdlrm
unsafe_coalesce.h24810644editdlrm
upsample_op.h22460644editdlrm
utility_ops.h499940644editdlrm
variable_length_sequence_padding.h13780644editdlrm
weighted_multi_sampling_op.h6020644editdlrm
weighted_sample_op.h7390644editdlrm
while_op.h19610644editdlrm
zero_gradient_op.h3470644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/include/caffe2/operators/reducer_functors.h (24556B)
#ifndef CAFFE2_OPERATORS_RECUDER_FUNCTORS_H_ #define CAFFE2_OPERATORS_RECUDER_FUNCTORS_H_ #include #include "caffe2/core/context.h" #include "caffe2/core/tensor.h" #include "caffe2/utils/eigen_utils.h" #include "caffe2/utils/math.h" #include "caffe2/utils/proto_utils.h" namespace caffe2 { //////////////////////////////////////////////////////////////////////////////// // Range reducers: can leverage that input segment is continuous and provide // special implementation //////////////////////////////////////////////////////////////////////////////// // Put forward and backward in the same template? template class SumRangeReducer; template class SumRangeReducerGradient; template class SumRangeReducer { public: void operator()( const int64_t block_size, const int64_t blocks, const T* in, T* out, CPUContext* /*context*/) { // do we need to go through wrapper in math.h? EigenVectorMap out_vec(out, block_size); out_vec = ConstEigenMatrixMap(in, block_size, blocks).rowwise().sum(); } }; template class SumRangeReducerGradient { public: void operator()( const int64_t block_size, const int64_t blocks, const T* segment_grad, T* data_grad, const T* /*data_in*/, // unused const T* /*data_out*/, // unused Context* context) { // do we have some op that does it smartly with minimum number of memcpy? for (int64_t i = 0; i < blocks; ++i) { context->template CopySameDevice( block_size, segment_grad, data_grad + block_size * i); } } }; struct SumRangeReducerDef { template using Reducer = SumRangeReducer; template using ReducerGradient = SumRangeReducerGradient; static constexpr const char* name = "Sum"; static constexpr const char* doc = "Summation is done element-wise across slices of the input tensor and " "doesn't change the shape of the individual blocks."; }; // Put forward and backward in the same template? template class LogSumExpRangeReducer; template class LogSumExpRangeReducerGradient; template class LogSumExpRangeReducer { public: void operator()( const int64_t block_size, const int64_t blocks, const T* in, T* out, CPUContext* /*context*/) { for (int j = 0; j < block_size; ++j) { T max_value = std::numeric_limits::lowest(); for (int i = 0; i < blocks; ++i) { max_value = std::max(max_value, in[i * block_size + j]); } T scaled_exp_sum = 0; for (int i = 0; i < blocks; ++i) { scaled_exp_sum += std::exp(in[i * block_size + j] - max_value); } *(out++) = std::log(scaled_exp_sum) + max_value; } } T r{1}; }; template class LogSumExpRangeReducerGradient { public: void operator()( const int64_t block_size, const int64_t blocks, const T* segment_grad, // GO T* data_grad, // GI const T* data_in, // I const T* data_out, // O Context* /*context*/) { for (int j = 0; j < block_size; ++j) { const T out_grad = *(segment_grad++); const T offset = *(data_out++); for (int i = 0; i < blocks; ++i) { auto idx = i * block_size + j; data_grad[idx] = out_grad * std::exp(data_in[idx] - offset); } } } }; struct LogSumExpRangeReducerDef { template using Reducer = LogSumExpRangeReducer; template using ReducerGradient = LogSumExpRangeReducerGradient; static constexpr const char* name = "LogSumExp"; static constexpr const char* doc = "LogSumExp computes the element-wise log of the sum of exponentials of " "input slices. Operation doesn't change the shape of individual blocks."; }; template class LogMeanExpRangeReducer; template class LogMeanExpRangeReducerGradient; template class LogMeanExpRangeReducer { public: void operator()( const int64_t block_size, const int64_t blocks, const T* in, T* out, CPUContext* /*context*/) { for (int j = 0; j < block_size; ++j) { T max_value = std::numeric_limits::lowest(); for (int i = 0; i < blocks; ++i) { max_value = std::max(max_value, in[i * block_size + j]); } T scaled_exp_sum = 0; for (int i = 0; i < blocks; ++i) { scaled_exp_sum += std::exp(in[i * block_size + j] - max_value); } scaled_exp_sum /= blocks; *(out++) = std::log(scaled_exp_sum) + max_value; } } }; template class LogMeanExpRangeReducerGradient { public: void operator()( const int64_t block_size, const int64_t blocks, const T* segment_grad, // GO T* data_grad, // GI const T* data_in, // I const T* data_out, // O Context* /*context*/) { for (int j = 0; j < block_size; ++j) { const T out_grad = *(segment_grad++); const T offset = *(data_out++); for (int i = 0; i < blocks; ++i) { auto idx = i * block_size + j; data_grad[idx] = out_grad * std::exp(data_in[idx] - offset) / blocks; } } } }; struct LogMeanExpRangeReducerDef { template using Reducer = LogMeanExpRangeReducer; template using ReducerGradient = LogMeanExpRangeReducerGradient; static constexpr const char* name = "LogMeanExp"; static constexpr const char* doc = "LogMeanExp computes the element-wise log of the mean of exponentials of " "input slices. Operation doesn't change the shape of individual blocks."; }; template class MeanRangeReducer; template class MeanRangeReducerGradient; template class MeanRangeReducer { public: void operator()( const int64_t block_size, const int64_t blocks, const T* in, T* out, CPUContext* /*context*/) { for (int j = 0; j < block_size; ++j) { T avg_value = 0; for (int i = 0; i < blocks; ++i) { avg_value += in[i * block_size + j] / blocks; } *(out++) = avg_value; } } }; template class MeanRangeReducerGradient { public: void operator()( const int64_t block_size, const int64_t blocks, const T* segment_grad, // GO T* data_grad, // GI const T* /*data_in*/, // I const T* /*data_out*/, // O Context* /*context*/) { const auto in_grad = 1.0 / blocks; for (int j = 0; j < block_size; ++j) { const T out_grad = *(segment_grad++); for (int i = 0; i < blocks; ++i) { auto idx = i * block_size + j; data_grad[idx] = out_grad * in_grad; } } } }; struct MeanRangeReducerDef { template using Reducer = MeanRangeReducer; template using ReducerGradient = MeanRangeReducerGradient; static constexpr const char* name = "Mean"; static constexpr const char* doc = "Mean computation is done element-wise, so that each element of the " "output slice corresponds to the average value of the respective " "elements in the input slices. Operation doesn't change the shape of " "individual blocks."; }; template class MaxRangeReducer; template class MaxRangeReducerGradient; template class MaxRangeReducer { public: void operator()( const int64_t block_size, const int64_t blocks, const T* in, T* out, CPUContext* /*context*/) { for (int j = 0; j < block_size; ++j) { T max_value = std::numeric_limits::lowest(); for (int i = 0; i < blocks; ++i) { max_value = std::max(max_value, in[i * block_size + j]); } *(out++) = max_value; } } }; template class MaxRangeReducerGradient { public: void operator()( const int64_t block_size, const int64_t blocks, const T* segment_grad, // GO T* data_grad, // GI const T* data_in, // I const T* data_out, // O Context* /*context*/) { std::memset( static_cast(data_grad), 0, blocks * block_size * sizeof(T)); for (int j = 0; j < block_size; ++j) { const T out_grad = *(segment_grad++); const T out = data_out[j]; for (int i = 0; i < blocks; ++i) { auto idx = i * block_size + j; if (out == data_in[idx]) { data_grad[idx] = out_grad; } } } } }; struct MaxRangeReducerDef { template using Reducer = MaxRangeReducer; template using ReducerGradient = MaxRangeReducerGradient; static constexpr const char* name = "Max"; static constexpr const char* doc = "Max computation is done element-wise, so that each element of the " "output slice corresponds to the max value of the respective " "elements in the input slices. Operation doesn't change the shape of " "individual blocks. This implementation imitates torch nn.Max operator. " "If the maximum value occurs more than once, the operator will return " "the first occurrence of value. When computing the gradient using the " "backward propagation, the gradient input corresponding to the first " "occurrence of the maximum value will be used."; }; //////////////////////////////////////////////////////////////////////////////// // Incremental reducers: consume elements one by one //////////////////////////////////////////////////////////////////////////////// // Base implementation, everything can be overwritten class BaseReducer { public: static constexpr int kInputCount = 1; struct Meta { int64_t block_size; vector block_shape; bool first_dim; explicit Meta(bool first = true) : first_dim(first) {} void computeMeta(at::IntArrayRef dims, size_t skip_dims) { first_dim ? block_shape.assign(dims.begin() + skip_dims, dims.end()) : block_shape.assign(dims.begin(), dims.end() - skip_dims); block_size = first_dim ? size_from_dim_(skip_dims, dims) : size_from_dim_(dims.size() - skip_dims, dims); } void observeInput(int input, const Tensor& value, int skip_dims) { DCHECK_EQ(0, input); auto dims = value.sizes(); computeMeta(dims, skip_dims); } void appendOutputShape(vector* output_shape) { output_shape->insert( output_shape->end(), block_shape.begin(), block_shape.end()); } vector getOutputShape(const TensorShape& in, int skip_dims) { vector dims(in.dims().begin(), in.dims().end()); computeMeta(dims, skip_dims); return block_shape; } }; template void finish(const Meta& /*meta*/, CPUContext* /*context*/) {} }; class BaseReducerGradient { public: // which of the original inputs are required for gradient computation static constexpr std::array originalInputs() { return std::array(); } static constexpr bool computeLength() { return false; } static int numAuxInputsWithGrads(const OperatorDef& /*def*/) { return 0; } static bool requiresDataInput(const OperatorDef& /*def*/) { return false; } // True if the backward op requires the output of the forward op. static bool requiresForwardOutput() { return false; } struct Meta { int64_t block_size; vector block_shape; bool first_dim; Meta(const Tensor& out_grad, int skip_dims, bool first_dim = true) : first_dim(first_dim) { auto dims = out_grad.sizes(); first_dim ? block_shape.assign(dims.begin() + skip_dims, dims.end()) : block_shape.assign(dims.begin(), dims.end() - skip_dims); block_size = first_dim ? out_grad.size_from_dim(skip_dims) : out_grad.size_from_dim(out_grad.dim() - skip_dims); } void observeOriginalInput( int /*original_input*/, const Tensor& /*value*/, Tensor* /*input_grad*/, // optional grad to populate int /*skip_dims*/) {} void appendGradShape(vector* output_shape) { output_shape->insert( output_shape->end(), block_shape.begin(), block_shape.end()); } }; }; // Put forward and backward in the same template? template class SumReducer; template class SumReducerGradient; template class SumReducer : public BaseReducer { public: using FixedDispatch = FixedValues<1>; SumReducer(const Meta& meta, T* out, CPUContext* /*context*/) : current_size_(0), out_(out) { // add a wrapper in Context for it if (meta.first_dim) { memset(out, 0, sizeof(T) * meta.block_size); } } template void process( const Meta& meta, const T* in, int64_t /*offset*/, CPUContext* context) { if (meta.first_dim) { math::AxpyFixedSize( meta.block_size, 1, in, out_, context); } else { math::Sum( meta.block_size, in, out_ + current_size_++, context); } } private: int current_size_; T* out_; }; template class SumReducerGradient : public BaseReducerGradient { public: using FixedDispatch = FixedValues<1>; SumReducerGradient( const Meta& /*meta*/, const T* s_grad, CPUContext* /*context*/) : s_grad_(s_grad) {} template void fillGrad( const Meta& meta, T* data_grad, int64_t offset, Context* context, const int length) { if (FixedSize == 1) { // static if *data_grad = *s_grad_; } else if (meta.first_dim) { context->template CopySameDevice(meta.block_size, s_grad_, data_grad); } else { math::Set(length, s_grad_[offset], data_grad, context); } } private: const T* s_grad_; }; struct SumReducerDef { template using Reducer = SumReducer; template using ReducerGradient = SumReducerGradient; static constexpr const char* name = "Sum"; static constexpr const char* doc = "Summation is done element-wise across slices of the input tensor and " "doesn't change the shape of the individual blocks."; static void PopulateSchema(OpSchema& /*schema*/) {} }; // Put forward and backward in the same template? template class WeightedSumReducer; template class WeightedSumReducerGradient; template class WeightedSumReducer : public BaseReducer { public: static constexpr int kInputCount = 2; using FixedDispatch = FixedValues<1>; struct Meta : BaseReducer::Meta { const T* scalars; bool first_dim; explicit Meta(bool first = true) : first_dim(first) {} void observeInput(int input, const Tensor& value, int skip_dims) { if (input == 1) { CAFFE_ENFORCE_EQ( skip_dims, value.dim(), "SCALARS mustn't have extra dimensions"); scalars = value.data(); return; } BaseReducer::Meta::observeInput(input, value, skip_dims); } }; WeightedSumReducer(const Meta& meta, T* out, CPUContext* /*context*/) : out_(out) { // do we have a wrapper for it? memset(out, 0, sizeof(T) * meta.block_size); } template void process(const Meta& meta, const T* in, int64_t offset, CPUContext* context) { CAFFE_ENFORCE( meta.first_dim, "WeightedSumReducer implemented only for " "front dimensions reduction"); math::AxpyFixedSize( meta.block_size, meta.scalars[offset], in, out_, context); } private: T* out_; }; template class WeightedSumReducerGradient : public BaseReducerGradient { public: // which of the original inputs are required for gradient computation static constexpr std::array originalInputs() { return {{1}}; } static int numAuxInputsWithGrads(const OperatorDef& def) { return GetFlagArgument(def, "grad_on_weights"); } static bool requiresDataInput(const OperatorDef& def) { return numAuxInputsWithGrads(def) > 0; } using FixedDispatch = FixedValues<1>; struct Meta : public BaseReducerGradient::Meta { const T* scalars; T* scalars_grad; using BaseReducerGradient::Meta::Meta; void observeOriginalInput( int original_input, const Tensor& value, Tensor* input_grad, // optional grad to populate int /*skip_dims*/) { CAFFE_ENFORCE_EQ(1, original_input); scalars = value.data(); if (input_grad) { input_grad->ResizeLike(value); scalars_grad = input_grad->template mutable_data(); } } }; WeightedSumReducerGradient( const Meta& /*meta*/, const T* s_grad, CPUContext* /*context*/) : s_grad_(s_grad) {} template void fillGrad( const Meta& meta, T* data_grad, int64_t offset, Context* context, const int /*length*/) { math::ScaleFixedSize( meta.block_size, meta.scalars[offset], s_grad_, data_grad, context); } // Special version which is called with the main input too, used only if // additional input grad is requested template void fillGradWithMainInput( const Meta& meta, const T* data, T* data_grad, int64_t offset, Context* context, const int /*length*/) { math::ScaleFixedSize( meta.block_size, meta.scalars[offset], s_grad_, data_grad, context); math::Dot( meta.block_size, s_grad_, data, meta.scalars_grad + offset, context); } private: const T* s_grad_; }; struct WeightedSumReducerDef { template using Reducer = WeightedSumReducer; template using ReducerGradient = WeightedSumReducerGradient; static constexpr const char* name = "WeightedSum"; static constexpr const char* doc = "Input slices are first scaled by SCALARS and then summed element-wise. " "It doesn't change the shape of the individual blocks."; static void PopulateSchema(OpSchema& schema) { schema.Input(0, "DATA", "Input tensor for the summation"); schema.Input( 1, "SCALARS", "Scalar multipliers for the input slices. Must be a vector with the " "length matching the number of slices"); schema.Arg( "grad_on_weights", "Produce also gradient for `weights`. For now it's only supported in " "`Lengths`-based operators"); } }; template class MeanReducer; template class MeanReducerGradient; template class MeanReducer : public BaseReducer { public: using FixedDispatch = FixedValues<1>; MeanReducer(const Meta& meta, T* out, CPUContext* /*context*/) : out_(out), current_size_(0) { if (meta.first_dim) { memset(out, 0, sizeof(T) * meta.block_size); } } template void process( const Meta& meta, const T* in, int64_t /*offset*/, CPUContext* context) { if (meta.first_dim) { math::AxpyFixedSize( meta.block_size, 1, in, out_, context); } else { math::Sum( meta.block_size, in, out_ + current_size_, context); } current_size_++; } template void finish(const Meta& meta, CPUContext* context) { if (meta.first_dim) { if (current_size_ > 0) { math::ScaleFixedSize( meta.block_size, 1.0 / current_size_, out_, out_, context); } } else { math::ScaleFixedSize( current_size_, 1.0 / meta.block_size, out_, out_, context); } } private: T* out_; int current_size_; }; template class MeanReducerGradient : public BaseReducerGradient { public: static constexpr bool computeLength() { return true; } using FixedDispatch = FixedValues<1>; MeanReducerGradient( const Meta& /*meta*/, const T* s_grad, CPUContext* /*context*/) : s_grad_(s_grad) {} template void fillGrad( const Meta& meta, T* data_grad, int64_t offset, Context* context, const int length) { CAFFE_ENFORCE_GT(length, 0, "Segment length must be > 0"); if (meta.first_dim) { math::ScaleFixedSize( meta.block_size, 1.0 / length, s_grad_, data_grad, context); } else { math::Set( length, s_grad_[offset] * 1.0f / length, data_grad, context); } } private: const T* s_grad_; }; struct MeanReducerDef { template using Reducer = MeanReducer; template using ReducerGradient = MeanReducerGradient; static constexpr const char* name = "Mean"; static constexpr const char* doc = "Mean computes the element-wise mean of the input slices. " "Operation doesn't change the shape of the individual blocks."; static void PopulateSchema(OpSchema& /*schema*/) {} }; template class MaxReducer; template class MaxReducerGradient; template class MaxReducer : public BaseReducer { public: using FixedDispatch = FixedValues<1>; MaxReducer(const Meta& meta, T* out, CPUContext* /*context*/) : out_(out), current_size_(0) { // add a wrapper in Context for it memset(out, 0, sizeof(T) * meta.block_size); } template void process( const Meta& meta, const T* in, int64_t /*offset*/, CPUContext* context) { CAFFE_ENFORCE( meta.first_dim, "MaxReducer implemented only for front dimensions reduction"); if (current_size_ > 0) { EigenVectorMap output_vec(out_, meta.block_size); output_vec = output_vec.cwiseMax(ConstEigenVectorMap(in, meta.block_size)); } else { memcpy(out_, in, sizeof(T) * meta.block_size); } ++current_size_; } private: T* out_; int current_size_; }; template class MaxReducerGradient : public BaseReducerGradient { public: static bool requiresDataInput(const OperatorDef& /*def*/) { return true; } static bool requiresForwardOutput() { return true; } using FixedDispatch = FixedValues<1>; MaxReducerGradient( const Meta& /*meta*/, const T* s_grad, CPUContext* /*context*/) : s_grad_(s_grad) {} template void fillGradWithMainInputAndForwardOutput( const Meta& meta, const T* data, T* data_grad, const T* forward_output, int64_t /*offset*/, Context* /*context*/, const int /*length*/) { for (int64_t i = 0; i < meta.block_size; ++i) { data_grad[i] = data[i] == forward_output[i] ? s_grad_[i] : 0; } } private: const T* s_grad_; }; struct MaxReducerDef { template using Reducer = MaxReducer; template using ReducerGradient = MaxReducerGradient; static constexpr const char* name = "Max"; static constexpr const char* doc = "Max computes the element-wise max of the input slices. " "Operation doesn't change the shape of the individual blocks."; static void PopulateSchema(OpSchema& /*schema*/) {} }; } // namespace caffe2 #endif // CAFFE2_OPERATORS_RECUDER_FUNCTORS_H_