/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/lengths_reducer_ops.h (23315B)
#pragma once #include "caffe2/core/context.h" #include "caffe2/core/operator.h" #include "caffe2/perfkernels/embedding_lookup.h" #ifdef USE_FBGEMM #include "fbgemm/Fbgemm.h" #endif #include #include namespace caffe2 { // A templated class that implements SparseLengths[Sum,WeightedSum,Mean]. template < typename T, // output type class InputTypes, // supported input types, such as TensorTypes bool USE_WEIGHT = false, // Whether it is SparseLengthsWeightedSum bool USE_MEAN = false, // Whether this is SparseLengthsMean bool USE_POSITIONAL_WEIGHT = false // USE_WEIGHT = true and USE_POSITIONAL_WEIGHT = true // -> SparseLengthsPositionalWeightedSum > class CPUSparseLengthsReductionOp : public Operator { public: USE_OPERATOR_FUNCTIONS(CPUContext); template explicit CPUSparseLengthsReductionOp(Args&&... args) : Operator(std::forward(args)...) { static_assert( !(USE_WEIGHT & USE_MEAN), "Cannot both specify weight and mean."); } ~CPUSparseLengthsReductionOp() {} // Currently, we support float and at::Half inputs for input data type, and // int32_t and int64_t for the index type. bool RunOnDevice() override { return DispatchHelper::call(this, Input(DATA)); } template bool DoRunWithType() { return DispatchHelper, InputType>::call( this, Input(INDICES)); } template bool DoRunWithType2() { auto& dataInput = Input(DATA); auto& indicesInput = Input(INDICES); auto& lengthsInput = Input(LENGTHS); const int64_t M = lengthsInput.size(0); const int64_t indices_size = indicesInput.numel(); auto shape = dataInput.sizes().vec(); shape[0] = M; auto* output = Output(0, shape, at::dtype()); T* out_data = output->template mutable_data(); if (indices_size == 0) { if (M > 0) { memset(out_data, 0, output->numel() * sizeof(T)); } return true; } CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t N = dataInput.size(0); const int D = dataInput.size_from_dim(1); const InputType* in_data = dataInput.template data(); const IndexType* indices = indicesInput.template data(); const int* lengths = lengthsInput.template data(); const T* in_weight = nullptr; if (USE_WEIGHT) { // static if auto& weightInput = Input(WEIGHT); CAFFE_ENFORCE_EQ(1, weightInput.dim(), "WEIGHT must be a vector"); if (!USE_POSITIONAL_WEIGHT) { CAFFE_ENFORCE_EQ( weightInput.numel(), indices_size, "Weight should have the same length as indices."); } in_weight = weightInput.template data(); } #ifdef USE_FBGEMM // If this is the first call or block size has changed (should never // happen actually), generate a kernel. if (D != last_block_size) { last_block_size = D; if (std::is_same::value) { if (std::is_same::value) { kernel_fp32_i32_ = fbgemm::GenerateEmbeddingSpMDM( D, USE_WEIGHT, USE_MEAN, /*prefetch distance*/ 16, USE_POSITIONAL_WEIGHT, /*use_offsets*/ false); } else { CAFFE_ENFORCE((std::is_same::value)); kernel_fp32_i64_ = fbgemm::GenerateEmbeddingSpMDM( D, USE_WEIGHT, USE_MEAN, /*prefetch distance*/ 16, USE_POSITIONAL_WEIGHT, /*use_offsets*/ false); } } else { CAFFE_ENFORCE((std::is_same::value)); if (std::is_same::value) { kernel_fp16_i32_ = fbgemm::GenerateEmbeddingSpMDM( D, USE_WEIGHT, USE_MEAN, /*prefetch distance*/ 16, USE_POSITIONAL_WEIGHT, /*use_offsets*/ false); } else { CAFFE_ENFORCE((std::is_same::value)); kernel_fp16_i64_ = fbgemm::GenerateEmbeddingSpMDM( D, USE_WEIGHT, USE_MEAN, /*prefetch distance*/ 16, USE_POSITIONAL_WEIGHT, /*use_offsets*/ false); } } } bool success; if (std::is_same::value) { if (std::is_same::value) { success = kernel_fp32_i32_( M, indices_size, N, reinterpret_cast(in_data), indicesInput.template data(), lengths, in_weight, out_data); } else { success = kernel_fp32_i64_( M, indices_size, N, reinterpret_cast(in_data), indicesInput.template data(), lengths, in_weight, out_data); } } else { if (std::is_same::value) { success = kernel_fp16_i32_( M, indices_size, N, reinterpret_cast(in_data), indicesInput.template data(), lengths, in_weight, out_data); } else { success = kernel_fp16_i64_( M, indices_size, N, reinterpret_cast(in_data), indicesInput.template data(), lengths, in_weight, out_data); } } if (success) { return true; } int64_t current = 0; for (int m = 0; m < M; ++m) { for (int i = 0; i < lengths[m]; ++i) { CAFFE_ENFORCE_LT( current, indices_size, "Your input seems to be incorrect: the sum of lengths values " "should be the size of the indices tensor, but it appears not."); IndexType idx = indices[current]; CAFFE_ENFORCE( 0 <= idx && idx < N, "Index ", current, " is out of bounds: ", idx, ", range 0 to ", N, ", actual batch length is ", M); ++current; } } CAFFE_ENFORCE_EQ( current, indices_size, "Your input seems to be incorrect: the sum of lengths values should be " "the size of the indices tensor, but it appears not."); return false; #endif // delegate work to perfkernel that branches based on architecture EmbeddingLookup( D, M, indices_size, N, in_data, indices, lengths, in_weight, nullptr, // scale_bias field is only used in SparseLengths8BitsRowwiseOp USE_MEAN, out_data); return true; } enum { DATA = 0, // Data input. WEIGHT = 1, // Weight input used in SparseLengthsWeightedSum INDICES = 1 + USE_WEIGHT, // 1 in SparseLengths[Sum,Mean] and // 2 in SparseLengthsWeightedSum LENGTHS = 2 + USE_WEIGHT, // 2 in SparseLengths[Sum, Mean], // 3 in SparseLengthsWeightedSum }; #ifdef USE_FBGEMM private: std::int64_t last_block_size{-1}; fbgemm::EmbeddingSpMDMKernelSignature::Type kernel_fp32_i32_; fbgemm::EmbeddingSpMDMKernelSignature::Type kernel_fp32_i64_; fbgemm::EmbeddingSpMDMKernelSignature::Type kernel_fp16_i32_; fbgemm::EmbeddingSpMDMKernelSignature::Type kernel_fp16_i64_; #endif }; template class TTSparseLengthsSumOp final : public Operator { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template explicit TTSparseLengthsSumOp(Args&&... args) : Operator(std::forward(args)...), factor_i(this->template GetRepeatedArgument( "factor_i", vector{1, 1, 1})), factor_j(this->template GetRepeatedArgument( "factor_j", vector{1, 1, 1})), ranks(this->template GetRepeatedArgument( "ranks", vector{1, 1, 1, 1})), emb_size(this->template GetSingleArgument("emb_size", 64)) { // cumprod of i, used for index slice l_cumprod.push_back(1); for (size_t i = 1; i < factor_i.size(); ++i) { l_cumprod.push_back(l_cumprod[i - 1] * factor_i[i - 1]); } } ~TTSparseLengthsSumOp() {} void Ind2Sub(int64_t* out_factor_index, const int64_t* indices, int len) { // TODO: vectorization auto N = factor_i.size(); for (int j = 0; j < len; j++) { auto idx = indices[j]; for (int i = N; i > 0; i--) { out_factor_index[j * N + i - 1] = idx / l_cumprod[i - 1]; idx = idx % l_cumprod[i - 1]; } } } bool GetSlice( std::vector>& tgt_slice, const T* core, const vector& ind_slice, int bs, int idx) { // implement the functinality index_select(core, 1, ind_slice) auto num_of_elements = ranks[idx] * factor_j[idx] * ranks[idx + 1]; for (int i = 0; i < bs; i++) { memcpy( tgt_slice[i].data(), core + ind_slice[i] * num_of_elements, num_of_elements * sizeof(T)); } return true; } // ind: it stores the index to each tensor core // bs: the number of indices // GatherAllRows uses two steps to calculate the lengthsum functionality: 1) it uses tensor train // to calculate the embedding for each index. 2) it sums the embedding for each bag. // In Step 1), it batches all the indices together. Specifically, for every index, it uses the pre-computed // ind of each tensor core to extract the corresponding slice of the core. Then it does gemm operation // sequentially on the slices to produce the embedding result for each index. // In Step 2), it takes the embedding computed in step 1) and apply the sum operation for each bag. bool GatherAllRows( int64_t* ind, int bs, int x_len, vector cores, int segments, const int* lengths, T* out_data) { // compute the largest memory consumption of intermediate result // TODO: dynamic allocation size: cur_rows*factor_j[i]*ranks[i+1] // and also explore the contiguous memory storage for res and int_res int max_rank = *max_element(ranks.begin(), ranks.end()); std::vector> res(bs, std::vector(emb_size * max_rank, 0)); std::vector> int_res( bs, std::vector(emb_size * max_rank, 0)); // Store the matrix A vector Y_ptr(bs); // Store the intermediate result in each layer vector Z_ptr(bs); for (int b = 0; b < bs; b++) { Y_ptr[b] = res[b].data(); Z_ptr[b] = int_res[b].data(); } vector ind_slice(bs); int rows = 0; for (int i = 0; i < x_len; i++) { // slice cur for (int j = 0; j < bs; j++) { ind_slice[j] = ind[x_len * j + i]; } if (i == 0) { GetSlice(res, cores[i], ind_slice, bs, i); rows = factor_j[0]; } else { std::vector> slice( bs, std::vector(ranks[i] * factor_j[i] * ranks[i + 1], 0)); vector X_ptr(bs); for (int b = 0; b < bs; b++) { X_ptr[b] = slice[b].data(); } GetSlice(slice, cores[i], ind_slice, bs, i); math::GemmBatched( CblasNoTrans, CblasNoTrans, bs, rows, factor_j[i] * ranks[i + 1], ranks[i], 1.0f, const_cast(Y_ptr.data()), X_ptr.data(), 0.0f, Z_ptr.data(), &context_); for (int b = 0; b < bs; b++) { std::memcpy(Y_ptr[b], Z_ptr[b], (emb_size * max_rank) * sizeof(T)); } rows *= factor_j[i]; } // save the intermediate output for backward path // shape for the core auto shape = vector({bs, rows, ranks[i + 1]}); if (i < 2) { auto* core_data = Output(i + 1, shape, at::dtype()); T* out_core = core_data->template mutable_data(); for (int b = 0; b < bs; b++) { std::memcpy( out_core + b * rows * ranks[i + 1], Y_ptr[b], rows * ranks[i + 1] * sizeof(T)); } } } // reduction and store back to output vector cum_lengths(segments); for (int seg = 0; seg < segments; seg++) { cum_lengths[seg] = seg == 0 ? lengths[0] : lengths[seg] + cum_lengths[seg - 1]; } int length_idx = 0; vector tmp_sum(emb_size, 0.0f); for (int i = 0; i <= bs; i++) { while ((length_idx < segments) && (i == cum_lengths[length_idx])) { // store the tmp_sum into output memcpy( &out_data[length_idx * emb_size], tmp_sum.data(), emb_size * sizeof(T)); length_idx++; fill(tmp_sum.begin(), tmp_sum.end(), 0.0f); } if (i == bs) { break; } transform( res[i].begin(), res[i].begin() + emb_size, tmp_sum.begin(), tmp_sum.begin(), std::plus()); } return true; } bool RunOnDevice() override { const auto& dataInput0 = Input(0); const auto& dataInput1 = Input(1); const auto& dataInput2 = Input(2); const auto& indicesInput = Input(3); const auto& lengthsInput = Input(4); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); int N = factor_i.size(); const int64_t M = lengthsInput.size(0); auto shape = vector({M, emb_size}); auto* output = Output(0, shape, at::dtype()); T* out_data = output->template mutable_data(); const T* core0 = dataInput0.template data(); const T* core1 = dataInput1.template data(); const T* core2 = dataInput2.template data(); const int* lengths = lengthsInput.template data(); vector cores = {core0, core1, core2}; const int64_t* indices = indicesInput.template data(); // Store the factor index for backward path auto index_shape = vector({indicesInput.size(), N}); auto* index_data = Output(3, index_shape, at::dtype()); int64_t* out_factor_index = index_data->template mutable_data(); // Store the factorized index for each core Ind2Sub(out_factor_index, indices, indicesInput.size()); return GatherAllRows( out_factor_index, indicesInput.size(), N, cores, M, lengths, out_data); } protected: vector factor_i; vector factor_j; vector ranks; vector l_cumprod; int emb_size; }; template class TTSparseLengthsSumGradientOp final : public Operator { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template explicit TTSparseLengthsSumGradientOp(Args&&... args) : Operator(std::forward(args)...) {} bool RunOnDevice() override; ~TTSparseLengthsSumGradientOp() {} }; // implement the graident op for TTLengthSumGradient op template bool TTSparseLengthsSumGradientOp::RunOnDevice() { const auto& core0 = Input(0); const auto& core1 = Input(1); const auto& core2 = Input(2); const auto& lengths = Input(3); const auto& core0_out = Input(4); const auto& core1_out = Input(5); const auto& index_out = Input(6); const auto& dY = Input(7); const int* lengths_data = lengths.template data(); const T* dY_data = dY.template data(); // restore the arguments from shape const int64_t bs = index_out.size(0); const int64_t emb_size = dY.size(1); const int64_t num_segments = lengths.size(0); auto core0_shape = core0.sizes().vec(); auto core1_shape = core1.sizes().vec(); auto core2_shape = core2.sizes().vec(); auto core0_out_shape = core0_out.sizes().vec(); auto core1_out_shape = core1_out.sizes().vec(); auto* dCore0 = Output(0, core0_shape, at::dtype()); auto* dCore1 = Output(1, core1_shape, at::dtype()); auto* dCore2 = Output(2, core2_shape, at::dtype()); T* dCore0_data = dCore0->template mutable_data(); T* dCore1_data = dCore1->template mutable_data(); T* dCore2_data = dCore2->template mutable_data(); memset( dCore0_data, 0.0f, sizeof(T) * accumulate( core0_shape.begin(), core0_shape.end(), 1, std::multiplies())); memset( dCore1_data, 0.0f, sizeof(T) * accumulate( core1_shape.begin(), core1_shape.end(), 1, std::multiplies())); memset( dCore2_data, 0.0f, sizeof(T) * accumulate( core2_shape.begin(), core2_shape.end(), 1, std::multiplies())); int64_t* index_out_data = index_out.template mutable_data(); vector> index_slice(bs, vector(3, 0)); for (int64_t b = 0; b < bs; b++) { memcpy(index_slice[b].data(), index_out_data + b * 3, 3 * sizeof(int64_t)); } vector A_ptr(bs); vector B_ptr(bs); vector C_ptr(bs); // size of each batch int64_t num_of_elements = 0; // construct the ranks // expand the gradient into all indices vector> core2_out_grad(bs, vector(emb_size, 0)); int64_t data_index = 0; for (int64_t range_index = 0; range_index < num_segments; ++range_index) { for (int64_t start = data_index; data_index < start + lengths_data[range_index]; ++data_index) { memcpy( core2_out_grad[data_index].data(), dY_data + range_index * emb_size, emb_size * sizeof(T)); } } // ======================================================= // Calculate dCore2_data: // 1) Transpose core1_out and multiply iwth core2_out_grad // 2) add to dCore2_data vector> dCore2_data_slice_grad( bs, vector(core2_shape[1] * core2_shape[2] * core2_shape[3], 0)); const T* core1_out_data = core1_out.template data(); // const T* core1_out_p[bs]; for (int64_t b = 0; b < bs; b++) { A_ptr[b] = core1_out_data + b * core1_out.size(1) * core1_out.size(2); B_ptr[b] = core2_out_grad[b].data(); C_ptr[b] = dCore2_data_slice_grad[b].data(); } math::GemmBatched( CblasTrans, CblasNoTrans, bs, core2.size(1), // M core2.size(2) * core2.size(3), // N core1_out.size(1), // K 1.0f, const_cast(A_ptr.data()), const_cast(B_ptr.data()), 0.0f, C_ptr.data(), &context_); // update the corresponding slice num_of_elements = core2_shape[1] * core2_shape[2] * core2_shape[3]; T* core2_data = core2.template mutable_data(); vector> core2_slice( bs, vector(core2_shape[1] * core2_shape[2] * core2_shape[3], 0)); for (int64_t b = 0; b < bs; b++) { for (int i = 0; i < num_of_elements; i++) { dCore2_data[index_slice[b][2] * num_of_elements + i] += C_ptr[b][i]; } memcpy( core2_slice[b].data(), core2_data + index_slice[b][2] * num_of_elements, sizeof(T) * num_of_elements); } // Calculate core1_out_grad vector> core1_out_grad( bs, vector(core1_out_shape[1] * core1_out_shape[2], 0)); for (int64_t b = 0; b < bs; b++) { A_ptr[b] = core2_out_grad[b].data(); B_ptr[b] = core2_slice[b].data(); C_ptr[b] = core1_out_grad[b].data(); } math::GemmBatched( CblasNoTrans, CblasTrans, bs, core1_out.size(1), // M core2_shape[1], // N core2_shape[2] * core2_shape[3], // K 1.0f, const_cast(A_ptr.data()), const_cast(B_ptr.data()), 0.0f, C_ptr.data(), &context_); // ======================================================= // Calcuate dCore1_data: // 1) Transpose core1_out_grad and multiply with core0_out // 2) Transpose the result and then add to dCore1_data vector> dCore1_data_slice_grad( bs, vector(core1_shape[1] * core1_shape[2] * core1_shape[3], 0)); const T* core0_out_data = core0_out.template data(); for (int64_t b = 0; b < bs; b++) { A_ptr[b] = core0_out_data + b * core0_out.size(1) * core0_out.size(2); B_ptr[b] = core1_out_grad[b].data(); C_ptr[b] = dCore1_data_slice_grad[b].data(); } math::GemmBatched( CblasTrans, CblasNoTrans, bs, core1.size(1), // M core1.size(2) * core1.size(3), // N core0_out.size(1), // K 1.0f, const_cast(A_ptr.data()), const_cast(B_ptr.data()), 0.0f, C_ptr.data(), &context_); // update the corresponding slice num_of_elements = core1_shape[1] * core1_shape[2] * core1_shape[3]; T* core1_data = core1.template mutable_data(); vector> core1_slice( bs, vector(core1_shape[1] * core1_shape[2] * core1_shape[3], 0)); for (int64_t b = 0; b < bs; b++) { for (int i = 0; i < num_of_elements; i++) { dCore1_data[index_slice[b][1] * num_of_elements + i] += C_ptr[b][i]; } memcpy( core1_slice[b].data(), core1_data + index_slice[b][1] * num_of_elements, sizeof(T) * num_of_elements); } // Calcuate core0_out_grad vector> core0_out_grad( bs, vector(core0_out_shape[1] * core0_out_shape[2], 0)); for (int64_t b = 0; b < bs; b++) { A_ptr[b] = core1_out_grad[b].data(); B_ptr[b] = core1_slice[b].data(); C_ptr[b] = core0_out_grad[b].data(); } math::GemmBatched( CblasNoTrans, CblasTrans, bs, core0_out.size(1), // M core1_shape[1], // N core1_shape[2] * core1_shape[3], // K 1.0f, const_cast(A_ptr.data()), const_cast(B_ptr.data()), 0.0f, C_ptr.data(), &context_); num_of_elements = core0_shape[1] * core0_shape[2] * core0_shape[3]; for (int64_t b = 0; b < bs; b++) { for (int i = 0; i < num_of_elements; i++) { dCore0_data[index_slice[b][0] * num_of_elements + i] += C_ptr[b][i]; } } return true; } } // namespace caffe2