Repository: BM-K/Sentence-Embedding-Is-All-You-Need Branch: main Commit: 32cec8ea887f Files: 522 Total size: 4.0 MB Directory structure: gitextract_y9jvowoy/ ├── KoSBERT/ │ ├── Clustering.py │ ├── README.md │ ├── SemanticSearch.py │ ├── con_training_sts.py │ ├── output/ │ │ └── empty.txt │ ├── run_example.sh │ └── training_nli.py ├── KoSentenceT5/ │ ├── README.md │ ├── apex/ │ │ ├── RNN/ │ │ │ ├── README.md │ │ │ ├── RNNBackend.py │ │ │ ├── __init__.py │ │ │ ├── cells.py │ │ │ └── models.py │ │ ├── __init__.py │ │ ├── amp/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── __version__.py │ │ │ ├── _amp_state.py │ │ │ ├── _initialize.py │ │ │ ├── _process_optimizer.py │ │ │ ├── amp.py │ │ │ ├── compat.py │ │ │ ├── frontend.py │ │ │ ├── handle.py │ │ │ ├── lists/ │ │ │ │ ├── __init__.py │ │ │ │ ├── functional_overrides.py │ │ │ │ ├── tensor_overrides.py │ │ │ │ └── torch_overrides.py │ │ │ ├── opt.py │ │ │ ├── rnn_compat.py │ │ │ ├── scaler.py │ │ │ ├── utils.py │ │ │ └── wrap.py │ │ ├── contrib/ │ │ │ ├── __init__.py │ │ │ ├── bottleneck/ │ │ │ │ ├── __init__.py │ │ │ │ ├── bottleneck.py │ │ │ │ └── test.py │ │ │ ├── csrc/ │ │ │ │ ├── bottleneck/ │ │ │ │ │ └── bottleneck.cpp │ │ │ │ ├── fmha/ │ │ │ │ │ ├── fmha_api.cpp │ │ │ │ │ └── src/ │ │ │ │ │ ├── fmha/ │ │ │ │ │ │ ├── gemm.h │ │ │ │ │ │ ├── gmem_tile.h │ │ │ │ │ │ ├── kernel_traits.h │ │ │ │ │ │ ├── mask.h │ │ │ │ │ │ ├── smem_tile.h │ │ │ │ │ │ ├── softmax.h │ │ │ │ │ │ └── utils.h │ │ │ │ │ ├── fmha.h │ │ │ │ │ ├── fmha_dgrad_fp16_128_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_256_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_384_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_512_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_kernel_1xN_reload.h │ │ │ │ │ ├── fmha_dgrad_kernel_1xN_reload_nl.h │ │ │ │ │ ├── fmha_fprop_fp16_128_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_256_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_384_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_512_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_kernel_1xN.h │ │ │ │ │ ├── fmha_fprop_kernel_1xN_nl.h │ │ │ │ │ ├── fmha_fprop_kernel_1xN_reload_v.h │ │ │ │ │ ├── fmha_kernel.h │ │ │ │ │ ├── fmha_noloop_reduce.cu │ │ │ │ │ └── fmha_utils.h │ │ │ │ ├── groupbn/ │ │ │ │ │ ├── batch_norm.cu │ │ │ │ │ ├── batch_norm.h │ │ │ │ │ ├── batch_norm_add_relu.cu │ │ │ │ │ ├── batch_norm_add_relu.h │ │ │ │ │ ├── cuda_utils.h │ │ │ │ │ ├── interface.cpp │ │ │ │ │ ├── ipc.cu │ │ │ │ │ └── nhwc_batch_norm_kernel.h │ │ │ │ ├── layer_norm/ │ │ │ │ │ ├── ln_api.cpp │ │ │ │ │ ├── ln_bwd_semi_cuda_kernel.cu │ │ │ │ │ ├── ln_fwd_cuda_kernel.cu │ │ │ │ │ ├── ln_kernel_traits.h │ │ │ │ │ └── utils.cuh │ │ │ │ ├── multihead_attn/ │ │ │ │ │ ├── additive_masked_softmax_dropout.cpp │ │ │ │ │ ├── additive_masked_softmax_dropout_cuda.cu │ │ │ │ │ ├── dropout.h │ │ │ │ │ ├── encdec_multihead_attn.cpp │ │ │ │ │ ├── encdec_multihead_attn_cuda.cu │ │ │ │ │ ├── encdec_multihead_attn_norm_add.cpp │ │ │ │ │ ├── encdec_multihead_attn_norm_add_cuda.cu │ │ │ │ │ ├── layer_norm.h │ │ │ │ │ ├── masked_softmax_dropout.cpp │ │ │ │ │ ├── masked_softmax_dropout_cuda.cu │ │ │ │ │ ├── philox.h │ │ │ │ │ ├── self_multihead_attn.cpp │ │ │ │ │ ├── self_multihead_attn_bias.cpp │ │ │ │ │ ├── self_multihead_attn_bias_additive_mask.cpp │ │ │ │ │ ├── self_multihead_attn_bias_additive_mask_cuda.cu │ │ │ │ │ ├── self_multihead_attn_bias_cuda.cu │ │ │ │ │ ├── self_multihead_attn_cuda.cu │ │ │ │ │ ├── self_multihead_attn_norm_add.cpp │ │ │ │ │ ├── self_multihead_attn_norm_add_cuda.cu │ │ │ │ │ ├── softmax.h │ │ │ │ │ └── strided_batched_gemm.h │ │ │ │ ├── optimizers/ │ │ │ │ │ ├── fused_adam_cuda.cpp │ │ │ │ │ ├── fused_adam_cuda_kernel.cu │ │ │ │ │ ├── fused_lamb_cuda.cpp │ │ │ │ │ ├── fused_lamb_cuda_kernel.cu │ │ │ │ │ ├── multi_tensor_distopt_adam.cpp │ │ │ │ │ ├── multi_tensor_distopt_adam_kernel.cu │ │ │ │ │ ├── multi_tensor_distopt_lamb.cpp │ │ │ │ │ └── multi_tensor_distopt_lamb_kernel.cu │ │ │ │ ├── transducer/ │ │ │ │ │ ├── transducer_joint.cpp │ │ │ │ │ ├── transducer_joint_kernel.cu │ │ │ │ │ ├── transducer_loss.cpp │ │ │ │ │ └── transducer_loss_kernel.cu │ │ │ │ └── xentropy/ │ │ │ │ ├── interface.cpp │ │ │ │ └── xentropy_kernel.cu │ │ │ ├── examples/ │ │ │ │ └── multihead_attn/ │ │ │ │ ├── func_test_multihead_attn.py │ │ │ │ └── perf_test_multihead_attn.py │ │ │ ├── fmha/ │ │ │ │ ├── __init__.py │ │ │ │ └── fmha.py │ │ │ ├── groupbn/ │ │ │ │ ├── __init__.py │ │ │ │ └── batch_norm.py │ │ │ ├── layer_norm/ │ │ │ │ ├── __init__.py │ │ │ │ └── layer_norm.py │ │ │ ├── multihead_attn/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── encdec_multihead_attn.py │ │ │ │ ├── encdec_multihead_attn_func.py │ │ │ │ ├── fast_encdec_multihead_attn_func.py │ │ │ │ ├── fast_encdec_multihead_attn_norm_add_func.py │ │ │ │ ├── fast_self_multihead_attn_func.py │ │ │ │ ├── fast_self_multihead_attn_norm_add_func.py │ │ │ │ ├── mask_softmax_dropout_func.py │ │ │ │ ├── self_multihead_attn.py │ │ │ │ └── self_multihead_attn_func.py │ │ │ ├── optimizers/ │ │ │ │ ├── __init__.py │ │ │ │ ├── distributed_fused_adam.py │ │ │ │ ├── distributed_fused_adam_v2.py │ │ │ │ ├── distributed_fused_adam_v3.py │ │ │ │ ├── distributed_fused_lamb.py │ │ │ │ ├── fp16_optimizer.py │ │ │ │ ├── fused_adam.py │ │ │ │ ├── fused_lamb.py │ │ │ │ └── fused_sgd.py │ │ │ ├── sparsity/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── asp.py │ │ │ │ ├── sparse_masklib.py │ │ │ │ └── test/ │ │ │ │ ├── checkpointing_test_part1.py │ │ │ │ ├── checkpointing_test_part2.py │ │ │ │ ├── checkpointing_test_reference.py │ │ │ │ └── toy_problem.py │ │ │ ├── test/ │ │ │ │ ├── fmha/ │ │ │ │ │ └── test_fmha.py │ │ │ │ ├── layer_norm/ │ │ │ │ │ └── test_fast_layer_norm.py │ │ │ │ ├── multihead_attn/ │ │ │ │ │ ├── test_encdec_multihead_attn.py │ │ │ │ │ ├── test_encdec_multihead_attn_norm_add.py │ │ │ │ │ ├── test_fast_self_multihead_attn_bias.py │ │ │ │ │ ├── test_mha_fused_softmax.py │ │ │ │ │ ├── test_self_multihead_attn.py │ │ │ │ │ └── test_self_multihead_attn_norm_add.py │ │ │ │ ├── test_label_smoothing.py │ │ │ │ └── transducer/ │ │ │ │ ├── test_transducer_joint.py │ │ │ │ ├── test_transducer_loss.py │ │ │ │ └── transducer_ref.py │ │ │ ├── transducer/ │ │ │ │ ├── __init__.py │ │ │ │ └── transducer.py │ │ │ └── xentropy/ │ │ │ ├── __init__.py │ │ │ └── softmax_xentropy.py │ │ ├── fp16_utils/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── fp16_optimizer.py │ │ │ ├── fp16util.py │ │ │ └── loss_scaler.py │ │ ├── mlp/ │ │ │ ├── __init__.py │ │ │ └── mlp.py │ │ ├── multi_tensor_apply/ │ │ │ ├── __init__.py │ │ │ └── multi_tensor_apply.py │ │ ├── normalization/ │ │ │ ├── __init__.py │ │ │ └── fused_layer_norm.py │ │ ├── optimizers/ │ │ │ ├── __init__.py │ │ │ ├── fused_adagrad.py │ │ │ ├── fused_adam.py │ │ │ ├── fused_lamb.py │ │ │ ├── fused_novograd.py │ │ │ └── fused_sgd.py │ │ ├── parallel/ │ │ │ ├── LARC.py │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── distributed.py │ │ │ ├── multiproc.py │ │ │ ├── optimized_sync_batchnorm.py │ │ │ ├── optimized_sync_batchnorm_kernel.py │ │ │ ├── sync_batchnorm.py │ │ │ └── sync_batchnorm_kernel.py │ │ ├── pyprof/ │ │ │ ├── FAQs.md │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── examples/ │ │ │ │ ├── .gitignore │ │ │ │ ├── apex/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── fused_adam.py │ │ │ │ │ ├── fused_layer_norm.py │ │ │ │ │ └── test.sh │ │ │ │ ├── custom_func_module/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── custom_function.py │ │ │ │ │ ├── custom_module.py │ │ │ │ │ └── test.sh │ │ │ │ ├── imagenet/ │ │ │ │ │ ├── imagenet.py │ │ │ │ │ └── test.sh │ │ │ │ ├── jit/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── jit_script_function.py │ │ │ │ │ ├── jit_script_method.py │ │ │ │ │ ├── jit_trace_function.py │ │ │ │ │ ├── jit_trace_method.py │ │ │ │ │ └── test.sh │ │ │ │ ├── lenet.py │ │ │ │ ├── operators.py │ │ │ │ ├── simple.py │ │ │ │ └── user_annotation/ │ │ │ │ ├── README.md │ │ │ │ ├── resnet.py │ │ │ │ └── test.sh │ │ │ ├── nvtx/ │ │ │ │ ├── __init__.py │ │ │ │ └── nvmarker.py │ │ │ ├── parse/ │ │ │ │ ├── __init__.py │ │ │ │ ├── __main__.py │ │ │ │ ├── db.py │ │ │ │ ├── kernel.py │ │ │ │ ├── nvvp.py │ │ │ │ └── parse.py │ │ │ └── prof/ │ │ │ ├── __init__.py │ │ │ ├── __main__.py │ │ │ ├── activation.py │ │ │ ├── base.py │ │ │ ├── blas.py │ │ │ ├── conv.py │ │ │ ├── convert.py │ │ │ ├── data.py │ │ │ ├── dropout.py │ │ │ ├── embedding.py │ │ │ ├── index_slice_join_mutate.py │ │ │ ├── linear.py │ │ │ ├── loss.py │ │ │ ├── misc.py │ │ │ ├── normalization.py │ │ │ ├── optim.py │ │ │ ├── output.py │ │ │ ├── pointwise.py │ │ │ ├── pooling.py │ │ │ ├── prof.py │ │ │ ├── randomSample.py │ │ │ ├── recurrentCell.py │ │ │ ├── reduction.py │ │ │ ├── softmax.py │ │ │ ├── usage.py │ │ │ └── utility.py │ │ └── reparameterization/ │ │ ├── README.md │ │ ├── __init__.py │ │ ├── reparameterization.py │ │ └── weight_norm.py │ ├── data/ │ │ └── dataloader.py │ ├── main.py │ ├── model/ │ │ ├── loss.py │ │ ├── setting.py │ │ ├── simcse/ │ │ │ ├── kost5.py │ │ │ └── processor.py │ │ └── utils.py │ └── run_example.sh ├── KoSimCSE/ │ ├── README.md │ ├── SemanticSearch.py │ ├── apex/ │ │ ├── RNN/ │ │ │ ├── README.md │ │ │ ├── RNNBackend.py │ │ │ ├── __init__.py │ │ │ ├── cells.py │ │ │ └── models.py │ │ ├── __init__.py │ │ ├── amp/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── __version__.py │ │ │ ├── _amp_state.py │ │ │ ├── _initialize.py │ │ │ ├── _process_optimizer.py │ │ │ ├── amp.py │ │ │ ├── compat.py │ │ │ ├── frontend.py │ │ │ ├── handle.py │ │ │ ├── lists/ │ │ │ │ ├── __init__.py │ │ │ │ ├── functional_overrides.py │ │ │ │ ├── tensor_overrides.py │ │ │ │ └── torch_overrides.py │ │ │ ├── opt.py │ │ │ ├── rnn_compat.py │ │ │ ├── scaler.py │ │ │ ├── utils.py │ │ │ └── wrap.py │ │ ├── contrib/ │ │ │ ├── __init__.py │ │ │ ├── bottleneck/ │ │ │ │ ├── __init__.py │ │ │ │ ├── bottleneck.py │ │ │ │ └── test.py │ │ │ ├── csrc/ │ │ │ │ ├── bottleneck/ │ │ │ │ │ └── bottleneck.cpp │ │ │ │ ├── fmha/ │ │ │ │ │ ├── fmha_api.cpp │ │ │ │ │ └── src/ │ │ │ │ │ ├── fmha/ │ │ │ │ │ │ ├── gemm.h │ │ │ │ │ │ ├── gmem_tile.h │ │ │ │ │ │ ├── kernel_traits.h │ │ │ │ │ │ ├── mask.h │ │ │ │ │ │ ├── smem_tile.h │ │ │ │ │ │ ├── softmax.h │ │ │ │ │ │ └── utils.h │ │ │ │ │ ├── fmha.h │ │ │ │ │ ├── fmha_dgrad_fp16_128_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_256_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_384_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_fp16_512_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_dgrad_kernel_1xN_reload.h │ │ │ │ │ ├── fmha_dgrad_kernel_1xN_reload_nl.h │ │ │ │ │ ├── fmha_fprop_fp16_128_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_256_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_384_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_fp16_512_64_kernel.sm80.cu │ │ │ │ │ ├── fmha_fprop_kernel_1xN.h │ │ │ │ │ ├── fmha_fprop_kernel_1xN_nl.h │ │ │ │ │ ├── fmha_fprop_kernel_1xN_reload_v.h │ │ │ │ │ ├── fmha_kernel.h │ │ │ │ │ ├── fmha_noloop_reduce.cu │ │ │ │ │ └── fmha_utils.h │ │ │ │ ├── groupbn/ │ │ │ │ │ ├── batch_norm.cu │ │ │ │ │ ├── batch_norm.h │ │ │ │ │ ├── batch_norm_add_relu.cu │ │ │ │ │ ├── batch_norm_add_relu.h │ │ │ │ │ ├── cuda_utils.h │ │ │ │ │ ├── interface.cpp │ │ │ │ │ ├── ipc.cu │ │ │ │ │ └── nhwc_batch_norm_kernel.h │ │ │ │ ├── layer_norm/ │ │ │ │ │ ├── ln_api.cpp │ │ │ │ │ ├── ln_bwd_semi_cuda_kernel.cu │ │ │ │ │ ├── ln_fwd_cuda_kernel.cu │ │ │ │ │ ├── ln_kernel_traits.h │ │ │ │ │ └── utils.cuh │ │ │ │ ├── multihead_attn/ │ │ │ │ │ ├── additive_masked_softmax_dropout.cpp │ │ │ │ │ ├── additive_masked_softmax_dropout_cuda.cu │ │ │ │ │ ├── dropout.h │ │ │ │ │ ├── encdec_multihead_attn.cpp │ │ │ │ │ ├── encdec_multihead_attn_cuda.cu │ │ │ │ │ ├── encdec_multihead_attn_norm_add.cpp │ │ │ │ │ ├── encdec_multihead_attn_norm_add_cuda.cu │ │ │ │ │ ├── layer_norm.h │ │ │ │ │ ├── masked_softmax_dropout.cpp │ │ │ │ │ ├── masked_softmax_dropout_cuda.cu │ │ │ │ │ ├── philox.h │ │ │ │ │ ├── self_multihead_attn.cpp │ │ │ │ │ ├── self_multihead_attn_bias.cpp │ │ │ │ │ ├── self_multihead_attn_bias_additive_mask.cpp │ │ │ │ │ ├── self_multihead_attn_bias_additive_mask_cuda.cu │ │ │ │ │ ├── self_multihead_attn_bias_cuda.cu │ │ │ │ │ ├── self_multihead_attn_cuda.cu │ │ │ │ │ ├── self_multihead_attn_norm_add.cpp │ │ │ │ │ ├── self_multihead_attn_norm_add_cuda.cu │ │ │ │ │ ├── softmax.h │ │ │ │ │ └── strided_batched_gemm.h │ │ │ │ ├── optimizers/ │ │ │ │ │ ├── fused_adam_cuda.cpp │ │ │ │ │ ├── fused_adam_cuda_kernel.cu │ │ │ │ │ ├── fused_lamb_cuda.cpp │ │ │ │ │ ├── fused_lamb_cuda_kernel.cu │ │ │ │ │ ├── multi_tensor_distopt_adam.cpp │ │ │ │ │ ├── multi_tensor_distopt_adam_kernel.cu │ │ │ │ │ ├── multi_tensor_distopt_lamb.cpp │ │ │ │ │ └── multi_tensor_distopt_lamb_kernel.cu │ │ │ │ ├── transducer/ │ │ │ │ │ ├── transducer_joint.cpp │ │ │ │ │ ├── transducer_joint_kernel.cu │ │ │ │ │ ├── transducer_loss.cpp │ │ │ │ │ └── transducer_loss_kernel.cu │ │ │ │ └── xentropy/ │ │ │ │ ├── interface.cpp │ │ │ │ └── xentropy_kernel.cu │ │ │ ├── examples/ │ │ │ │ └── multihead_attn/ │ │ │ │ ├── func_test_multihead_attn.py │ │ │ │ └── perf_test_multihead_attn.py │ │ │ ├── fmha/ │ │ │ │ ├── __init__.py │ │ │ │ └── fmha.py │ │ │ ├── groupbn/ │ │ │ │ ├── __init__.py │ │ │ │ └── batch_norm.py │ │ │ ├── layer_norm/ │ │ │ │ ├── __init__.py │ │ │ │ └── layer_norm.py │ │ │ ├── multihead_attn/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── encdec_multihead_attn.py │ │ │ │ ├── encdec_multihead_attn_func.py │ │ │ │ ├── fast_encdec_multihead_attn_func.py │ │ │ │ ├── fast_encdec_multihead_attn_norm_add_func.py │ │ │ │ ├── fast_self_multihead_attn_func.py │ │ │ │ ├── fast_self_multihead_attn_norm_add_func.py │ │ │ │ ├── mask_softmax_dropout_func.py │ │ │ │ ├── self_multihead_attn.py │ │ │ │ └── self_multihead_attn_func.py │ │ │ ├── optimizers/ │ │ │ │ ├── __init__.py │ │ │ │ ├── distributed_fused_adam.py │ │ │ │ ├── distributed_fused_adam_v2.py │ │ │ │ ├── distributed_fused_adam_v3.py │ │ │ │ ├── distributed_fused_lamb.py │ │ │ │ ├── fp16_optimizer.py │ │ │ │ ├── fused_adam.py │ │ │ │ ├── fused_lamb.py │ │ │ │ └── fused_sgd.py │ │ │ ├── sparsity/ │ │ │ │ ├── README.md │ │ │ │ ├── __init__.py │ │ │ │ ├── asp.py │ │ │ │ ├── sparse_masklib.py │ │ │ │ └── test/ │ │ │ │ ├── checkpointing_test_part1.py │ │ │ │ ├── checkpointing_test_part2.py │ │ │ │ ├── checkpointing_test_reference.py │ │ │ │ └── toy_problem.py │ │ │ ├── test/ │ │ │ │ ├── fmha/ │ │ │ │ │ └── test_fmha.py │ │ │ │ ├── layer_norm/ │ │ │ │ │ └── test_fast_layer_norm.py │ │ │ │ ├── multihead_attn/ │ │ │ │ │ ├── test_encdec_multihead_attn.py │ │ │ │ │ ├── test_encdec_multihead_attn_norm_add.py │ │ │ │ │ ├── test_fast_self_multihead_attn_bias.py │ │ │ │ │ ├── test_mha_fused_softmax.py │ │ │ │ │ ├── test_self_multihead_attn.py │ │ │ │ │ └── test_self_multihead_attn_norm_add.py │ │ │ │ ├── test_label_smoothing.py │ │ │ │ └── transducer/ │ │ │ │ ├── test_transducer_joint.py │ │ │ │ ├── test_transducer_loss.py │ │ │ │ └── transducer_ref.py │ │ │ ├── transducer/ │ │ │ │ ├── __init__.py │ │ │ │ └── transducer.py │ │ │ └── xentropy/ │ │ │ ├── __init__.py │ │ │ └── softmax_xentropy.py │ │ ├── fp16_utils/ │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── fp16_optimizer.py │ │ │ ├── fp16util.py │ │ │ └── loss_scaler.py │ │ ├── mlp/ │ │ │ ├── __init__.py │ │ │ └── mlp.py │ │ ├── multi_tensor_apply/ │ │ │ ├── __init__.py │ │ │ └── multi_tensor_apply.py │ │ ├── normalization/ │ │ │ ├── __init__.py │ │ │ └── fused_layer_norm.py │ │ ├── optimizers/ │ │ │ ├── __init__.py │ │ │ ├── fused_adagrad.py │ │ │ ├── fused_adam.py │ │ │ ├── fused_lamb.py │ │ │ ├── fused_novograd.py │ │ │ └── fused_sgd.py │ │ ├── parallel/ │ │ │ ├── LARC.py │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── distributed.py │ │ │ ├── multiproc.py │ │ │ ├── optimized_sync_batchnorm.py │ │ │ ├── optimized_sync_batchnorm_kernel.py │ │ │ ├── sync_batchnorm.py │ │ │ └── sync_batchnorm_kernel.py │ │ ├── pyprof/ │ │ │ ├── FAQs.md │ │ │ ├── README.md │ │ │ ├── __init__.py │ │ │ ├── examples/ │ │ │ │ ├── .gitignore │ │ │ │ ├── apex/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── fused_adam.py │ │ │ │ │ ├── fused_layer_norm.py │ │ │ │ │ └── test.sh │ │ │ │ ├── custom_func_module/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── custom_function.py │ │ │ │ │ ├── custom_module.py │ │ │ │ │ └── test.sh │ │ │ │ ├── imagenet/ │ │ │ │ │ ├── imagenet.py │ │ │ │ │ └── test.sh │ │ │ │ ├── jit/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── jit_script_function.py │ │ │ │ │ ├── jit_script_method.py │ │ │ │ │ ├── jit_trace_function.py │ │ │ │ │ ├── jit_trace_method.py │ │ │ │ │ └── test.sh │ │ │ │ ├── lenet.py │ │ │ │ ├── operators.py │ │ │ │ ├── simple.py │ │ │ │ └── user_annotation/ │ │ │ │ ├── README.md │ │ │ │ ├── resnet.py │ │ │ │ └── test.sh │ │ │ ├── nvtx/ │ │ │ │ ├── __init__.py │ │ │ │ └── nvmarker.py │ │ │ ├── parse/ │ │ │ │ ├── __init__.py │ │ │ │ ├── __main__.py │ │ │ │ ├── db.py │ │ │ │ ├── kernel.py │ │ │ │ ├── nvvp.py │ │ │ │ └── parse.py │ │ │ └── prof/ │ │ │ ├── __init__.py │ │ │ ├── __main__.py │ │ │ ├── activation.py │ │ │ ├── base.py │ │ │ ├── blas.py │ │ │ ├── conv.py │ │ │ ├── convert.py │ │ │ ├── data.py │ │ │ ├── dropout.py │ │ │ ├── embedding.py │ │ │ ├── index_slice_join_mutate.py │ │ │ ├── linear.py │ │ │ ├── loss.py │ │ │ ├── misc.py │ │ │ ├── normalization.py │ │ │ ├── optim.py │ │ │ ├── output.py │ │ │ ├── pointwise.py │ │ │ ├── pooling.py │ │ │ ├── prof.py │ │ │ ├── randomSample.py │ │ │ ├── recurrentCell.py │ │ │ ├── reduction.py │ │ │ ├── softmax.py │ │ │ ├── usage.py │ │ │ └── utility.py │ │ └── reparameterization/ │ │ ├── README.md │ │ ├── __init__.py │ │ ├── reparameterization.py │ │ └── weight_norm.py │ ├── data/ │ │ └── dataloader.py │ ├── main.py │ ├── model/ │ │ ├── loss.py │ │ ├── setting.py │ │ ├── simcse/ │ │ │ ├── bert.py │ │ │ └── processor.py │ │ └── utils.py │ ├── output/ │ │ └── empty.txt │ ├── requirements.txt │ └── run_example.sh ├── LICENSE ├── README.md ├── get_model_checkpoint.sh └── get_model_dataset.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: KoSBERT/Clustering.py ================================================ from sentence_transformers import SentenceTransformer, util import numpy as np model_path = '../Checkpoint/KoSBERT/kosbert-klue-bert-base' embedder = SentenceTransformer(model_path) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.', '한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] corpus_embeddings = embedder.encode(corpus) # Then, we perform k-means clustering using sklearn: from sklearn.cluster import KMeans num_clusters = 5 clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(corpus_embeddings) cluster_assignment = clustering_model.labels_ clustered_sentences = [[] for i in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(corpus[sentence_id]) for i, cluster in enumerate(clustered_sentences): print("Cluster ", i+1) print(cluster) print("") ================================================ FILE: KoSBERT/README.md ================================================ # KoSentenceBERT [[Github]](https://github.com/UKPLab/sentence-transformers) Official implementation of SBERT.
Korean SentenceBERT : Korean Sentence Embeddings using Siamese BERT-Networks. ## Quick start - If you want to do inference quickly, download the pre-trained models and then you can start some downstream tasks. ``` bash get_model_checkpoint.sh python SemanticSearch.py ``` ## Training - Before training or evaluation, please download the datasets by running ``` bash get_model_dataset.sh ``` - Two stage training - First step, training NLI dataset ``` python training_nli.py --model klue/bert-base --batch 32 --evaluation_steps 1000 --epochs 1 ``` - Second step, continued training STS dataset ``` python con_training_sts.py --model klue/bert-base --batch 32 --evaluation_steps 1000 --epochs 4 ``` - Run Examples ``` bash run_example.sh ``` ### Hyperparameters - Training NLI 1. Pooling Method: MEAN strategy 2. Batch Size: 32 3. Evaluation Steps: 1000 4. Epochs: 1(BERT), 2(RoBERTa) - Continued Training STS 1. Pooling Method: MEAN strategy 2. Batch Size: 32 3. Evaluation Steps: 1000 4. Epochs: 4 ### Semantic Search ``` python SemanticSearch.py ``` ```python from sentence_transformers import SentenceTransformer, util import numpy as np model_path = '../Checkpoint/KoSBERT/kosbert-klue-bert-base' embedder = SentenceTransformer(model_path) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.'] corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True) # Query sentences: queries = ['한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] # Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity top_k = 5 for query in queries: query_embedding = embedder.encode(query, convert_to_tensor=True) cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0] cos_scores = cos_scores.cpu() #We use np.argpartition, to only partially sort the top_k results top_results = np.argpartition(-cos_scores, range(top_k))[0:top_k] print("\n\n======================\n\n") print("Query:", query) print("\nTop 5 most similar sentences in corpus:") for idx in top_results[0:top_k]: print(corpus[idx].strip(), "(Score: %.4f)" % (cos_scores[idx])) ``` - Results are as follows : ``` Query: 한 남자가 파스타를 먹는다. Top 5 most similar sentences in corpus: 한 남자가 음식을 먹는다. (Score: 0.6141) 한 남자가 빵 한 조각을 먹는다. (Score: 0.5952) 한 남자가 말을 탄다. (Score: 0.1231) 한 남자가 담으로 싸인 땅에서 백마를 타고 있다. (Score: 0.0752) 두 남자가 수레를 숲 솦으로 밀었다. (Score: 0.0486) ====================== Query: 고릴라 의상을 입은 누군가가 드럼을 연주하고 있다. Top 5 most similar sentences in corpus: 원숭이 한 마리가 드럼을 연주한다. (Score: 0.6656) 치타 한 마리가 먹이 뒤에서 달리고 있다. (Score: 0.2988) 한 여자가 바이올린을 연주한다. (Score: 0.1566) 한 남자가 말을 탄다. (Score: 0.1112) 한 남자가 담으로 싸인 땅에서 백마를 타고 있다. (Score: 0.0262) ====================== Query: 치타가 들판을 가로 질러 먹이를 쫓는다. Top 5 most similar sentences in corpus: 치타 한 마리가 먹이 뒤에서 달리고 있다. (Score: 0.7570) 두 남자가 수레를 숲 솦으로 밀었다. (Score: 0.3658) 원숭이 한 마리가 드럼을 연주한다. (Score: 0.3583) 한 남자가 말을 탄다. (Score: 0.0505) 그 여자가 아이를 돌본다. (Score: -0.0087) ``` ### Clustering ``` python Clustering.py ``` ```python from sentence_transformers import SentenceTransformer, util import numpy as np model_path = '../Checkpoint/KoSBERT/kosbert-klue-bert-base' embedder = SentenceTransformer(model_path) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.', '한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] corpus_embeddings = embedder.encode(corpus) # Then, we perform k-means clustering using sklearn: from sklearn.cluster import KMeans num_clusters = 5 clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(corpus_embeddings) cluster_assignment = clustering_model.labels_ clustered_sentences = [[] for i in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(corpus[sentence_id]) for i, cluster in enumerate(clustered_sentences): print("Cluster ", i+1) print(cluster) print("") ``` - Results are as follows: ``` Cluster 1 ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '한 남자가 파스타를 먹는다.'] Cluster 2 ['원숭이 한 마리가 드럼을 연주한다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.'] Cluster 3 ['한 남자가 말을 탄다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.'] Cluster 4 ['치타 한 마리가 먹이 뒤에서 달리고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] Cluster 5 ['그 여자가 아이를 돌본다.', '한 여자가 바이올린을 연주한다.'] ``` ================================================ FILE: KoSBERT/SemanticSearch.py ================================================ from sentence_transformers import SentenceTransformer, util import numpy as np model_path = '../Checkpoint/KoSBERT/kosbert-klue-bert-base' embedder = SentenceTransformer(model_path) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.'] corpus_embeddings = embedder.encode(corpus, convert_to_tensor=True) # Query sentences: queries = ['한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] # Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity top_k = 5 for query in queries: query_embedding = embedder.encode(query, convert_to_tensor=True) cos_scores = util.pytorch_cos_sim(query_embedding, corpus_embeddings)[0] cos_scores = cos_scores.cpu() #We use np.argpartition, to only partially sort the top_k results top_results = np.argpartition(-cos_scores, range(top_k))[0:top_k] print("\n\n======================\n\n") print("Query:", query) print("\nTop 5 most similar sentences in corpus:") for idx in top_results[0:top_k]: print(corpus[idx].strip(), "(Score: %.4f)" % (cos_scores[idx])) ================================================ FILE: KoSBERT/con_training_sts.py ================================================ from torch.utils.data import DataLoader import math from sentence_transformers import SentenceTransformer, SentencesDataset, LoggingHandler, losses, util, InputExample from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator import logging from datetime import datetime import os import gzip import csv import argparse parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, default='klue/bert-base') parser.add_argument('--batch', type=int, default=32) parser.add_argument('--evaluation_steps', type=int, default=1000) parser.add_argument('--epochs', type=int, default=4) args = parser.parse_args() logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) model_name = './output/training_nli_'+args.model.replace("/", "-") train_batch_size = args.batch num_epochs = args.epochs model_save_path = 'output/kosbert-'+args.model.replace("/", "-") model = SentenceTransformer(model_name) logging.info("Read STSbenchmark train dataset") train_samples = [] dev_samples = [] test_samples = [] with open('../Dataset/tune_sts_dev.tsv', 'rt', encoding='utf-8') as fIn: lines = fIn.readlines() for line in lines: s1, s2, score = line.split('\t') score = score.strip() score = float(score) / 5.0 dev_samples.append(InputExample(texts= [s1,s2], label=score)) with open('../Dataset/tune_sts_test.tsv', 'rt', encoding='utf-8') as fIn: lines = fIn.readlines() for line in lines: s1, s2, score = line.split('\t') score = score.strip() score = float(score) / 5.0 test_samples.append(InputExample(texts= [s1,s2], label=score)) with open('../Dataset/tune_sts_train.tsv', 'rt', encoding='utf-8') as fIn: lines = fIn.readlines() for line in lines: s1, s2, score = line.split('\t') score = score.strip() score = float(score) / 5.0 train_samples.append(InputExample(texts= [s1,s2], label=score)) train_dataset = SentencesDataset(train_samples, model) train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=train_batch_size) train_loss = losses.CosineSimilarityLoss(model=model) # Development set: Measure correlation between cosine score and gold labels logging.info("Read STSbenchmark dev dataset") evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name='sts-dev') warmup_steps = math.ceil(len(train_dataset) * num_epochs / train_batch_size * 0.1) #10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the model model.fit(train_objectives=[(train_dataloader, train_loss)], evaluator=evaluator, epochs=num_epochs, evaluation_steps=args.evaluation_steps, warmup_steps=warmup_steps, output_path=model_save_path) ############################################################################## # # Load the stored model and evaluate its performance on STS benchmark dataset # ############################################################################## model = SentenceTransformer(model_save_path) test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name='sts-test') test_evaluator(model, output_path=model_save_path) ================================================ FILE: KoSBERT/output/empty.txt ================================================ . ================================================ FILE: KoSBERT/run_example.sh ================================================ #!/bin/bash # bert-base echo "First Step Training NLI Dataset (BERT-BASE)" CUDA_VISIBLE_DEVICES=0 python training_nli.py --model klue/bert-base --batch 32 --evaluation_steps 1000 --epochs 1 echo "Second Step Continuously Training STS Dataset (BERT-BASE)" CUDA_VISIBLE_DEVICES=0 python con_training_sts.py --model klue/bert-base --batch 32 --evaluation_steps 1000 --epochs 4 # roberta-base echo "First Step Training NLI Dataset (ROBERTA-BASE)" CUDA_VISIBLE_DEVICES=0 python training_nli.py --model klue/roberta-base --batch 32 --evaluation_steps 1000 --epochs 1 echo "Second Step Continuously Training STS Dataset (ROBERTA-BASE)" CUDA_VISIBLE_DEVICES=0 python con_training_sts.py --model klue/roberta-base --batch 32 --evaluation_steps 1000 --epochs 4 # roberta-large echo "First Step Training NLI Dataset (ROBERAT-LARGE)" CUDA_VISIBLE_DEVICES=0 python training_nli.py --model klue/roberta-large --batch 32 --evaluation_steps 1000 --epochs 1 echo "Second Step Continuously Training STS Dataset (ROBERTA-LARGE)" CUDA_VISIBLE_DEVICES=0 python con_training_sts.py --model klue/roberta-large --batch 32 --evaluation_steps 1000 --epochs 4 ================================================ FILE: KoSBERT/training_nli.py ================================================ from torch.utils.data import DataLoader import math from sentence_transformers import models, losses from sentence_transformers import SentencesDataset, LoggingHandler, SentenceTransformer, util, InputExample from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator import logging from datetime import datetime import sys import os import gzip import csv import argparse parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, default='klue/bert-base') parser.add_argument('--batch', type=int, default=32) parser.add_argument('--evaluation_steps', type=int, default=1000) parser.add_argument('--epochs', type=int, default=1) args = parser.parse_args() model_name = args.model train_batch_size = args.batch model_save_path = 'output/training_nli_'+model_name.replace("/", "-")#+'-'+datetime.now().strftime("%Y-%m-%d_%H-%M-%S") word_embedding_model = models.Transformer(model_name) # Apply mean pooling to get one fixed sized sentence vector pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(), pooling_mode_mean_tokens=True, pooling_mode_cls_token=False, pooling_mode_max_tokens=False) model = SentenceTransformer(modules=[word_embedding_model, pooling_model]) logging.info("Read AllNLI train dataset") label2int = {"contradiction": 0, "entailment": 1, "neutral": 2} train_samples = [] with open('../Dataset/snli_1.0_train.ko.tsv', "rt", encoding="utf-8") as fIn: lines = fIn.readlines() for line in lines: s1, s2, label = line.split('\t') label = label2int[label.strip()] train_samples.append(InputExample(texts=[s1, s2], label=label)) train_dataset = SentencesDataset(train_samples, model=model) train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=train_batch_size) train_loss = losses.SoftmaxLoss(model=model, sentence_embedding_dimension=model.get_sentence_embedding_dimension(), num_labels=len(label2int)) #Read STSbenchmark dataset and use it as development set logging.info("Read STSbenchmark dev dataset") dev_samples = [] with open('../Dataset/tune_sts_dev.tsv', 'rt', encoding='utf-8') as fIn: lines = fIn.readlines() for line in lines: s1, s2, score = line.split('\t') score = score.strip() score = float(score) / 5.0 dev_samples.append(InputExample(texts= [s1,s2], label=score)) dev_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, batch_size=train_batch_size, name='sts-dev') num_epochs = args.epochs warmup_steps = math.ceil(len(train_dataset) * num_epochs / train_batch_size * 0.1) #10% of train data for warm-up logging.info("Warmup-steps: {}".format(warmup_steps)) # Train the model model.fit(train_objectives=[(train_dataloader, train_loss)], evaluator=dev_evaluator, epochs=num_epochs, evaluation_steps=args.evaluation_steps, warmup_steps=warmup_steps, output_path=model_save_path ) ############################################################################## # # Load the stored model and evaluate its performance on STS benchmark dataset # ############################################################################## test_samples = [] with open('../Dataset/tune_sts_test.tsv', 'rt', encoding='utf-8') as fIn: lines = fIn.readlines() for line in lines: s1, s2, score = line.split('\t') score = score.strip() score = float(score) / 5.0 test_samples.append(InputExample(texts=[s1,s2], label=score)) print("\n\n\n") print("======================TEST===================") print("\n\n\n") model = SentenceTransformer(model_save_path) print(f"model save path > {model_save_path}") test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, batch_size=train_batch_size, name='sts-test') test_evaluator(model, output_path=model_save_path) ================================================ FILE: KoSentenceT5/README.md ================================================ # KoSentenceT5 KoSentenceT5 : Korean Sentence Embeddings using T5.
> **Warning**
> This repository uses ETRI-T5 model and does not provide it. You can download T5 model from [here](https://aiopen.etri.re.kr/service_dataset.php). ## Training - Before training or evaluation, please download the datasets by running ``` bash get_model_dataset.sh ``` ### Train KoSentenceT5 ``` python main.py \ --model etri-t5 \ --multi_gpu True \ --test False \ --max_len 110 \ --batch_size 64 \ --epochs 2 \ --eval_steps 125 \ --lr 0.0001 \ --warmup_ratio 0.01 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --train_data train_nli.tsv \ --valid_data valid_sts.tsv ``` ### Evaluation ``` python main.py \ --model etri-t5 \ --train False \ --test True \ --max_len 110 \ --batch_size 64 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --test_data test_sts.tsv \ ``` ### Run Examples ``` bash run_example.sh ``` ================================================ FILE: KoSentenceT5/apex/RNN/README.md ================================================ Under construction... ================================================ FILE: KoSentenceT5/apex/RNN/RNNBackend.py ================================================ import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import math def is_iterable(maybe_iterable): return isinstance(maybe_iterable, list) or isinstance(maybe_iterable, tuple) def flatten_list(tens_list): """ flatten_list """ if not is_iterable(tens_list): return tens_list return torch.cat(tens_list, dim=0).view(len(tens_list), *tens_list[0].size() ) #These modules always assumes batch_first class bidirectionalRNN(nn.Module): """ bidirectionalRNN """ def __init__(self, inputRNN, num_layers=1, dropout = 0): super(bidirectionalRNN, self).__init__() self.dropout = dropout self.fwd = stackedRNN(inputRNN, num_layers=num_layers, dropout = dropout) self.bckwrd = stackedRNN(inputRNN.new_like(), num_layers=num_layers, dropout = dropout) self.rnns = nn.ModuleList([self.fwd, self.bckwrd]) #collect hidden option will return all hidden/cell states from entire RNN def forward(self, input, collect_hidden=False): """ forward() """ seq_len = input.size(0) bsz = input.size(1) fwd_out, fwd_hiddens = list(self.fwd(input, collect_hidden = collect_hidden)) bckwrd_out, bckwrd_hiddens = list(self.bckwrd(input, reverse=True, collect_hidden = collect_hidden)) output = torch.cat( [fwd_out, bckwrd_out], -1 ) hiddens = tuple( torch.cat(hidden, -1) for hidden in zip( fwd_hiddens, bckwrd_hiddens) ) return output, hiddens def reset_parameters(self): """ reset_parameters() """ for rnn in self.rnns: rnn.reset_parameters() def init_hidden(self, bsz): """ init_hidden() """ for rnn in self.rnns: rnn.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for rnn in self.rnns: rnn.detachHidden() def reset_hidden(self, bsz): """ reset_hidden() """ for rnn in self.rnns: rnn.reset_hidden(bsz) def init_inference(self, bsz): """ init_inference() """ for rnn in self.rnns: rnn.init_inference(bsz) #assumes hidden_state[0] of inputRNN is output hidden state #constructor either takes an RNNCell or list of RNN layers class stackedRNN(nn.Module): """ stackedRNN """ def __init__(self, inputRNN, num_layers=1, dropout=0): super(stackedRNN, self).__init__() self.dropout = dropout if isinstance(inputRNN, RNNCell): self.rnns = [inputRNN] for i in range(num_layers-1): self.rnns.append(inputRNN.new_like(inputRNN.output_size)) elif isinstance(inputRNN, list): assert len(inputRNN) == num_layers, "RNN list length must be equal to num_layers" self.rnns=inputRNN else: raise RuntimeError() self.nLayers = len(self.rnns) self.rnns = nn.ModuleList(self.rnns) ''' Returns output as hidden_state[0] Tensor([sequence steps][batch size][features]) If collect hidden will also return Tuple( [n_hidden_states][sequence steps] Tensor([layer][batch size][features]) ) If not collect hidden will also return Tuple( [n_hidden_states] Tensor([layer][batch size][features]) ''' def forward(self, input, collect_hidden=False, reverse=False): """ forward() """ seq_len = input.size(0) bsz = input.size(1) inp_iter = reversed(range(seq_len)) if reverse else range(seq_len) hidden_states = [[] for i in range(self.nLayers)] outputs = [] for seq in inp_iter: for layer in range(self.nLayers): if layer == 0: prev_out = input[seq] outs = self.rnns[layer](prev_out) if collect_hidden: hidden_states[layer].append(outs) elif seq == seq_len-1: hidden_states[layer].append(outs) prev_out = outs[0] outputs.append(prev_out) if reverse: outputs = list(reversed(outputs)) ''' At this point outputs is in format: list( [seq_length] x Tensor([bsz][features]) ) need to convert it to: list( Tensor([seq_length][bsz][features]) ) ''' output = flatten_list(outputs) ''' hidden_states at this point is in format: list( [layer][seq_length][hidden_states] x Tensor([bsz][features]) ) need to convert it to: For not collect hidden: list( [hidden_states] x Tensor([layer][bsz][features]) ) For collect hidden: list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) ) ''' if not collect_hidden: seq_len = 1 n_hid = self.rnns[0].n_hidden_states new_hidden = [ [ [ None for k in range(self.nLayers)] for j in range(seq_len) ] for i in range(n_hid) ] for i in range(n_hid): for j in range(seq_len): for k in range(self.nLayers): new_hidden[i][j][k] = hidden_states[k][j][i] hidden_states = new_hidden #Now in format list( [hidden_states][seq_length][layer] x Tensor([bsz][features]) ) #Reverse seq_length if reverse if reverse: hidden_states = list( list(reversed(list(entry))) for entry in hidden_states) #flatten layer dimension into tensor hiddens = list( list( flatten_list(seq) for seq in hidden ) for hidden in hidden_states ) #Now in format list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) ) #Remove seq_length dimension if not collect_hidden if not collect_hidden: hidden_states = list( entry[0] for entry in hidden_states) return output, hidden_states def reset_parameters(self): """ reset_parameters() """ for rnn in self.rnns: rnn.reset_parameters() def init_hidden(self, bsz): """ init_hidden() """ for rnn in self.rnns: rnn.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for rnn in self.rnns: rnn.detach_hidden() def reset_hidden(self, bsz): """ reset_hidden() """ for rnn in self.rnns: rnn.reset_hidden(bsz) def init_inference(self, bsz): """ init_inference() """ for rnn in self.rnns: rnn.init_inference(bsz) class RNNCell(nn.Module): """ RNNCell gate_multiplier is related to the architecture you're working with For LSTM-like it will be 4 and GRU-like will be 3. Always assumes input is NOT batch_first. Output size that's not hidden size will use output projection Hidden_states is number of hidden states that are needed for cell if one will go directly to cell as tensor, if more will go as list """ def __init__(self, gate_multiplier, input_size, hidden_size, cell, n_hidden_states = 2, bias = False, output_size = None): super(RNNCell, self).__init__() self.gate_multiplier = gate_multiplier self.input_size = input_size self.hidden_size = hidden_size self.cell = cell self.bias = bias self.output_size = output_size if output_size is None: self.output_size = hidden_size self.gate_size = gate_multiplier * self.hidden_size self.n_hidden_states = n_hidden_states self.w_ih = nn.Parameter(torch.Tensor(self.gate_size, self.input_size)) self.w_hh = nn.Parameter(torch.Tensor(self.gate_size, self.output_size)) #Check if there's recurrent projection if(self.output_size != self.hidden_size): self.w_ho = nn.Parameter(torch.Tensor(self.output_size, self.hidden_size)) self.b_ih = self.b_hh = None if self.bias: self.b_ih = nn.Parameter(torch.Tensor(self.gate_size)) self.b_hh = nn.Parameter(torch.Tensor(self.gate_size)) #hidden states for forward self.hidden = [ None for states in range(self.n_hidden_states)] self.reset_parameters() def new_like(self, new_input_size=None): """ new_like() """ if new_input_size is None: new_input_size = self.input_size return type(self)(self.gate_multiplier, new_input_size, self.hidden_size, self.cell, self.n_hidden_states, self.bias, self.output_size) #Use xavier where we can (weights), otherwise use uniform (bias) def reset_parameters(self, gain=1): """ reset_parameters() """ stdev = 1.0 / math.sqrt(self.hidden_size) for param in self.parameters(): param.data.uniform_(-stdev, stdev) ''' Xavier reset: def reset_parameters(self, gain=1): stdv = 1.0 / math.sqrt(self.gate_size) for param in self.parameters(): if (param.dim() > 1): torch.nn.init.xavier_normal(param, gain) else: param.data.uniform_(-stdv, stdv) ''' def init_hidden(self, bsz): """ init_hidden() """ for param in self.parameters(): if param is not None: a_param = param break for i, _ in enumerate(self.hidden): if(self.hidden[i] is None or self.hidden[i].data.size()[0] != bsz): if i==0: hidden_size = self.output_size else: hidden_size = self.hidden_size tens = a_param.data.new(bsz, hidden_size).zero_() self.hidden[i] = Variable(tens, requires_grad=False) def reset_hidden(self, bsz): """ reset_hidden() """ for i, _ in enumerate(self.hidden): self.hidden[i] = None self.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for i, _ in enumerate(self.hidden): if self.hidden[i] is None: raise RuntimeError("Must initialize hidden state before you can detach it") for i, _ in enumerate(self.hidden): self.hidden[i] = self.hidden[i].detach() def forward(self, input): """ forward() if not inited or bsz has changed this will create hidden states """ self.init_hidden(input.size()[0]) hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden self.hidden = self.cell(input, hidden_state, self.w_ih, self.w_hh, b_ih=self.b_ih, b_hh=self.b_hh) if(self.n_hidden_states > 1): self.hidden = list(self.hidden) else: self.hidden=[self.hidden] if self.output_size != self.hidden_size: self.hidden[0] = F.linear(self.hidden[0], self.w_ho) return tuple(self.hidden) ================================================ FILE: KoSentenceT5/apex/RNN/__init__.py ================================================ from .models import LSTM, GRU, ReLU, Tanh, mLSTM __all__ = ['models'] ================================================ FILE: KoSentenceT5/apex/RNN/cells.py ================================================ import torch import torch.nn as nn import torch.nn.functional as F from .RNNBackend import RNNCell from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend import math class mLSTMRNNCell(RNNCell): """ mLSTMRNNCell """ def __init__(self, input_size, hidden_size, bias = False, output_size = None): gate_multiplier = 4 super(mLSTMRNNCell, self).__init__(gate_multiplier, input_size, hidden_size, mLSTMCell, n_hidden_states = 2, bias = bias, output_size = output_size) self.w_mih = nn.Parameter(torch.Tensor(self.output_size, self.input_size)) self.w_mhh = nn.Parameter(torch.Tensor(self.output_size, self.output_size)) self.reset_parameters() def forward(self, input): """ mLSTMRNNCell.forward() """ #if not inited or bsz has changed this will create hidden states self.init_hidden(input.size()[0]) hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden self.hidden = list( self.cell(input, hidden_state, self.w_ih, self.w_hh, self.w_mih, self.w_mhh, b_ih=self.b_ih, b_hh=self.b_hh) ) if self.output_size != self.hidden_size: self.hidden[0] = F.linear(self.hidden[0], self.w_ho) return tuple(self.hidden) def new_like(self, new_input_size=None): if new_input_size is None: new_input_size = self.input_size return type(self)( new_input_size, self.hidden_size, self.bias, self.output_size) def mLSTMCell(input, hidden, w_ih, w_hh, w_mih, w_mhh, b_ih=None, b_hh=None): """ mLSTMCell """ if input.is_cuda: igates = F.linear(input, w_ih) m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh) hgates = F.linear(m, w_hh) state = fusedBackend.LSTMFused.apply return state(igates, hgates, hidden[1], b_ih, b_hh) hx, cx = hidden m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh) gates = F.linear(input, w_ih, b_ih) + F.linear(m, w_hh, b_hh) ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1) ingate = F.sigmoid(ingate) forgetgate = F.sigmoid(forgetgate) cellgate = F.tanh(cellgate) outgate = F.sigmoid(outgate) cy = (forgetgate * cx) + (ingate * cellgate) hy = outgate * F.tanh(cy) return hy, cy ================================================ FILE: KoSentenceT5/apex/RNN/models.py ================================================ import torch from torch.nn._functions.rnn import LSTMCell, RNNReLUCell, RNNTanhCell, GRUCell from .RNNBackend import bidirectionalRNN, stackedRNN, RNNCell from .cells import mLSTMRNNCell, mLSTMCell def toRNNBackend(inputRNN, num_layers, bidirectional=False, dropout = 0): """ :class:`toRNNBackend` """ if bidirectional: return bidirectionalRNN(inputRNN, num_layers, dropout = dropout) else: return stackedRNN(inputRNN, num_layers, dropout = dropout) def LSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`LSTM` """ inputRNN = RNNCell(4, input_size, hidden_size, LSTMCell, 2, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def GRU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`GRU` """ inputRNN = RNNCell(3, input_size, hidden_size, GRUCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def ReLU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`ReLU` """ inputRNN = RNNCell(1, input_size, hidden_size, RNNReLUCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def Tanh(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`Tanh` """ inputRNN = RNNCell(1, input_size, hidden_size, RNNTanhCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def mLSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`mLSTM` """ inputRNN = mLSTMRNNCell(input_size, hidden_size, bias=bias, output_size=output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) ================================================ FILE: KoSentenceT5/apex/__init__.py ================================================ # May help avoid undefined symbol errors https://pytorch.org/cppdocs/notes/faq.html#undefined-symbol-errors-from-pytorch-aten import torch import warnings if torch.distributed.is_available(): from . import parallel from . import amp from . import fp16_utils # For optimizers and normalization there is no Python fallback. # Absence of cuda backend is a hard error. # I would like the errors from importing fused_adam_cuda or fused_layer_norm_cuda # to be triggered lazily, because if someone has installed with --cpp_ext and --cuda_ext # so they expect those backends to be available, but for some reason they actually aren't # available (for example because they built improperly in a way that isn't revealed until # load time) the error message is timely and visible. from . import optimizers from . import normalization from . import pyprof ================================================ FILE: KoSentenceT5/apex/amp/README.md ================================================ # amp: Automatic Mixed Precision ## Annotating User Functions Nearly all PyTorch user code needs nothing more than the two steps above to use amp. After all, custom layers are built out of simpler PyTorch components, and amp already can see those. However, any custom C++ or CUDA code is outside of amp's (default) view of things. For example, suppose I implemented a new recurrent cell called a "forgetful recurrent unit" that calls directly into a CUDA backend: ```python from backend import FRUBackend def fru(input, hidden, weight, bias): # call to CUDA code FRUBackend(input, hidden, weight, bias) ``` In this case, it is possible to get a runtime type mismatch. For example, you might have `input` in fp16, and `weight` in fp32, and amp doesn't have the visibility to insert an appropriate cast. amp exposes two ways to handle "invisible" backend code: function annotations and explicit registration. #### Function annotation The first way to handle backend code is a set of function annotations: - `@amp.half_function` - `@amp.float_function` - `@amp.promote_function` These correspond to: - Cast all arguments to fp16 - Cast all argumnets fo fp32 - If there are any type mismatches, cast everything to the widest type In our example, we believe that the FRU unit is fp16-safe and will get performance gains from casting its arguments to fp16, so we write: ```python @amp.half_function def fru(input, hidden, weight, bias): #... ``` #### Explicit registration The other way to handle backend code is with explicit function registration: - `amp.register_half_function(module, function_name)` - `amp.register_float_function(module, function_name)` - `amp.register_promote_function(module, function_name)` When using this API, `module` is the containing class or module for the function, and `function_name` is the _string_ name of the function. Note that the function must be registered before the call to `amp.initalize()`. For our FRU unit, we can register the backend function directly: ```python import backend amp.register_half_function(backend, 'FRUBackend') ``` ================================================ FILE: KoSentenceT5/apex/amp/__init__.py ================================================ from .amp import init, half_function, float_function, promote_function,\ register_half_function, register_float_function, register_promote_function from .handle import scale_loss, disable_casts from .frontend import initialize, state_dict, load_state_dict from ._amp_state import master_params, _amp_state ================================================ FILE: KoSentenceT5/apex/amp/__version__.py ================================================ VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) ================================================ FILE: KoSentenceT5/apex/amp/_amp_state.py ================================================ # This is a "header object" that allows different amp modules to communicate. # I'm a C++ guy, not a python guy. I decided this approach because it seemed most C++-like. # But apparently it's ok: # http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm import os import torch TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 1 and TORCH_MINOR < 8: from torch._six import container_abcs else: import collections.abc as container_abcs class AmpState(object): def __init__(self): self.hard_override=False self.allow_incoming_model_not_fp32 = False self.verbosity=1 # Attribute stash. Could also just stash things as global module attributes. _amp_state = AmpState() def warn_or_err(msg): if _amp_state.hard_override: print("Warning: " + msg) else: raise RuntimeError(msg) # I'm not sure if allowing hard_override is a good idea. # + " If you're sure you know what you're doing, supply " + # "hard_override=True to amp.initialize.") def maybe_print(msg, rank0=False): distributed = torch.distributed.is_available() and \ torch.distributed.is_initialized() and \ torch.distributed.get_world_size() > 1 if _amp_state.verbosity > 0: if rank0: if distributed: if torch.distributed.get_rank() == 0: print(msg) else: print(msg) else: print(msg) # def iter_params(param_groups): # for group in param_groups: # for p in group['params']: # yield p def master_params(optimizer): """ Generator expression that iterates over the params owned by ``optimizer``. Args: optimizer: An optimizer previously returned from ``amp.initialize``. """ for group in optimizer.param_groups: for p in group['params']: yield p ================================================ FILE: KoSentenceT5/apex/amp/_initialize.py ================================================ import torch from torch._six import string_classes import functools import numpy as np import sys from types import MethodType import warnings from ._amp_state import _amp_state, warn_or_err, container_abcs from .handle import disable_casts from .scaler import LossScaler from ._process_optimizer import _process_optimizer from apex.fp16_utils import convert_network from ..fp16_utils import FP16_Optimizer as FP16_Optimizer_general from ..contrib.optimizers import FP16_Optimizer as FP16_Optimizer_for_fused if torch.distributed.is_available(): from ..parallel import DistributedDataParallel as apex_DDP from ..parallel.LARC import LARC def to_type(dtype, t): if isinstance(t, torch.Tensor): if not t.is_cuda: # This should not be a hard error, since it may be legitimate. warnings.warn("An input tensor was not cuda.") # GANs require this. # if t.requires_grad: # warn_or_err("input data requires grad. Since input data is not a model parameter,\n" # "its gradients will not be properly allreduced by DDP.") if t.is_floating_point(): return t.to(dtype) return t else: # Trust the user's custom batch type, that's all I can do here. return t.to(dtype) # Modified from torch.optim.optimizer.py. This is a bit more general than casted_args in utils.py. def applier(value, fn): if isinstance(value, torch.Tensor): return fn(value) elif isinstance(value, string_classes): return value elif isinstance(value, np.ndarray): return value elif hasattr(value, "to"): # Allow handling of custom batch classes return fn(value) elif isinstance(value, container_abcs.Mapping): return {applier(k, fn) : applier(v, fn) for k, v in value.items()} elif isinstance(value, container_abcs.Iterable): return type(value)(applier(v, fn) for v in value) else: # Do I want this to fire off even if someone chooses to pass something ordinary like # an int or float? May be more annoying than it's worth. # print("Warning: unrecognized type in applier. If your input data is a custom class, " # "provide it with a .to(dtype) method which converts its floating-point Tensors to dtype. " # "Amp will check for your custom to() and invoke it to cast the batch's " # "floating-point Tensors to the appropriate type. " # "Also, if your data is a custom class, it is your responsibility to ensure that " # "any Tensors you want to be cuda are already cuda." return value def check_models(models): for model in models: parallel_type = None if isinstance(model, torch.nn.parallel.DistributedDataParallel): parallel_type = "torch.nn.parallel.DistributedDataParallel" if ('apex_DDP' in sys.modules) and isinstance(model, apex_DDP): parallel_type = "apex.parallel.DistributedDataParallel" if isinstance(model, torch.nn.parallel.DataParallel): parallel_type = "torch.nn.parallel.DataParallel" if parallel_type is not None: raise RuntimeError("Incoming model is an instance of {}. ".format(parallel_type) + "Parallel wrappers should only be applied to the model(s) AFTER \n" "the model(s) have been returned from amp.initialize.") def check_params_fp32(models): for model in models: for name, param in model.named_parameters(): if param.is_floating_point(): if 'Half' in param.type(): warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you do not need to call .half() on your model\n" "before passing it, no matter what optimization level you choose.".format( name, param.type())) elif not param.is_cuda: warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you need to provide a model with parameters\n" "located on a CUDA device before passing it no matter what optimization level\n" "you chose. Use model.to('cuda') to use the default device.".format( name, param.type())) # Backward compatibility for PyTorch 0.4 if hasattr(model, 'named_buffers'): buf_iter = model.named_buffers() else: buf_iter = model._buffers for obj in buf_iter: if type(obj)==tuple: name, buf = obj else: name, buf = obj, buf_iter[obj] if buf.is_floating_point(): if 'Half' in buf.type(): warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you do not need to call .half() on your model\n" "before passing it, no matter what optimization level you choose.".format( name, buf.type())) elif not buf.is_cuda: warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you need to provide a model with buffers\n" "located on a CUDA device before passing it no matter what optimization level\n" "you chose. Use model.to('cuda') to use the default device.".format( name, buf.type())) def check_optimizers(optimizers): for optim in optimizers: bad_optim_type = None if isinstance(optim, FP16_Optimizer_general): bad_optim_type = "apex.fp16_utils.FP16_Optimizer" if isinstance(optim, FP16_Optimizer_for_fused): bad_optim_type = "apex.optimizers.FP16_Optimizer" if bad_optim_type is not None: raise RuntimeError("An incoming optimizer is an instance of {}. ".format(bad_optim_type) + "The optimizer(s) passed to amp.initialize() must be bare \n" "instances of either ordinary Pytorch optimizers, or Apex fused \n" "optimizers.\n") class O2StateDictHook(object): def __init__(self, fn): self.fn = fn def __call__(self, module, state_dict, prefix, local_metadata): for key in state_dict: param = state_dict[key] if 'Half' in param.type(): param = param.to(torch.float32) state_dict[key] = param def _initialize(models, optimizers, properties, num_losses=1, cast_model_outputs=None): from .amp import init as amp_init optimizers_was_list = False if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)): optimizers = [optimizers] elif optimizers is None: optimizers = [] elif isinstance(optimizers, list): optimizers_was_list = True check_optimizers(optimizers) else: check_optimizers([optimizers]) raise TypeError("optimizers must be either a single optimizer or a list of optimizers.") if isinstance(models, torch.nn.Module): models_was_list = False models = [models] elif isinstance(models, list): models_was_list = True else: raise TypeError("models must be either a single model or a list of models.") check_models(models) if not _amp_state.allow_incoming_model_not_fp32: check_params_fp32(models) # In the future, when FP16_Optimizer can be deprecated and master weights can # become an attribute, remember to stash master weights before casting the model. if properties.cast_model_type: if properties.keep_batchnorm_fp32: for model in models: convert_network(model, properties.cast_model_type) else: for model in models: model.to(properties.cast_model_type) input_caster = functools.partial(to_type, properties.cast_model_type) if cast_model_outputs is not None: output_caster = functools.partial(to_type, cast_model_outputs) else: output_caster = functools.partial(to_type, torch.float32) for model in models: # Patch the forward method to cast incoming data to the correct type, and # outgoing data to float32, so "the user never needs to call .half()." # I like writing things explicitly more than decorators. def patch_forward(old_fwd): def new_fwd(*args, **kwargs): output = old_fwd(*applier(args, input_caster), **applier(kwargs, input_caster)) return applier(output, output_caster) return new_fwd model.forward = patch_forward(model.forward) # State dict trick to recast any preexisting per-param state tensors for optimizer in optimizers: optimizer.load_state_dict(optimizer.state_dict()) # patch model.state_dict() to return float32 params for model in models: for module in model.modules(): module._register_state_dict_hook(O2StateDictHook(functools.partial(to_type, torch.float32))) elif cast_model_outputs is not None: output_caster = functools.partial(to_type, cast_model_outputs) for model in models: def patch_forward(old_fwd): def new_fwd(*args, **kwargs): output = old_fwd(*args, **kwargs) return applier(output, output_caster) return new_fwd model.forward = patch_forward(model.forward) for i, optimizer in enumerate(optimizers): optimizers[i] = _process_optimizer(optimizer, properties) _amp_state.loss_scalers = [] for _ in range(num_losses): _amp_state.loss_scalers.append(LossScaler(properties.loss_scale, min_loss_scale=_amp_state.min_loss_scale, max_loss_scale=_amp_state.max_loss_scale)) if properties.patch_torch_functions: # handle is unused here. It's accessible later through a global value anyway. handle = amp_init(loss_scale=properties.loss_scale, verbose=(_amp_state.verbosity == 2)) for optimizer in optimizers: # Disable Amp casting for the optimizer step, because it should only be # applied to FP32 master params anyway. def patch_step(old_step): def new_step(self, *args, **kwargs): with disable_casts(): output = old_step(*args, **kwargs) return output return new_step optimizer.step = MethodType(patch_step(optimizer.step), optimizer) if optimizers_was_list: if models_was_list: return models, optimizers else: return models[0], optimizers else: if models_was_list: if len(optimizers) == 0: return models else: return models, optimizers[0] else: if len(optimizers) == 0: return models[0] else: return models[0], optimizers[0] ================================================ FILE: KoSentenceT5/apex/amp/_process_optimizer.py ================================================ import types from ..fp16_utils import master_params_to_model_params from ..multi_tensor_apply import multi_tensor_applier from ._amp_state import maybe_print import torch from ..optimizers import FusedSGD class AmpOptimizerState(object): def __init__(self): pass def _master_params_to_model_params(self): stash = self._amp_stash if multi_tensor_applier.available: if len(stash.all_fp16_params) > 0: multi_tensor_applier( stash.multi_tensor_scale, stash.dummy_overflow_buf, [stash.all_fp32_from_fp16_params, stash.all_fp16_params], 1.0) else: for fp16_group, fp32_from_fp16_group in zip(stash.fp16_groups, stash.fp32_from_fp16_groups): master_params_to_model_params(fp16_group, fp32_from_fp16_group) def lazy_init_with_master_weights(self): stash = self._amp_stash stash.fp16_groups = [] stash.fp32_from_fp16_groups = [] stash.fp32_from_fp32_groups = [] for i, param_group in enumerate(self.param_groups): # maybe_print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(param_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': # maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}" # .format(param.size())) fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True param_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) # Reset existing state dict key to the new master param. # We still need to recast per-param state tensors, if any, to FP32. if param in self.state: self.state[master_param] = self.state.pop(param) elif param.type() == 'torch.cuda.FloatTensor': # maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}" # .format(param.size())) fp32_params_this_group.append(param) param_group['params'][i] = param else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.fp16_groups.append(fp16_params_this_group) stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) stash.fp32_from_fp32_groups.append(fp32_params_this_group) stash.all_fp16_params = [] for group in stash.fp16_groups: stash.all_fp16_params += group stash.all_fp32_from_fp16_params = [] for group in stash.fp32_from_fp16_groups: stash.all_fp32_from_fp16_params += group stash.all_fp32_from_fp32_params = [] for group in stash.fp32_from_fp32_groups: stash.all_fp32_from_fp32_params += group # all_fp16_grad_stash is only needed for fused optimizers. stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params] # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params] stash.all_fp32_from_fp32_grad_stash = [None for _ in stash.all_fp32_from_fp32_params] for param in stash.all_fp32_from_fp16_params: param.grad = None for param in stash.all_fp32_from_fp32_params: param.grad = None # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors self.load_state_dict(self.state_dict()) def post_backward_models_are_masters(scaler, params, stashed_grads, scale_override=None): grads_have_scale, stashed_have_scale, out_scale = scaler.loss_scale(), 1.0, 1.0 # not much to do if scale == 1.0 and static scaling if scaler.loss_scale() == 1.0 and not scaler.dynamic: # Clear the stash. for i in range(len(stashed_grads)): stashed_grads[i] = None return if scale_override is not None: grads_have_scale, stashed_have_scale, out_scale = scale_override # This is a lot of python overhead... grads_needing_unscale = [] grads_needing_unscale_with_stash = [] stashed = [] for param, stashed_grad in zip(params, stashed_grads): if param.grad is None and stashed_grad is not None: param.grad = stashed_grad elif param.grad is not None and stashed_grad is None: grads_needing_unscale.append(param.grad) elif param.grad is not None and stashed_grad is not None: grads_needing_unscale_with_stash.append(param.grad) stashed.append(stashed_grad) else: # param.grad is None and stashed_grad is None continue # unscale() implements grads*(1/scale), so "scale" should be grads_have_scale/out_scale. if len(grads_needing_unscale) > 0: scaler.unscale( grads_needing_unscale, grads_needing_unscale, None, # unused_scale, currently present to avoid API breakage elsewhere models_are_masters=True, scale_override=grads_have_scale/out_scale) if len(grads_needing_unscale_with_stash) > 0: scaler.unscale_with_stashed( grads_needing_unscale_with_stash, stashed, grads_needing_unscale_with_stash, scale_override=(grads_have_scale, stashed_have_scale, out_scale)) # Clear the stash. for i in range(len(stashed_grads)): stashed_grads[i] = None def prepare_backward_with_master_weights(self): stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): # Set up to leverage grad copy elision. # This may behave differently from an unpatched optimizer if zero_grad is used and the param is unused. param.grad = None # for i, param in enumerate(stash.all_fp32_from_fp16_params): # stash.all_fp32_from_fp16_grad_stash[i] = param.grad for i, param in enumerate(stash.all_fp32_from_fp32_params): stash.all_fp32_from_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_with_master_weights(self, scaler): stash = self._amp_stash self._amp_lazy_init() # This is a lot of python overhead... fp16_grads_needing_unscale = [] new_fp32_grads = [] fp16_grads_needing_unscale_with_stash = [] preexisting_fp32_grads = [] for fp16_param, fp32_param in zip(stash.all_fp16_params, stash.all_fp32_from_fp16_params): if fp16_param.grad is None and fp32_param.grad is not None: continue elif fp16_param.grad is not None and fp32_param.grad is None: fp32_param.grad = torch.empty_like(fp32_param) fp16_grads_needing_unscale.append(fp16_param.grad) new_fp32_grads.append(fp32_param.grad) elif fp16_param.grad is not None and fp32_param.grad is not None: fp16_grads_needing_unscale_with_stash.append(fp16_param.grad) preexisting_fp32_grads.append(fp32_param.grad) else: # fp16_param.grad is None and fp32_param.grad is None: continue if len(fp16_grads_needing_unscale) > 0: scaler.unscale( fp16_grads_needing_unscale, new_fp32_grads, scaler.loss_scale(), models_are_masters=False) if len(fp16_grads_needing_unscale_with_stash) > 0: scaler.unscale_with_stashed( fp16_grads_needing_unscale_with_stash, preexisting_fp32_grads, preexisting_fp32_grads) # fp32 params can be treated as they would be in the "no_master_weights" case. post_backward_models_are_masters( scaler, stash.all_fp32_from_fp32_params, stash.all_fp32_from_fp32_grad_stash) def lazy_init_no_master_weights(self): stash = self._amp_stash stash.all_fp16_params = [] stash.all_fp32_params = [] for i, param_group in enumerate(self.param_groups): for i, param in enumerate(param_group['params']): if param.type() == 'torch.cuda.HalfTensor': stash.all_fp16_params.append(param) elif param.type() == 'torch.cuda.FloatTensor': stash.all_fp32_params.append(param) else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params] stash.all_fp32_grad_stash = [None for _ in stash.all_fp32_params] def prepare_backward_no_master_weights(self): stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): stash.all_fp16_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None for i, param in enumerate(stash.all_fp32_params): stash.all_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_no_master_weights(self, scaler): stash = self._amp_stash self._amp_lazy_init() split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash), (stash.all_fp32_params, stash.all_fp32_grad_stash)) for params, stashed_grads in split_types: post_backward_models_are_masters(scaler, params, stashed_grads) ##################################################################################### # FusedSGD versions ##################################################################################### # FusedSGD never explicitly materializes the fp32 gradients for "fp32 from fp16" master params # outside the kernel, so we must accumulate directly into the model grads. def prepare_backward_with_master_weights_FusedSGD(self): if self.materialize_master_grads: prepare_backward_with_master_weights(self) else: stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): stash.all_fp16_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None for i, param in enumerate(stash.all_fp32_from_fp32_params): stash.all_fp32_from_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_with_master_weights_FusedSGD(self, scaler): if self.materialize_master_grads: post_backward_with_master_weights(self, scaler) else: stash = self._amp_stash self._amp_lazy_init() grads_have_scale = scaler.loss_scale() stashed_have_scale = self.most_recent_scale out_scale = grads_have_scale if self.scale_set_by_backward: out_scale = min(grads_have_scale, self.most_recent_scale) split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash), (stash.all_fp32_from_fp32_params, stash.all_fp32_from_fp32_grad_stash)) # unscale_with_stashed() implements grads*1/scale + stashed_grads*1. # stashed_grads are scaled by self.most_recent_scale. for params, stashed_grads in split_types: post_backward_models_are_masters(scaler, params, stashed_grads, (grads_have_scale, stashed_have_scale, out_scale)) self.most_recent_scale = out_scale self.scale_set_by_backward = True def prepare_backward_no_master_weights_FusedSGD(self): prepare_backward_no_master_weights(self) def post_backward_no_master_weights_FusedSGD(self, scaler): post_backward_no_master_weights(self, scaler) def _amp_lazy_init(self): stash = self._amp_stash if not stash.lazy_init_called: self._lazy_init_maybe_master_weights() stash.lazy_init_called = True def _process_optimizer(optimizer, properties): if hasattr(optimizer, "_amp_stash"): raise RuntimeError("A given optimizer should only be passed through amp.initialize once.") else: optimizer._amp_stash = AmpOptimizerState() optimizer._amp_stash.lazy_init_called = False optimizer._amp_stash.already_patched = False optimizer._amp_stash.params_have_scaled_gradients = False for name in ("_lazy_init_maybe_master_weights", "_master_params_to_model_params", "_prepare_amp_backward", "_post_amp_backward", "_amp_lazy_init"): if hasattr(optimizer, name): raise RuntimeError("Incoming optimizer already has {} defined.".format(name)) # TODO: Centralize exposure and import error checking for the C backend. if multi_tensor_applier.available: import amp_C optimizer._amp_stash.multi_tensor_scale = amp_C.multi_tensor_scale optimizer._amp_stash.multi_tensor_l2norm = amp_C.multi_tensor_l2norm optimizer._amp_stash.dummy_overflow_buf = torch.cuda.IntTensor([0]); if properties.master_weights: optimizer._lazy_init_maybe_master_weights = types.MethodType( lazy_init_with_master_weights, optimizer) optimizer._master_params_to_model_params = types.MethodType( _master_params_to_model_params, optimizer) old_step = optimizer.step def new_step(self, closure=None): if closure is not None: raise RuntimeError("Currently, Amp does not support closure use with optimizers.") retval = old_step() if not isinstance(self, FusedSGD): self._master_params_to_model_params() # Clear the master grads that wouldn't be zeroed by model.zero_grad() for param in self._amp_stash.all_fp32_from_fp16_params: param.grad = None return retval optimizer.step = types.MethodType(new_step, optimizer) old_zero_grad = optimizer.zero_grad def new_zero_grad(self): stash = self._amp_stash self._amp_lazy_init() # Zero the model grads. for param in stash.all_fp16_params: if param.grad is not None: param.grad.detach_() param.grad.zero_() for param in stash.all_fp32_from_fp32_params: if param.grad is not None: param.grad.detach_() param.grad.zero_() # Clear the master grads that are independent of model grads for param in self._amp_stash.all_fp32_from_fp16_params: param.grad = None optimizer.zero_grad = types.MethodType(new_zero_grad, optimizer) if isinstance(optimizer, FusedSGD): optimizer._prepare_amp_backward = types.MethodType( prepare_backward_with_master_weights_FusedSGD, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_with_master_weights_FusedSGD, optimizer) else: optimizer._prepare_amp_backward = types.MethodType( prepare_backward_with_master_weights, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_with_master_weights, optimizer) else: optimizer._lazy_init_maybe_master_weights = types.MethodType( lazy_init_no_master_weights, optimizer) if isinstance(optimizer, FusedSGD): optimizer._prepare_amp_backward = types.MethodType( prepare_backward_no_master_weights_FusedSGD, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_no_master_weights_FusedSGD, optimizer) else: optimizer._prepare_amp_backward = types.MethodType( prepare_backward_no_master_weights, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_no_master_weights, optimizer) optimizer._amp_lazy_init = types.MethodType(_amp_lazy_init, optimizer) old_add_param_group = optimizer.add_param_group def new_add_param_group(self, new_group): stash = self._amp_stash if not stash.lazy_init_called: self._lazy_init_maybe_master_weights() stash.lazy_init_called = True assert isinstance(new_group, dict), "param group must be a dict" new_params = new_group['params'] if isinstance(new_params, torch.Tensor): new_group['params'] = [new_params] elif isinstance(new_params, set): raise TypeError('optimizer parameters need to be organized in ordered collections, but ' 'the ordering of tensors in sets will change between runs. Please use a list instead.') else: new_group['params'] = list(new_params) if properties.master_weights: # Mutate new_group in-place to use FP32 master params fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(new_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True new_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) elif param.type() == 'torch.cuda.FloatTensor': fp32_params_this_group.append(param) new_group['params'][i] = param else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.fp16_groups.append(fp16_params_this_group) stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) stash.fp32_from_fp32_groups.append(fp32_params_this_group) stash.all_fp16_params += fp16_params_this_group stash.all_fp32_from_fp16_params += fp32_from_fp16_params_this_group stash.all_fp32_from_fp32_params += fp32_params_this_group # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params] stash.all_fp32_from_fp32_grad_stash += [None for _ in fp32_params_this_group] # It should be ok to let params be added with existing .grad attributes. # for param in fp16_params_this_group: # param.grad = None # for param in fp32_from_fp16_params_this_group: # param.grad = None # for param in stash.fp32_params_this_group: # param.grad = None else: for param in new_group['params']: if param.type() == 'torch.cuda.HalfTensor': stash.all_fp16_params.append(param) stash.all_fp16_grad_stash.append(None) elif param.type() == 'torch.cuda.FloatTensor': stash.all_fp32_params.append(param) stash.all_fp32_grad_stash.append(None) else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) old_add_param_group(new_group) optimizer.add_param_group = types.MethodType(new_add_param_group, optimizer) return optimizer ================================================ FILE: KoSentenceT5/apex/amp/amp.py ================================================ from . import compat, rnn_compat, utils, wrap from .handle import AmpHandle, NoOpHandle from .lists import functional_overrides, torch_overrides, tensor_overrides from ._amp_state import _amp_state from .frontend import * import functools import itertools import torch _DECORATOR_HANDLE = None _USER_CAST_REGISTRY = set() _USER_PROMOTE_REGISTRY = set() def _decorator_helper(orig_fn, cast_fn, wrap_fn): def wrapper(*args, **kwargs): handle = _DECORATOR_HANDLE if handle is None or not handle.is_active(): return orig_fn(*args, **kwargs) inner_cast_fn = utils.verbosify(cast_fn, orig_fn.__name__, handle.verbose) return wrap_fn(orig_fn, inner_cast_fn, handle)(*args, **kwargs) return wrapper # Decorator form def half_function(fn): wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=True) return _decorator_helper(fn, utils.maybe_half, wrap_fn) def float_function(fn): wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=False) return _decorator_helper(fn, utils.maybe_float, wrap_fn) def promote_function(fn): wrap_fn = functools.partial(wrap.make_promote_wrapper) return _decorator_helper(fn, utils.maybe_float, wrap_fn) # Registry form def register_half_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_CAST_REGISTRY.add((module, name, utils.maybe_half)) def register_float_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_CAST_REGISTRY.add((module, name, utils.maybe_float)) def register_promote_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_PROMOTE_REGISTRY.add((module, name)) # Top-level function to insert _all_ the hooks. def init(enabled=True, loss_scale="dynamic", enable_caching=True, verbose=False, allow_banned=False): global _DECORATOR_HANDLE if not enabled: handle = NoOpHandle() _DECORATOR_HANDLE = handle return handle handle = AmpHandle(loss_scale, enable_caching, verbose) # 0) Force-{fp16, fp32} for user-annotated functions for mod, fn, cast_fn in _USER_CAST_REGISTRY: try_caching = (cast_fn == utils.maybe_half) wrap.cached_cast(mod, fn, cast_fn, handle, try_caching, verbose) _USER_CAST_REGISTRY.clear() # 0.5) Force-promote for user-annotated functions for mod, fn in _USER_PROMOTE_REGISTRY: wrap.promote(mod, fn, handle, verbose) _USER_PROMOTE_REGISTRY.clear() # 1) Force-{fp16, fp32} on white- / black-list functions override_modules = [functional_overrides, torch_overrides, tensor_overrides] cast_table = [('FP16_FUNCS', utils.maybe_half), ('FP32_FUNCS', utils.maybe_float)] for module, (list_name, cast_fn) in itertools.product(override_modules, cast_table): for fn in getattr(module, list_name): try_caching = (cast_fn == utils.maybe_half) wrap.cached_cast(module.MODULE, fn, cast_fn, handle, try_caching, verbose) # 1.5) Pre-0.4, put the blacklist methods on HalfTensor and whitelist # methods on FloatTensor, since they're distinct types. if compat.tensor_is_float_tensor(): for fn in tensor_overrides.FP16_FUNCS: wrap.cached_cast(torch.cuda.FloatTensor, fn, utils.maybe_half, handle, try_caching=True, verbose=verbose) for fn in tensor_overrides.FP32_FUNCS: wrap.cached_cast(torch.cuda.HalfTensor, fn, utils.maybe_float, handle, try_caching=False, verbose=verbose) # 2) Enable type-promotion on multi-arg functions and methods. # NB: special handling for sequence fns (e.g. `torch.cat`). promote_modules = [torch_overrides, tensor_overrides] promote_table = [('CASTS', wrap.promote), ('SEQUENCE_CASTS', wrap.sequence_promote)] for promote_mod, (list_name, promote_fn) in itertools.product(promote_modules, promote_table): for fn in getattr(promote_mod, list_name): promote_fn(promote_mod.MODULE, fn, handle, verbose) # 2.5) Pre-0.4, add blacklist methods directly to HalfTensor and FloatTensor types if compat.tensor_is_float_tensor(): for cls, (list_name, promote_fn) in itertools.product([torch.cuda.FloatTensor, torch.cuda.HalfTensor], promote_table): for fn in getattr(tensor_overrides, list_name): promote_fn(cls, fn, handle, verbose) # 3) For any in-place version of a blacklist function, error if any input is fp16. # NB: this is overly conservative. for fn in utils.as_inplace(torch_overrides.FP32_FUNCS): wrap.err_if_any_half(torch_overrides.MODULE, fn, handle) # 3.5) For any in-place blacklist method, error if called on fp16 tensor for fn in utils.as_inplace(tensor_overrides.FP32_FUNCS): wrap.err_if_arg0_half(tensor_overrides.MODULE, fn, handle, verbose) if compat.tensor_is_float_tensor(): wrap.err_if_arg0_half(torch.cuda.HalfTensor, fn, handle, verbose) # 4) For other in-place methods, match the type of self tensor for fn in utils.as_inplace(itertools.chain( tensor_overrides.FP16_FUNCS, tensor_overrides.CASTS)): wrap.promote_match_arg0(tensor_overrides.MODULE, fn, handle, verbose) if compat.tensor_is_float_tensor(): wrap.promote_match_arg0(torch.cuda.HalfTensor, fn, handle, verbose) wrap.promote_match_arg0(torch.cuda.FloatTensor, fn, handle, verbose) # 5) RNNs + RNN cells are whitelisted specially if rnn_compat.has_old_rnns(): wrap.rnn_cast(torch.nn.backends.thnn.backend, 'RNN', handle, verbose) if not rnn_compat.has_old_rnns(): # Patch in our own indirection of `_VF` in modules/rnn s.t. it is mutable. torch.nn.modules.rnn._VF = rnn_compat.VariableFunctionsShim() # Wrap all the rnns for x in rnn_compat.RNN_NAMES: wrap.new_rnn_cast(x.upper(), handle, verbose) # Wrap all the RNN cells rnn_compat.whitelist_rnn_cells(handle, verbose) # 6) Place error+print message on banned functions. # Or, if allow_banned, then cast to FP32. for fn, err_msg in functional_overrides.BANNED_FUNCS: if allow_banned: wrap.cached_cast(functional_overrides.MODULE, fn, utils.maybe_float, handle, try_caching=True, verbose=verbose) else: wrap.err_if_any_half(functional_overrides.MODULE, fn, handle, err_msg) _DECORATOR_HANDLE = handle _amp_state.handle = handle return handle ================================================ FILE: KoSentenceT5/apex/amp/compat.py ================================================ import torch # True for post-0.4, when Variables/Tensors merged. def variable_is_tensor(): v = torch.autograd.Variable() return isinstance(v, torch.Tensor) def tensor_is_variable(): x = torch.Tensor() return type(x) == torch.autograd.Variable # False for post-0.4 def tensor_is_float_tensor(): x = torch.Tensor() return type(x) == torch.FloatTensor # Akin to `torch.is_tensor`, but returns True for Variable # objects in pre-0.4. def is_tensor_like(x): return torch.is_tensor(x) or isinstance(x, torch.autograd.Variable) # Wraps `torch.is_floating_point` if present, otherwise checks # the suffix of `x.type()`. def is_floating_point(x): if hasattr(torch, 'is_floating_point'): return torch.is_floating_point(x) try: torch_type = x.type() return torch_type.endswith('FloatTensor') or \ torch_type.endswith('HalfTensor') or \ torch_type.endswith('DoubleTensor') except AttributeError: return False def scalar_python_val(x): if hasattr(x, 'item'): return x.item() else: if isinstance(x, torch.autograd.Variable): return x.data[0] else: return x[0] # Accounts for the possibility that some ops may be removed from a namespace. def filter_attrs(module, attrs): return list(attrname for attrname in attrs if hasattr(module, attrname)) ================================================ FILE: KoSentenceT5/apex/amp/frontend.py ================================================ import torch from ._initialize import _initialize from ._amp_state import _amp_state, warn_or_err, maybe_print from collections import OrderedDict class Properties(object): """ This class has two purposes: to establish a set of default properties, and to route setting of these attributes through __setattr__ so that (in theory) they can be checked for consistency with other existing args. """ def __init__(self): self.options = { "enabled" : False, "opt_level" : None, "cast_model_type" : None, "patch_torch_functions" : False, "keep_batchnorm_fp32" : None, "master_weights" : None, "loss_scale" : 1.0, # Reserved for future functionality # "fused_optimizer" : False, # "enable_ddp_interop" : False, } """ This function allows updating several options at a time without routing through __setattr__ checks, to avoid "you can't get there from here" scenarios. Currently not intended to be exposed; users are expected to select an opt_level and apply consistent modifications. """ def _update_options_dict(self, new_options): for k, v in new_options: if k in self.options: self.options[k] = v else: raise ValueError("Tried to set unexpected option {}".format(k)) """ The members of "options" are not direct attributes of self, so access attempts will roll down to __getattr__. This borrows from the logic in torch.nn.Module. """ def __getattr__(self, name): if "options" in self.__dict__: options = self.__dict__["options"] if name in options: return options[name] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, name)) def __setattr__(self, name, value): if "options" in self.__dict__: if name in self.options: # print("setting {} {}".format(name, value)) if name == "cast_model_type": if self.opt_level == "O1" and value is not None: if value is not False: if value is not torch.float32: warn_or_err("O1 inserts casts around Torch functions rather than " "model weights, so with O1, the model weights themselves " "should remain FP32. If you wish to cast the model to a " "different type, use opt_level='O2' or 'O3'. " + "cast_model_type was {}".format(value)) self.options[name] = value elif name == "patch_torch_functions": if self.opt_level != "O1" and value: warn_or_err("Currently, patch_torch_functions=True should only be set by " "selecting opt_level='O1'.") self.options[name] = value elif name == "keep_batchnorm_fp32": if self.opt_level == "O1" and value is not None: warn_or_err("With opt_level O1, batchnorm functions are automatically patched " "to run in FP32, so keep_batchnorm_fp32 should be None." + " keep_batchnorm_fp32 was {}".format(value)) if value == "False": self.options[name] = False elif value == "True": self.options[name] = True else: assert (value is True or value is False or value is None),\ "keep_batchnorm_fp32 must be a boolean, the string 'True' or 'False', "\ "or None, found keep_batchnorm_fp32={}".format(value) self.options[name] = value elif name == "master_weights": if self.opt_level == "O1" and value is not None: warn_or_err("It doesn't make sense to use master_weights with O1. " "With O1, your model weights themselves should be FP32.") self.options[name] = value elif name == "loss_scale": if value == "dynamic": self.options[name] = value else: self.options[name] = float(value) else: self.options[name] = value else: super(Properties, self).__setattr__(name, value) """ O0-O3 are convenience wrappers to establish defaults for typically used mixed precision options. """ class O3: brief = "O3: Pure FP16 training." more = "Calls .half() on your model, converting the entire model to FP16.\n"\ "A casting operation is also inserted to cast incoming Tensors to FP16,\n"\ "so you don't need to change your data pipeline.\n"\ "This mode is useful for establishing a performance ceiling.\n"\ "It's also possible training may 'just work' in this mode.\n"\ "If not, try other optimization levels." def __call__(self, properties): properties.enabled = True properties.opt_level = "O3" properties.cast_model_type = torch.float16 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = False properties.master_weights = False properties.loss_scale = 1.0 # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O2: brief = "O2: FP16 training with FP32 batchnorm and FP32 master weights.\n" more = "Calls .half() on your model, converting the entire model (except for batchnorms)\n"\ "to FP16. Batchnorms are retained in FP32 for additional stability.\n"\ "The forward pass is patched to cast incoming Tensors to FP16, so you don't need to change\n"\ "your data pipeline.\n"\ "O2 creates FP32 master weights outside the model and patches any optimizers to update\n"\ "these master weights, then copy the master weights into the FP16 model weights.\n"\ "Master weights can also improve convergence and stability." def __call__(self, properties): properties.enabled = True properties.opt_level = "O2" properties.cast_model_type = torch.float16 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = True properties.master_weights = True properties.loss_scale = "dynamic" # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O1: brief = "O1: Insert automatic casts around Pytorch functions and Tensor methods.\n" more = "The type of your model's weights is not altered. However, internally,\n"\ "Pytorch functions are patched to cast any Tensor Core-friendly ops to FP16 for speed,\n"\ "while operations that might benefit from the additional stability of FP32 are patched\n"\ "to cast their inputs to fp32.\n"\ "O1 is the safest way to try mixed precision training, and is recommended when\n"\ "trying mixed precision training for the first time." def __call__(self, properties): properties.enabled = True properties.opt_level = "O1" properties.cast_model_type = None properties.patch_torch_functions = True properties.keep_batchnorm_fp32 = None properties.master_weights = None properties.loss_scale = "dynamic" # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O0: brief = "O0: Pure FP32 training.\n" more = "Your models are checked to make sure parameters are FP32, but otherwise the\n"\ "types of weights and internal Pytorch operations are not altered. This mode disables any\n"\ "FP16 arithmetic, although other optimizations like DDP interop may still be requested.\n" def __call__(self, properties): properties.enabled = True properties.opt_level = "O0" properties.cast_model_type = torch.float32 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = None properties.master_weights = False properties.loss_scale = 1.0 # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary opt_levels = {"O3": O3(), "O2": O2(), "O1": O1(), "O0": O0()} # allow user to directly pass Properties struct as well? def initialize( models, optimizers=None, enabled=True, opt_level="O1", cast_model_type=None, patch_torch_functions=None, keep_batchnorm_fp32=None, master_weights=None, loss_scale=None, cast_model_outputs=None, num_losses=1, verbosity=1, min_loss_scale=None, max_loss_scale=2.**24 ): """ Initialize your models, optimizers, and the Torch tensor and functional namespace according to the chosen ``opt_level`` and overridden properties, if any. ``amp.initialize`` should be called **after** you have finished constructing your model(s) and optimizer(s), but **before** you send your model through any DistributedDataParallel wrapper. See `Distributed training`_ in the Imagenet example. Currently, ``amp.initialize`` should only be called **once**, although it can process an arbitrary number of models and optimizers (see the corresponding `Advanced Amp Usage topic`_). If you think your use case requires ``amp.initialize`` to be called more than once, `let us know`_. Any property keyword argument that is not ``None`` will be interpreted as a manual override. To prevent having to rewrite anything else in your script, name the returned models/optimizers to replace the passed models/optimizers, as in the code sample below. Args: models (torch.nn.Module or list of torch.nn.Modules): Models to modify/cast. optimizers (optional, torch.optim.Optimizer or list of torch.optim.Optimizers): Optimizers to modify/cast. REQUIRED for training, optional for inference. enabled (bool, optional, default=True): If False, renders all Amp calls no-ops, so your script should run as if Amp were not present. opt_level (str, optional, default="O1"): Pure or mixed precision optimization level. Accepted values are "O0", "O1", "O2", and "O3", explained in detail above. cast_model_type (``torch.dtype``, optional, default=None): Optional property override, see above. patch_torch_functions (bool, optional, default=None): Optional property override. keep_batchnorm_fp32 (bool or str, optional, default=None): Optional property override. If passed as a string, must be the string "True" or "False". master_weights (bool, optional, default=None): Optional property override. loss_scale (float or str, optional, default=None): Optional property override. If passed as a string, must be a string representing a number, e.g., "128.0", or the string "dynamic". cast_model_outputs (torch.dtype, optional, default=None): Option to ensure that the outputs of your model(s) are always cast to a particular type regardless of ``opt_level``. num_losses (int, optional, default=1): Option to tell Amp in advance how many losses/backward passes you plan to use. When used in conjunction with the ``loss_id`` argument to ``amp.scale_loss``, enables Amp to use a different loss scale per loss/backward pass, which can improve stability. See "Multiple models/optimizers/losses" under `Advanced Amp Usage`_ for examples. If ``num_losses`` is left to 1, Amp will still support multiple losses/backward passes, but use a single global loss scale for all of them. verbosity (int, default=1): Set to 0 to suppress Amp-related output. min_loss_scale (float, default=None): Sets a floor for the loss scale values that can be chosen by dynamic loss scaling. The default value of None means that no floor is imposed. If dynamic loss scaling is not used, `min_loss_scale` is ignored. max_loss_scale (float, default=2.**24): Sets a ceiling for the loss scale values that can be chosen by dynamic loss scaling. If dynamic loss scaling is not used, `max_loss_scale` is ignored. Returns: Model(s) and optimizer(s) modified according to the ``opt_level``. If either the ``models`` or ``optimizers`` args were lists, the corresponding return value will also be a list. Permissible invocations:: model, optim = amp.initialize(model, optim,...) model, [optim1, optim2] = amp.initialize(model, [optim1, optim2],...) [model1, model2], optim = amp.initialize([model1, model2], optim,...) [model1, model2], [optim1, optim2] = amp.initialize([model1, model2], [optim1, optim2],...) # This is not an exhaustive list of the cross product of options that are possible, # just a set of examples. model, optim = amp.initialize(model, optim, opt_level="O0") model, optim = amp.initialize(model, optim, opt_level="O0", loss_scale="dynamic"|128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O1") # uses "loss_scale="dynamic" default model, optim = amp.initialize(model, optim, opt_level="O1", loss_scale=128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O2") # uses "loss_scale="dynamic" default model, optim = amp.initialize(model, optim, opt_level="O2", loss_scale=128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O2", keep_batchnorm_fp32=True|False|"True"|"False") model, optim = amp.initialize(model, optim, opt_level="O3") # uses loss_scale=1.0 default model, optim = amp.initialize(model, optim, opt_level="O3", loss_scale="dynamic"|128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O3", keep_batchnorm_fp32=True|False|"True"|"False") The `Imagenet example`_ demonstrates live use of various opt_levels and overrides. .. _`Distributed training`: https://github.com/NVIDIA/apex/tree/master/examples/imagenet#distributed-training .. _`Imagenet example`: https://github.com/NVIDIA/apex/tree/master/examples/imagenet .. _`Advanced Amp Usage`: https://nvidia.github.io/apex/advanced.html .. _`Advanced Amp Usage topic`: https://nvidia.github.io/apex/advanced.html#multiple-models-optimizers-losses .. _`let us know`: https://github.com/NVIDIA/apex/issues """ _amp_state.opt_properties = Properties() _amp_state.verbosity = verbosity if not enabled: if optimizers is None: return models else: return models, optimizers if not torch.backends.cudnn.enabled: raise RuntimeError( "Amp requires torch.backends.cudnn.enabled = True") if opt_level not in opt_levels: raise RuntimeError( "Unexpected optimization level {}. ".format(opt_level) + "Options are 'O0', 'O1', 'O2', 'O3'. Note that in `O0`, `O1`, etc., the prefix O is the letter O, " + "not the number zero.") else: _amp_state.opt_properties = opt_levels[opt_level](_amp_state.opt_properties) maybe_print("Selected optimization level {}".format(opt_levels[opt_level].brief), True) maybe_print("Defaults for this optimization level are:", True) for k, v in _amp_state.opt_properties.options.items(): maybe_print("{:22} : {}".format(k, v), True) _amp_state.min_loss_scale = min_loss_scale _amp_state.max_loss_scale = max_loss_scale maybe_print("Processing user overrides (additional kwargs that are not None)...", True) # I chose to have the keyword arguments listed directly in the argument list, # instead of **kwargs, so I can't use kwargs.items() here. if enabled is not None: _amp_state.opt_properties.enabled = enabled if opt_level is not None: _amp_state.opt_properties.opt_level = opt_level if cast_model_type is not None: _amp_state.opt_properties.cast_model_type = cast_model_type if patch_torch_functions is not None: _amp_state.opt_properties.patch_torch_functions = patch_torch_functions if keep_batchnorm_fp32 is not None: _amp_state.opt_properties.keep_batchnorm_fp32 = keep_batchnorm_fp32 if master_weights is not None: _amp_state.opt_properties.master_weights = master_weights if loss_scale is not None: _amp_state.opt_properties.loss_scale = loss_scale maybe_print("After processing overrides, optimization options are:", True) for k, v in _amp_state.opt_properties.options.items(): maybe_print("{:22} : {}".format(k, v), True) return _initialize(models, optimizers, _amp_state.opt_properties, num_losses, cast_model_outputs) def state_dict(destination=None): if destination is None: destination = OrderedDict() for idx, loss_scaler in enumerate(_amp_state.loss_scalers): destination['loss_scaler%d' % idx] = { 'loss_scale': loss_scaler.loss_scale(), 'unskipped': loss_scaler._unskipped, } return destination def load_state_dict(state_dict): # Check if state_dict containes the same number of loss_scalers as current setup if len(state_dict) != len(_amp_state.loss_scalers): print('Warning: state_dict contains {} entries, while {} loss_scalers are used'.format( len(state_dict), len(_amp_state.loss_scalers))) state_dict = state_dict.copy() nb_loss_scalers = len(_amp_state.loss_scalers) unexpected_keys = [] # Initialize idx outside, since unexpected_keys will increase it if enumerate is used idx = 0 for key in state_dict: if 'loss_scaler' not in key: unexpected_keys.append(key) else: if idx > (nb_loss_scalers - 1): print('Skipping loss_scaler[{}], since num_losses was set to {}'.format( idx, nb_loss_scalers)) break _amp_state.loss_scalers[idx]._loss_scale = state_dict[key]['loss_scale'] _amp_state.loss_scalers[idx]._unskipped = state_dict[key]['unskipped'] idx += 1 if len(unexpected_keys) > 0: raise RuntimeError( 'Error(s) in loading state_dict. Unexpected key(s) in state_dict: {}. '.format( ', '.join('"{}"'.format(k) for k in unexpected_keys))) # TODO: is this necessary/useful? # def check_option_consistency(enabled=True, # opt_level=None, # cast_model_type=None, # patch_torch_functions=None, # keep_batchnorm_fp32=None, # master_weights=None, # loss_scale=None, # enable_ddp_interop=None, # hard_override=False): # """ # Utility function that enables users to quickly check if the option combination they intend # to use is permitted. ``check_option_consistency`` does not require models or optimizers # to be constructed, and can be called at any point in the script. ``check_option_consistency`` # is totally self-contained; it does not set any amp global state or affect anything outside # of itself. # """ # # if not enabled: # return # # if opt_level not in opt_levels: # raise RuntimeError("Unexpected optimization level. Options are 'O0', 'O1', 'O2', 'O3'.") # else: # opt_properties = opt_levels[opt_level](Properties()) # print("Selected optimization level {}", opt_levels[opt_level].brief) # print("Defaults for this optimization level are:") # for k, v in opt_properties.options: # print("{:22} : {}".format(k, v)) # # print("Processing user overrides (additional kwargs that are not None)...") # for k, v in kwargs: # if k not in _amp_state.opt_properties.options: # raise RuntimeError("Unexpected kwarg {}".format(k)) # if v is not None: # setattr(opt_properties, k, v) # # print("After processing overrides, optimization options are:") # for k, v in opt_properties.options: # print("{:22} : {}".format(k, v)) ================================================ FILE: KoSentenceT5/apex/amp/handle.py ================================================ import contextlib import warnings import sys import torch from . import utils from .opt import OptimWrapper from .scaler import LossScaler from ._amp_state import _amp_state, master_params, maybe_print if torch.distributed.is_available(): from ..parallel.LARC import LARC # There's no reason to expose the notion of a "handle". Everything can happen through amp.* calls. @contextlib.contextmanager def scale_loss(loss, optimizers, loss_id=0, model=None, delay_unscale=False, delay_overflow_check=False): """ On context manager entrance, creates ``scaled_loss = (loss.float())*current loss scale``. ``scaled_loss`` is yielded so that the user can call ``scaled_loss.backward()``:: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() On context manager exit (if ``delay_unscale=False``), the gradients are checked for infs/NaNs and unscaled, so that ``optimizer.step()`` can be called. .. note:: If Amp is using explicit FP32 master params (which is the default for ``opt_level=O2``, and can also be manually enabled by supplying ``master_weights=True`` to ``amp.initialize``) any FP16 gradients are copied to FP32 master gradients before being unscaled. ``optimizer.step()`` will then apply the unscaled master gradients to the master params. .. warning:: If Amp is using explicit FP32 master params, only the FP32 master gradients will be unscaled. The direct ``.grad`` attributes of any FP16 model params will remain scaled after context manager exit. This subtlety affects gradient clipping. See "Gradient clipping" under `Advanced Amp Usage`_ for best practices. Args: loss(Tensor): Typically a scalar Tensor. The ``scaled_loss`` that the context manager yields is simply ``loss.float()*loss_scale``, so in principle ``loss`` could have more than one element, as long as you call ``backward()`` on ``scaled_loss`` appropriately within the context manager body. optimizers: All optimizer(s) for which the current backward pass is creating gradients. Must be an optimizer or list of optimizers returned from an earlier call to ``amp.initialize``. For example use with multiple optimizers, see "Multiple models/optimizers/losses" under `Advanced Amp Usage`_. loss_id(int, optional, default=0): When used in conjunction with the ``num_losses`` argument to ``amp.initialize``, enables Amp to use a different loss scale per loss. ``loss_id`` must be an integer between 0 and ``num_losses`` that tells Amp which loss is being used for the current backward pass. See "Multiple models/optimizers/losses" under `Advanced Amp Usage`_ for examples. If ``loss_id`` is left unspecified, Amp will use the default global loss scaler for this backward pass. model(torch.nn.Module, optional, default=None): Currently unused, reserved to enable future optimizations. delay_unscale(bool, optional, default=False): ``delay_unscale`` is never necessary, and the default value of ``False`` is strongly recommended. If ``True``, Amp will not unscale the gradients or perform model->master gradient copies on context manager exit. ``delay_unscale=True`` is a minor ninja performance optimization and can result in weird gotchas (especially with multiple models/optimizers/losses), so only use it if you know what you're doing. "Gradient accumulation across iterations" under `Advanced Amp Usage`_ illustrates a situation where this CAN (but does not need to) be used. .. warning:: If ``delay_unscale`` is ``True`` for a given backward pass, ``optimizer.step()`` cannot be called yet after context manager exit, and must wait for another, later backward context manager invocation with ``delay_unscale`` left to False. .. _`Advanced Amp Usage`: https://nvidia.github.io/apex/advanced.html """ if not hasattr(_amp_state, "opt_properties"): raise RuntimeError("Invoked 'with amp.scale_loss`, but internal Amp state has not been initialized. " "model, optimizer = amp.initialize(model, optimizer, opt_level=...) must be called " "before `with amp.scale_loss`.") if not _amp_state.opt_properties.enabled: yield loss return if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)): optimizers = [optimizers] loss_scaler = _amp_state.loss_scalers[loss_id] loss_scale = loss_scaler.loss_scale() if ((not _amp_state.opt_properties.master_weights) and (not loss_scaler.dynamic) and loss_scale == 1.0): yield loss.float() # Needing to drop the cache here as well is an ugly gotcha. # But for now I think it's necessary to short-circuit. # Probably ok to skip this if not delay_unscale if _amp_state.opt_properties.patch_torch_functions: _amp_state.handle._clear_cache() return if not delay_unscale: if isinstance(optimizers, list): for optimizer in optimizers: if not optimizer._amp_stash.params_have_scaled_gradients: optimizer._prepare_amp_backward() yield (loss.float())*loss_scale if delay_unscale: for optimizer in optimizers: optimizer._amp_stash.params_have_scaled_gradients = True else: # FusedSGD may take care of unscaling as part of their step() methods. # if not isinstance(optimizers, FP16_Optimizer_for_fused): loss_scaler.clear_overflow_state() for optimizer in optimizers: optimizer._post_amp_backward(loss_scaler) optimizer._amp_stash.params_have_scaled_gradients = False # For future fused optimizers that enable sync-free dynamic loss scaling, # should_skip will always be False. should_skip = False if delay_overflow_check else loss_scaler.update_scale() if should_skip: for optimizer in optimizers: if not optimizer._amp_stash.already_patched: # Close on loss_scaler and loss_id as well, to be safe. Probably not # necessary because amp.scale_loss is already creating a temporary scope. def patch_step(opt, loss_scaler, loss_id): opt_step = opt.step def skip_step(closure=None): if closure is not None: raise RuntimeError("Currently, Amp does not support closure use with optimizers.") maybe_print(("Gradient overflow. Skipping step, loss scaler " + "{} reducing loss scale to {}").format(loss_id, loss_scaler.loss_scale())) # TODO: I don't like the special casing for different optimizer implementations. # Maybe skip should delegate to a method owned by the optimizers themselves. if hasattr(opt._amp_stash, "all_fp32_from_fp16_params"): # Clear the master grads that wouldn't be zeroed by model.zero_grad() for param in opt._amp_stash.all_fp32_from_fp16_params: param.grad = None if hasattr(opt, "most_recent_scale"): opt.most_recent_scale = 1.0 opt.scale_set_by_backward = False opt.step = opt_step opt._amp_stash.already_patched = False return skip_step optimizer.step = patch_step(optimizer, loss_scaler, loss_id) optimizer._amp_stash.already_patched = True # Probably ok to skip this if not delay_unscale if _amp_state.opt_properties.patch_torch_functions: _amp_state.handle._clear_cache() # Free function version of AmpHandle.disable_casts, another step on the # path to removing the concept of "AmpHandle" @contextlib.contextmanager def disable_casts(): _amp_state.handle._is_active = False yield _amp_state.handle._is_active = True class AmpHandle(object): def __init__(self, loss_scale="dynamic", enable_caching=True, verbose=False): self._enable_caching = enable_caching self._verbose = verbose self._cache = dict() self._default_scaler = LossScaler(loss_scale) self._is_active = True self._all_wrappers = [] def is_active(self): return self._is_active @contextlib.contextmanager def _disable_casts(self): self._is_active = False yield self._is_active = True def wrap_optimizer(self, optimizer, num_loss=1): self._default_scaler = None return OptimWrapper(optimizer, self, num_loss) @contextlib.contextmanager def scale_loss(self, loss, optimizer): raise RuntimeError("The old Amp API is no longer supported. Please move to the new API, " "documented here: https://nvidia.github.io/apex/amp.html. Transition guide: " "https://nvidia.github.io/apex/amp.html#transition-guide-for-old-api-users") if not self.is_active(): yield loss return if self._default_scaler is None: raise RuntimeError( 'After calling `handle.wrap_optimizer()`, you must explicitly ' + 'use `optimizer.scale_loss(loss)`.') # TODO: this code block is duplicated here and `opt.py`. Unify. loss_scale = self._default_scaler.loss_scale() yield loss * loss_scale self._default_scaler.clear_overflow_state() self._default_scaler.unscale( master_params(optimizer), master_params(optimizer), loss_scale) should_skip = self._default_scaler.update_scale() if should_skip: optimizer_step = optimizer.step def skip_step(): maybe_print('Gradient overflow, skipping update') optimizer.step = optimizer_step optimizer.step = skip_step self._clear_cache() def _clear_cache(self): self._cache.clear() # Experimental support for saving / restoring uncasted versions of functions def _save_func(self, mod, fn, func): self._all_wrappers.append((mod, fn, func)) def _deactivate(self): for mod, fn, func in self._all_wrappers: utils.set_func(mod, fn, func) self._all_wrappers = [] @property def has_cache(self): return self._enable_caching @property def cache(self): return self._cache def remove_cache(self, param): if self.has_cache and param in self.cache: del self.cache[param] @property def verbose(self): return self._verbose class NoOpHandle(object): def is_active(self): return False @contextlib.contextmanager def _disable_casts(self): yield def wrap_optimizer(self, optimizer, num_loss=1): return OptimWrapper(optimizer, self, num_loss) @contextlib.contextmanager def scale_loss(self, loss, optimizer): yield loss @property def has_cache(self): return False @property def verbose(self): return False def _clear_cache(self): pass def _deactivate(self): pass ================================================ FILE: KoSentenceT5/apex/amp/lists/__init__.py ================================================ ================================================ FILE: KoSentenceT5/apex/amp/lists/functional_overrides.py ================================================ # TODO: think about the following two. They do weird things. # - torch.nn.utils.clip_grad (but it should always be fp32 anyway) # - torch.nn.utils.weight_norm # Notes: # F.instance_norm uses batch_norm internally. Which correctly handles # fp16 in/out with fp32 weights. So we shouldn't do anything for # either of these. # F.normalize calls `input.norm()` internally, so it's redundant, but # kept here in case impl. changes. # F.cosine_similarity is same: calls `x.norm()` internally. import torch.nn.functional MODULE = torch.nn.functional FP16_FUNCS = [ 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d', 'conv_tbc', # Undocumented / maybe new? 'linear', ] FP32_FUNCS = [ # Interpolation/Upsampling TODO: Remove for 1.2 'interpolate', 'grid_sample', # Pointwise 'softplus', 'softmin', 'log_softmax', 'softmax', 'gelu', # Normalization 'layer_norm', 'group_norm', 'local_response_norm', 'normalize', 'cosine_similarity', # Loss functions # TODO: which of these can be fp16? 'poisson_nll_loss', 'cosine_embedding_loss', 'cross_entropy', 'hinge_embedding_loss', 'kl_div', 'l1_loss', 'mse_loss', 'margin_ranking_loss', 'multilabel_margin_loss', 'multilabel_soft_margin_loss', 'multi_margin_loss', 'nll_loss', 'binary_cross_entropy_with_logits', 'smooth_l1_loss', 'soft_margin_loss', 'triplet_margin_loss', 'ctc_loss' ] BANNED_FUNCS = [ ('binary_cross_entropy', ("\namp does not work out-of-the-box with `F.binary_cross_entropy` or `torch.nn.BCELoss.` " "It requires that the output of the previous function be already a FloatTensor. \n\n" "Most models have a Sigmoid right before BCELoss. In that case, you can use\n" " torch.nn.BCEWithLogitsLoss\nto combine Sigmoid+BCELoss into a single layer " "that is compatible with amp.\nAnother option is to add\n" " amp.register_float_function(torch, 'sigmoid')\nbefore calling `amp.init()`.\n" "If you _really_ know what you are doing, you can disable this warning by passing " "allow_banned=True to `amp.init()`.")) ] ================================================ FILE: KoSentenceT5/apex/amp/lists/tensor_overrides.py ================================================ from .. import compat from . import torch_overrides import importlib import torch # if compat.variable_is_tensor() and not compat.tensor_is_variable(): MODULE = torch.Tensor # else: # MODULE = torch.autograd.Variable FP16_FUNCS = compat.filter_attrs(MODULE, [ '__matmul__', ]) FP32_FUNCS = compat.filter_attrs(MODULE, [ '__ipow__', '__pow__', '__rpow__', # Cast to fp32 before transfer to CPU 'cpu', ]) CASTS = compat.filter_attrs(MODULE, [ '__add__', '__div__', '__eq__', '__ge__', '__gt__', '__iadd__', '__idiv__', '__imul__', '__isub__', '__itruediv__', '__le__', '__lt__', '__mul__', '__ne__', '__radd__', '__rdiv__', '__rmul__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__', ]) # None of these, but here to make code cleaner. SEQUENCE_CASTS = [] # We need to grab all the methods from torch_overrides and add them to # the Tensor lists as well, as almost all methods are duplicated # between `torch` and `torch.Tensor` (and check with `hasattr`, # because a few random ones aren't defined on Tensor) _self_mod = importlib.import_module(__name__) for attrname in ['FP16_FUNCS', 'FP32_FUNCS', 'CASTS', 'SEQUENCE_CASTS']: lst = getattr(_self_mod, attrname) for fn in getattr(torch_overrides, attrname): if hasattr(MODULE, fn): lst.append(fn) ================================================ FILE: KoSentenceT5/apex/amp/lists/torch_overrides.py ================================================ import torch from .. import utils MODULE = torch FP16_FUNCS = [ # Low level functions wrapped by torch.nn layers. # The wrapper layers contain the weights which are then passed in as a parameter # to these functions. 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d', 'conv_tbc', 'prelu', # BLAS 'addmm', 'addmv', 'addr', 'matmul', 'mm', 'mv', ] FP32_FUNCS = [ # Pointwise 'acos', 'asin', 'cosh', 'erfinv', 'exp', 'expm1', 'log', 'log10', 'log2', 'reciprocal', 'rsqrt', 'sinh', 'tan', # Other math 'pow', # Reduction 'cumprod', 'cumsum', 'dist', # 'mean', 'norm', 'prod', 'std', 'sum', 'var', # Misc 'renorm' ] version_strings = torch.__version__.split('.') version_major = version_strings[0] version_minor = version_strings[1] version_num = float(version_major + "." + version_minor) # Before torch 1.1, mean must be blacklisted. if version_num < 1.1: FP32_FUNCS.append('mean') # Before CUDA 9.1, batched matmul was missing fast FP16 kernels. We # check the CUDA version -- if at least 9.1, then put the bmm # functions on the fp16 list. Otherwise, put them on the fp32 list. _bmms = ['addbmm', 'baddbmm', 'bmm'] if utils.is_cuda_enabled(): # workaround https://github.com/facebookresearch/maskrcnn-benchmark/issues/802 if utils.get_cuda_version() >= (9, 1, 0): FP16_FUNCS.extend(_bmms) else: FP32_FUNCS.extend(_bmms) # Multi-tensor fns that may need type promotion CASTS = [ # Multi-tensor math 'addcdiv', 'addcmul', 'atan2', 'cross', 'bilinear', 'dot', # Element-wise _or_ tensor-wise math 'add', 'div', 'mul', # Comparison 'eq', 'equal', 'ge', 'gt', 'le', 'lt', 'ne' ] # Functions that take sequence arguments. We need to inspect the whole # sequence and cast to the widest type. SEQUENCE_CASTS = [ 'cat', 'stack' ] ================================================ FILE: KoSentenceT5/apex/amp/opt.py ================================================ import contextlib import warnings from .scaler import LossScaler, master_params from ._amp_state import maybe_print import numpy as np class OptimWrapper(object): def __init__(self, optimizer, amp_handle, num_loss): self._optimizer = optimizer self._amp_handle = amp_handle self._num_loss = num_loss self._loss_idx = 0 self._skip_next = [False] * num_loss self._loss_scaler = [LossScaler('dynamic') for _ in range(num_loss)] @contextlib.contextmanager def scale_loss(self, loss): if not self._amp_handle.is_active(): yield loss return # When there are multiple losses per-optimizer, we need # to save out current grad accumulation, since we won't be # able to unscale this particulare loss once the grads are # all mixed together. cached_grads = [] if self._loss_idx > 0: for p in master_params(self._optimizer): if p.grad is not None: cached_grads.append(p.grad.data.detach().clone()) else: cached_grads.append(None) self._optimizer.zero_grad() loss_scale = self._cur_loss_scaler().loss_scale() yield loss * loss_scale self._cur_loss_scaler().clear_overflow_state() self._cur_loss_scaler().unscale( master_params(self._optimizer), master_params(self._optimizer), loss_scale) self._skip_next[self._loss_idx] = self._cur_loss_scaler().update_scale() self._loss_idx += 1 if len(cached_grads) > 0: for p, cached_grad in zip(master_params(self._optimizer), cached_grads): if cached_grad is not None: p.grad.data.add_(cached_grad) cached_grads = [] def _cur_loss_scaler(self): assert 0 <= self._loss_idx < self._num_loss return self._loss_scaler[self._loss_idx] def step(self, closure=None): if not self._amp_handle.is_active(): return self._optimizer.step(closure=closure) self._loss_idx = 0 for group in self._optimizer.param_groups: for p in group['params']: self._amp_handle.remove_cache(p) if closure is not None: raise NotImplementedError( 'The `closure` argument is unsupported by the amp ' + 'optimizer wrapper.') if any(self._skip_next): maybe_print('Gradient overflow, skipping update') self._skip_next = [False] * self._num_loss else: return self._optimizer.step(closure=closure) # Forward any attribute lookups def __getattr__(self, attr): return getattr(self._optimizer, attr) # Forward all torch.optim.Optimizer methods def __getstate__(self): return self._optimizer.__getstate__() def __setstate__(self): return self._optimizer.__setstate__() def __repr__(self): return self._optimizer.__repr__() def state_dict(self): return self._optimizer.state_dict() def load_state_dict(self, state_dict): return self._optimizer.load_state_dict(state_dict) def zero_grad(self): return self._optimizer.zero_grad() def add_param_group(self, param_group): return self._optimizer.add_param_group(param_group) ================================================ FILE: KoSentenceT5/apex/amp/rnn_compat.py ================================================ from . import utils, wrap import torch _VF = torch._C._VariableFunctions RNN_NAMES = ['rnn_relu', 'rnn_tanh', 'gru', 'lstm'] def _gen_VF_wrapper(name): def wrapper(*args, **kwargs): return getattr(_VF, name)(*args, **kwargs) return wrapper # Some python magic to generate an object that has the rnn cell functions # defined on it, all of which call into corresponding _VF version. # Intended to patch torch.nn.modules.rnn._VF (aka, the ref named "_VF" # imported at module scope within torch.nn.modules.rnn). This should # not affect third-party importers of _VF.py. class VariableFunctionsShim(object): def __init__(self): for name in RNN_NAMES: for suffix in ['', '_cell']: fn_name = name + suffix setattr(self, fn_name, _gen_VF_wrapper(fn_name)) def has_old_rnns(): try: torch.nn.backends.thnn.backend.LSTMCell return True except: return False def whitelist_rnn_cells(handle, verbose): # Different module + function names in old/new RNN cases if has_old_rnns(): fn_names = ['RNNReLUCell', 'RNNTanhCell', 'LSTMCell', 'GRUCell'] mod = torch.nn.backends.thnn.backend else: fn_names = [x + '_cell' for x in RNN_NAMES] mod = torch.nn.modules.rnn._VF assert isinstance(mod, VariableFunctionsShim) # Insert casts on cell functions for fn in fn_names: wrap.cached_cast(mod, fn, utils.maybe_half, handle, try_caching=True, verbose=verbose) if has_old_rnns(): # Special handling of `backward` for fused gru / lstm: # The `backward` method calls Tensor.sum() (blacklist) internally, # and then the resulting grad_input has the wrong type. # TODO: where else is this a problem? for rnn_type in ['GRUFused', 'LSTMFused']: mod = getattr(torch.nn._functions.thnn.rnnFusedPointwise, rnn_type) wrap.disable_casts(mod, 'backward', handle) ================================================ FILE: KoSentenceT5/apex/amp/scaler.py ================================================ import torch from ..multi_tensor_apply import multi_tensor_applier from ._amp_state import _amp_state, master_params, maybe_print from itertools import product def scale_check_overflow_python(model_grad, master_grad, scale, check_overflow=False): # Exception handling for 18.04 compatibility if check_overflow: cpu_sum = float(model_grad.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True if master_grad is not model_grad: # copy_ probably internally short-circuits this master_grad.copy_(model_grad) if scale != 1.0: master_grad.mul_(scale) return False def axpby_check_overflow_python(model_grad, stashed_grad, master_grad, a, b, check_overflow=False): # Exception handling for 18.04 compatibility if check_overflow: cpu_sum = float(model_grad.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True # if master_grad is not model_grad: # copy_ probably internally short-circuits this # master_grad.copy_(model_grad) assert stashed_grad.dtype == master_grad.dtype converted_model_grad = model_grad.data.to(master_grad.dtype) master_grad.data = a*converted_model_grad.data + b*stashed_grad.data return False class LossScaler(object): warned_no_fused_kernel = False warned_unscaling_non_fp32_grad = False has_fused_kernel = False def __init__(self, loss_scale, init_scale=2.**16, scale_factor=2., scale_window=2000, min_loss_scale=None, max_loss_scale=2.**24): if loss_scale == "dynamic": self.dynamic = True self._loss_scale = min(max_loss_scale, init_scale) else: self.dynamic = False self._loss_scale = loss_scale self._max_loss_scale = max_loss_scale self._min_loss_scale = min_loss_scale self._scale_seq_len = scale_window self._unskipped = 0 self._has_overflow = False self._overflow_buf = torch.cuda.IntTensor([0]) if multi_tensor_applier.available: import amp_C LossScaler.has_fused_kernel = multi_tensor_applier.available LossScaler.multi_tensor_scale_cuda = amp_C.multi_tensor_scale LossScaler.multi_tensor_axpby_cuda = amp_C.multi_tensor_axpby else: if not LossScaler.warned_no_fused_kernel: maybe_print( "Warning: multi_tensor_applier fused unscale kernel is unavailable, " "possibly because apex was installed without --cuda_ext --cpp_ext. " "Using Python fallback. Original ImportError was: " + repr(multi_tensor_applier.import_err), True) LossScaler.has_fused_kernel = False LossScaler.warned_no_fused_kernel = True def loss_scale(self): return self._loss_scale def unscale_python(self, model_grads, master_grads, scale): for model, master in zip(model_grads, master_grads): if model is not None: if not LossScaler.warned_unscaling_non_fp32_grad: if master.dtype != torch.float32: maybe_print( "Attempting to unscale a grad with type {} ".format(master.type()) + "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") LossScaler.warned_unscaling_non_fp32_grad = True self._has_overflow = scale_check_overflow_python(model, master, 1./scale, self.dynamic) if self._has_overflow and self.dynamic: break # unused_scale keeps some of the old API alive for hopefully a short time. def unscale(self, model_grads, master_grads, unused_scale, models_are_masters=False, scale_override=None): if self._has_overflow: return scale = self._loss_scale if scale_override is not None: scale = scale_override if scale == 1.0 and models_are_masters and not self.dynamic: return if LossScaler.has_fused_kernel: # if (not LossScaler.warned_unscaling_non_fp32_grad # and master_grads[0].dtype == torch.float16): # print("Warning: unscaling grads that are not FP32. " # "Unscaling non-fp32 grads may indicate an error. " # "When using Amp, you don't need to call .half() on your model.") # # Setting this to True unconditionally allows the possibility of an escape # # if never-before-seen non-fp32 grads are created in some later iteration. # LossScaler.warned_unscaling_non_fp32_grad = True multi_tensor_applier(LossScaler.multi_tensor_scale_cuda, self._overflow_buf, [model_grads, master_grads], 1./scale) else: self.unscale_python(model_grads, master_grads, scale) # Defer to update_scale # If the fused kernel is available, we only need one D2H memcopy and sync. # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: # self._has_overflow = self._overflow_buf.item() def unscale_with_stashed_python(self, model_grads, stashed_master_grads, master_grads, a, b): for model, stashed, master in zip(model_grads, stashed_master_grads, master_grads): if model is None and stashed is None: continue else: if not LossScaler.warned_unscaling_non_fp32_grad: if master.dtype != torch.float32: maybe_print( "Attempting to unscale a grad with type {} ".format(master.type()) + "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") LossScaler.warned_unscaling_non_fp32_grad = True self._has_overflow = axpby_check_overflow_python(model, stashed, master, a, b, self.dynamic) if self._has_overflow and self.dynamic: break def unscale_with_stashed(self, model_grads, stashed_master_grads, master_grads, scale_override=None): if self._has_overflow: return grads_have_scale, stashed_have_scale, out_scale = self._loss_scale, 1.0, 1.0 if scale_override is not None: grads_have_scale, stashed_have_scale, out_scale = scale_override if LossScaler.has_fused_kernel: if (not LossScaler.warned_unscaling_non_fp32_grad and master_grads[0].dtype == torch.float16): print("Warning: unscaling grads that are not FP32. " "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") # Setting this to True unconditionally allows the possibility of an escape # if never-before-seen non-fp32 grads are created in some later iteration. LossScaler.warned_unscaling_non_fp32_grad = True multi_tensor_applier(LossScaler.multi_tensor_axpby_cuda, self._overflow_buf, [model_grads, stashed_master_grads, master_grads], out_scale/grads_have_scale, # 1./scale, out_scale/stashed_have_scale, # 1.0, 0) # check only arg 0, aka the incoming model grads, for infs else: self.unscale_with_stashed_python(model_grads, stashed_master_grads, master_grads, out_scale/grads_have_scale, out_scale/stashed_have_scale) # Defer to update_scale # If the fused kernel is available, we only need one D2H memcopy and sync. # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: # self._has_overflow = self._overflow_buf.item() def clear_overflow_state(self): self._has_overflow = False if self.has_fused_kernel: self._overflow_buf.zero_() # Separate so unscale() can be called more that once before updating. def update_scale(self): # If the fused kernel is available, we only need one D2H memcopy and sync. if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: self._has_overflow = self._overflow_buf.item() if self._has_overflow and self.dynamic: should_skip = True if(self._min_loss_scale): self._loss_scale = max(self._min_loss_scale, self._loss_scale/2.) else: self._loss_scale = self._loss_scale/2. self._unskipped = 0 else: should_skip = False self._unskipped += 1 if self._unskipped == self._scale_seq_len and self.dynamic: self._loss_scale = min(self._max_loss_scale, self._loss_scale*2.) self._unskipped = 0 return should_skip ================================================ FILE: KoSentenceT5/apex/amp/utils.py ================================================ from . import compat import functools import itertools import torch def is_cuda_enabled(): return torch.version.cuda is not None def get_cuda_version(): return tuple(int(x) for x in torch.version.cuda.split('.')) def is_fp_tensor(x): if is_nested(x): # Fast-fail version of all(is_fp_tensor) for y in x: if not is_fp_tensor(y): return False return True return compat.is_tensor_like(x) and compat.is_floating_point(x) def is_nested(x): return isinstance(x, tuple) or isinstance(x, list) def should_cache(x): if is_nested(x): # Fast-fail version of all(should_cache) for y in x: if not should_cache(y): return False return True return isinstance(x, torch.nn.parameter.Parameter) and \ type_string(x) == 'FloatTensor' def collect_fp_tensor_types(args, kwargs): def collect_types(x, types): if is_nested(x): for y in x: collect_types(y, types) else: types.add(type_string(x)) all_args = itertools.chain(args, kwargs.values()) types = set() for x in all_args: if is_fp_tensor(x): collect_types(x, types) return types def type_string(x): return x.type().split('.')[-1] def maybe_half(x, name='', verbose=False): if is_nested(x): return type(x)([maybe_half(y) for y in x]) if not x.is_cuda or type_string(x) == 'HalfTensor': return x else: if verbose: print('Float->Half ({})'.format(name)) return x.half() def maybe_float(x, name='', verbose=False): if is_nested(x): return type(x)([maybe_float(y) for y in x]) if not x.is_cuda or type_string(x) == 'FloatTensor': return x else: if verbose: print('Half->Float ({})'.format(name)) return x.float() # NB: returneds casted `args`, mutates `kwargs` in-place def casted_args(cast_fn, args, kwargs): new_args = [] for x in args: if is_fp_tensor(x): new_args.append(cast_fn(x)) else: new_args.append(x) for k in kwargs: val = kwargs[k] if is_fp_tensor(val): kwargs[k] = cast_fn(val) return new_args def cached_cast(cast_fn, x, cache): if is_nested(x): return type(x)([cached_cast(y) for y in x]) if x in cache: cached_x = cache[x] if x.requires_grad and cached_x.requires_grad: # Make sure x is actually cached_x's autograd parent. if cached_x.grad_fn.next_functions[1][0].variable is not x: raise RuntimeError("x and cache[x] both require grad, but x is not " "cache[x]'s parent. This is likely an error.") # During eval, it's possible to end up caching casted weights with # requires_grad=False. On the next training iter, if cached_x is found # and reused from the cache, it will not actually have x as its parent. # Therefore, we choose to invalidate the cache (and force refreshing the cast) # if x.requires_grad and cached_x.requires_grad do not match. # # During eval (i.e. running under with torch.no_grad()) the invalidation # check would cause the cached value to be dropped every time, because # cached_x would always be created with requires_grad=False, while x would # still have requires_grad=True. This would render the cache effectively # useless during eval. Therefore, if we are running under the no_grad() # context manager (torch.is_grad_enabled=False) we elide the invalidation # check, and use the cached value even though its requires_grad flag doesn't # match. During eval, we don't care that there's no autograd-graph # connection between x and cached_x. if torch.is_grad_enabled() and x.requires_grad != cached_x.requires_grad: del cache[x] else: return cached_x casted_x = cast_fn(x) cache[x] = casted_x return casted_x def verbosify(cast_fn, fn_name, verbose): if verbose: return functools.partial(cast_fn, name=fn_name, verbose=verbose) else: return cast_fn def as_inplace(fns): for x in fns: yield x + '_' def has_func(mod, fn): if isinstance(mod, dict): return fn in mod else: return hasattr(mod, fn) def get_func(mod, fn): if isinstance(mod, dict): return mod[fn] else: return getattr(mod, fn) def set_func(mod, fn, new_fn): if isinstance(mod, dict): mod[fn] = new_fn else: setattr(mod, fn, new_fn) def set_func_save(handle, mod, fn, new_fn): cur_fn = get_func(mod, fn) handle._save_func(mod, fn, cur_fn) set_func(mod, fn, new_fn) # A couple problems get solved here: # - The flat_weight buffer is disconnected from autograd graph, # so the fp16 weights need to be derived from the input weights # to this forward call, not the flat buffer. # - The ordering of weights in the flat buffer is...idiosyncratic. # First problem is solved with combination of set_ (to set up # correct storage) and copy_ (so the fp16 weight derives from the # fp32 one in autograd. # Second is solved by doing ptr arithmetic on the fp32 weights # to derive the correct offset. # # TODO: maybe this should actually use # `torch._cudnn_rnn_flatten_weight`? But then I need to call # on first iter and cache the right offsets. Ugh. def synthesize_flattened_rnn_weights(fp32_weights, fp16_flat_tensor, rnn_fn='', verbose=False): fp16_weights = [] fp32_base_ptr = fp32_weights[0][0].data_ptr() for layer_weights in fp32_weights: fp16_layer_weights = [] for w_fp32 in layer_weights: w_fp16 = w_fp32.new().half() offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size() w_fp16.set_(fp16_flat_tensor.storage(), offset, w_fp32.shape) w_fp16.copy_(w_fp32) if verbose: print('Float->Half ({})'.format(rnn_fn)) fp16_layer_weights.append(w_fp16) fp16_weights.append(fp16_layer_weights) return fp16_weights # Roughly same as above, just the `fp32_weights` aren't nested. # Code kept separate for readability. def new_synthesize_flattened_rnn_weights(fp32_weights, fp16_flat_tensor, rnn_fn='', verbose=False): fp16_weights = [] fp32_base_ptr = fp32_weights[0].data_ptr() for w_fp32 in fp32_weights: w_fp16 = w_fp32.new().half() offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size() w_fp16.set_(fp16_flat_tensor.storage(), offset, w_fp32.shape) w_fp16.copy_(w_fp32) if verbose: print('Float->Half ({})'.format(rnn_fn)) fp16_weights.append(w_fp16) return fp16_weights ================================================ FILE: KoSentenceT5/apex/amp/wrap.py ================================================ from . import compat from . import utils from ._amp_state import _amp_state from . import rnn_compat import functools import torch def make_cast_wrapper(orig_fn, cast_fn, handle, try_caching=False): @functools.wraps(orig_fn) def wrapper(*args, **kwargs): if not handle.is_active(): return orig_fn(*args, **kwargs) if try_caching and handle.has_cache: args = list(args) for i in range(len(args)): if utils.should_cache(args[i]): args[i] = utils.cached_cast(cast_fn, args[i], handle.cache) for k in kwargs: if utils.should_cache(kwargs[k]): kwargs[k] = utils.cached_cast(cast_fn, kwargs[k], handle.cache) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(*new_args, **kwargs) return wrapper def cached_cast(mod, fn, cast_fn, handle, try_caching=False, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) cast_fn = utils.verbosify(cast_fn, fn, verbose) wrapper = make_cast_wrapper(orig_fn, cast_fn, handle, try_caching) utils.set_func_save(handle, mod, fn, wrapper) # `handle` arg is unused, but simplifies API to make `make_cast_wrapper` # Annoyingly, make_promote_wrapper still uses the global handle. Once everyone # is on the new API and I am free to get rid of handle, I can clean this up. def make_promote_wrapper(orig_fn, cast_fn, handle=None): @functools.wraps(orig_fn) def wrapper(*args, **kwargs): if not _amp_state.handle.is_active(): return orig_fn(*args, **kwargs) types = utils.collect_fp_tensor_types(args, kwargs) if len(types) <= 1: return orig_fn(*args, **kwargs) elif len(types) == 2 and types == set(['HalfTensor', 'FloatTensor']): new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(*new_args, **kwargs) else: raise NotImplementedError('Do not know how to handle ' + 'these types to promote: {}' .format(types)) return wrapper def promote(mod, fn, handle, verbose=False): orig_fn = utils.get_func(mod, fn) maybe_float = utils.verbosify(utils.maybe_float, fn, verbose) wrapper = make_promote_wrapper(orig_fn, maybe_float) utils.set_func_save(handle, mod, fn, wrapper) def sequence_promote(mod, fn, handle, verbose=False): orig_fn = utils.get_func(mod, fn) maybe_float = utils.verbosify(utils.maybe_float, fn, verbose) @functools.wraps(orig_fn) def wrapper(seq, *args, **kwargs): if not _amp_state.handle.is_active(): return orig_fn(seq, *args, **kwargs) types = set([utils.type_string(x) for x in seq]) if len(types) <= 1: return orig_fn(seq, *args, **kwargs) elif types == set(['HalfTensor', 'FloatTensor']): cast_seq = utils.casted_args(maybe_float, seq, {}) return orig_fn(cast_seq, *args, **kwargs) else: # TODO: other mixed-type cases aren't due to amp. # Just pass through? return orig_fn(seq, *args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def promote_match_arg0(mod, fn, handle, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(arg0, *args, **kwargs): assert compat.is_tensor_like(arg0) if not _amp_state.handle.is_active(): return orig_fn(arg0, *args, **kwargs) if utils.type_string(arg0) == 'HalfTensor': cast_fn = utils.maybe_half elif utils.type_string(arg0) == 'FloatTensor': cast_fn = utils.maybe_float else: return orig_fn(arg0, *args, **kwargs) cast_fn = utils.verbosify(cast_fn, fn, verbose) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(arg0, *new_args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def err_if_any_half(mod, fn, handle, custom_err_msg=None): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): types = utils.collect_fp_tensor_types(args, kwargs) if 'HalfTensor' in types: if custom_err_msg: raise NotImplementedError(custom_err_msg) else: raise NotImplementedError('Cannot call in-place function ' + '{} with fp16 arguments.'.format(fn)) else: return orig_fn(*args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def err_if_arg0_half(mod, fn, handle, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(arg0, *args, **kwargs): assert compat.is_tensor_like(arg0) if utils.type_string(arg0) == 'HalfTensor': raise NotImplementedError('Cannot call in-place method ' + '{} on fp16 Tensors.'.format(fn)) else: cast_fn = utils.verbosify(utils.maybe_float, fn, verbose) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(arg0, *new_args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) # Current RNN approach: # - Wrap top-level `RNN` function in thnn backend # - Will call into either CudnnRNN or AutogradRNN # - Each of these are factory functions that return a per-iter # `forward` function # - We interpose on the factory function to: # 1) Interpose on the actual forward function and put in casts # 2) Insert an fp16 `flat_weight` if necessary def rnn_cast(backend, fn, handle, verbose=False): orig_rnn = utils.get_func(backend, fn) @functools.wraps(orig_rnn) def rnn_wrapper(*args, **kwargs): flat_weight = kwargs.get('flat_weight') if flat_weight is not None: # We replace `flat_weight` with an uninitialized fp16 # Tensor. The "actual" weight tensors (provided in `forward`), # will then be set up as ptrs into the buffer and have the # corresponding fp32 values copied in. # We need to call `copy` on the "actual" weights so that the # autograd graph correctly backprops from the wgrads computed # inside cuDNN (on fp16 weights) into the fp32 weights. assert utils.type_string(flat_weight) == 'FloatTensor' if compat.tensor_is_float_tensor() or compat.tensor_is_variable(): # Pre-0.4. A little slower, since it zeros out memory. flat_weight_fp16 = flat_weight.new().half().resize_(flat_weight.shape) else: flat_weight_fp16 = torch.empty_like(flat_weight, dtype=torch.float16) kwargs['flat_weight'] = flat_weight_fp16 else: flat_weight_fp16 = None forward = orig_rnn(*args, **kwargs) @functools.wraps(forward) def fwd_wrapper(*fargs, **fkwargs): assert len(fargs) == 3 or len(fargs) == 4 inputs, weights, hiddens = fargs[:3] assert utils.is_fp_tensor(inputs) assert isinstance(weights, list) cast_fn = utils.verbosify(utils.maybe_half, fn, verbose) new_args = [] # 0) Inputs new_args.append(cast_fn(inputs)) # 1) Weights if flat_weight_fp16 is not None: fp16_weights = utils.synthesize_flattened_rnn_weights( weights, flat_weight_fp16, fn, verbose) else: fp16_weights = [[cast_fn(w) for w in layer] for layer in weights] new_args.append(fp16_weights) # 2) Inputs: either a tuple (for LSTM) or single tensor if isinstance(hiddens, tuple): new_args.append(tuple(cast_fn(x) for x in hiddens)) elif utils.is_fp_tensor(hiddens): new_args.append(cast_fn(hiddens)) else: # Hiddens can, in principle, be `None` -- pass through new_args.append(hiddens) # 3) Batch sizes (0.4 or later only) if len(fargs) == 4: new_args.append(fargs[3]) return forward(*new_args, **fkwargs) return fwd_wrapper utils.set_func_save(handle, backend, fn, rnn_wrapper) def new_rnn_cast(fn, handle, verbose=False): # Forward+backward compatibility around https://github.com/pytorch/pytorch/pull/15744 # For rnn backend calls that route through _rnn_impls, we must patch the ref # that _rnn_impls stashed. For rnn backend calls that directly invoke # _VF., e.g. _VF.lstm, we can patch onto VariableFunctionsShim, # which in turn has patched the ref named "_VF" in torch.nn.modules.rnn. if utils.has_func(torch.nn.modules.rnn._rnn_impls, fn): mod = torch.nn.modules.rnn._rnn_impls else: mod = torch.nn.modules.rnn._VF assert isinstance(mod, rnn_compat.VariableFunctionsShim) fn = fn.lower() orig_fn = utils.get_func(mod, fn) cast_fn = utils.verbosify(utils.maybe_half, fn, verbose) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): # Exact call signature from modules/rnn.py assert len(args) == 9 assert len(kwargs) == 0 if not _amp_state.handle.is_active(): return orig_fn(*args, **kwargs) if isinstance(args[6], bool): params_idx = 2 # Not PackedSequence case else: params_idx = 3 # PackedSequence case new_args = [] for i, arg in enumerate(args): if i == params_idx: num_params = sum([x.numel() for x in arg]) fp16_weight_buf = args[0].new_empty((num_params,), dtype=torch.half) casted_weights = utils.new_synthesize_flattened_rnn_weights( arg, fp16_weight_buf, fn, verbose) new_args.append(casted_weights) elif utils.is_fp_tensor(arg): new_args.append(cast_fn(arg)) else: new_args.append(arg) return orig_fn(*new_args) utils.set_func_save(handle, mod, fn, wrapper) def disable_casts(mod, fn, handle): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): with handle._disable_casts(): return orig_fn(*args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) ================================================ FILE: KoSentenceT5/apex/contrib/__init__.py ================================================ ================================================ FILE: KoSentenceT5/apex/contrib/bottleneck/__init__.py ================================================ from .bottleneck import Bottleneck ================================================ FILE: KoSentenceT5/apex/contrib/bottleneck/bottleneck.py ================================================ import torch from torch import nn import fast_bottleneck def kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu'): weight_tensor_nchw = tensor nn.init.kaiming_uniform_(weight_tensor_nchw, a=a, mode=mode, nonlinearity=nonlinearity) class FrozenBatchNorm2d(torch.nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed """ def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n)) def get_scale_bias(self, nhwc=False): scale = self.weight * self.running_var.rsqrt() bias = self.bias - self.running_mean * scale if nhwc: scale = scale.reshape(1, 1, 1, -1) bias = bias.reshape(1, 1, 1, -1) else: scale = scale.reshape(1, -1, 1, 1) bias = bias.reshape(1, -1, 1, 1) return scale, bias def forward(self, x): scale, bias = self.get_scale_bias() return x * scale + bias @torch.jit.script def drelu_dscale1(grad_o, output, scale1): relu_mask = (output>0).half() dx_relu = relu_mask * grad_o g1 = dx_relu * scale1 return g1, dx_relu @torch.jit.script def drelu_dscale2(grad_o, output, scale1, scale2): relu_mask = (output>0).half() dx_relu = relu_mask * grad_o g1 = dx_relu * scale1 g2 = dx_relu * scale2 return g1, g2 class BottleneckFunction(torch.autograd.Function): @staticmethod def forward(ctx, nhwc, stride_1x1, scale, bias, x, *conv): # TODO: clean up order of tensors args = [x, *conv[0:3], *scale[0:3], *bias[0:3]] ctx.downsample = len(conv) > 3 if ctx.downsample: args.append(conv[3]) args.append(scale[3]) args.append(bias[3]) # weight buffers are always in nhwc while shape can be nhwc or channels_last # here we pass in flag and let c++ handle it # alternatively, we can put all sizes into a fixed format and pass it in outputs = fast_bottleneck.forward(nhwc, stride_1x1, args) ctx.save_for_backward(*(args+outputs)) # save relu outputs for drelu ctx.nhwc = nhwc ctx.stride_1x1 = stride_1x1 return outputs[2] # backward relu is not exposed, MUL with mask used now # only support dgrad @staticmethod def backward(ctx, grad_o): outputs = ctx.saved_tensors[-3:] if ctx.downsample: grad_conv3, grad_conv4 = drelu_dscale2(grad_o, outputs[2], ctx.saved_tensors[6], ctx.saved_tensors[11]) else: grad_conv3, grad_conv4 = drelu_dscale1(grad_o, outputs[2], ctx.saved_tensors[6]) # create input vector for backward t_list = [*ctx.saved_tensors[0:10]] t_list.append(grad_conv3) t_list.append(grad_conv4) # outputs used for wgrad and generating drelu mask t_list.append(outputs[0]) t_list.append(outputs[1]) # in case there is downsample if ctx.downsample: t_list.append(ctx.saved_tensors[10]) grads = fast_bottleneck.backward(ctx.nhwc, ctx.stride_1x1, t_list) return (None, None, None, None, *grads) bottleneck_function = BottleneckFunction.apply def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(torch.nn.Module): # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) # while original implementation places the stride at the first 1x1 convolution(self.conv1) # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. # This variant is also known as ResNet V1.5 and improves accuracy according to # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. # here we put it at 1x1 def __init__(self, in_channels, bottleneck_channels, out_channels, stride=1, groups=1, dilation=1, norm_func=None, use_cudnn=False, explicit_nhwc=False): super(Bottleneck, self).__init__() if groups != 1: raise RuntimeError('Only support groups == 1') if dilation != 1: raise RuntimeError('Only support dilation == 1') if norm_func == None: norm_func = FrozenBatchNorm2d else: raise RuntimeError('Only support frozen BN now.') if stride != 1 or in_channels != out_channels: self.downsample = nn.Sequential( conv1x1(in_channels, out_channels, stride), norm_func(out_channels), ) else: self.downsample = None # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(in_channels, bottleneck_channels, stride) self.conv2 = conv3x3(bottleneck_channels, bottleneck_channels) self.conv3 = conv1x1(bottleneck_channels, out_channels) self.relu = nn.ReLU(inplace=True) self.stride = stride self.bn1 = norm_func(bottleneck_channels) self.bn2 = norm_func(bottleneck_channels) self.bn3 = norm_func(out_channels) self.use_cudnn = use_cudnn # setup conv weights self.w_conv = [self.conv1.weight, self.conv2.weight, self.conv3.weight] if self.downsample is not None: self.w_conv.append(self.downsample[0].weight) # init weight in nchw format before possible transpose for w in self.w_conv: kaiming_uniform_(w, a=1) # TODO: prevent unsupported case usage # support cases # native cudnn # normal yes no # channel_last yes yes # explicit_nhwc no yes self.explicit_nhwc = explicit_nhwc if self.explicit_nhwc: for p in self.parameters(): with torch.no_grad(): p.data = p.data.permute(0,2,3,1).contiguous() return def forward(self, x): if self.use_cudnn: # calculate scale/bias from registered buffers # TODO: make this better s1, b1 = self.bn1.get_scale_bias(self.explicit_nhwc) s2, b2 = self.bn2.get_scale_bias(self.explicit_nhwc) s3, b3 = self.bn3.get_scale_bias(self.explicit_nhwc) w_scale = [s1, s2, s3] w_bias = [b1, b2, b3] if self.downsample is not None: s4, b4 = self.downsample[1].get_scale_bias(self.explicit_nhwc) w_scale.append(s4) w_bias.append(b4) out = bottleneck_function(self.explicit_nhwc, self.stride, w_scale, w_bias, x, *self.w_conv) return out if self.explicit_nhwc: raise RuntimeError('explicit nhwc with native ops is not supported.') # fallback to native ops identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out ================================================ FILE: KoSentenceT5/apex/contrib/bottleneck/test.py ================================================ import torch from bottleneck import Bottleneck torch.manual_seed(23337) # use True to print layerwise sum for all outputs in reference code path DEBUG = False#True for stride, o_channel in [(1,32), (1,128), (2,32)]: print("testing stride ==", stride, ", in_channel == 32 , out_channel ==", o_channel) a_ = torch.randn(17,32,28,28) a = a_.cuda().half().to(memory_format=torch.channels_last).requires_grad_() model = Bottleneck(32,8,o_channel,stride=stride).cuda().half().to(memory_format=torch.channels_last) # test model b = model(a) b.mean().backward() d_grad = a.grad.float() a.grad = None torch.cuda.synchronize() if DEBUG: print("[DEBUG] ref dx :", d_grad.sum().item()) # print wgrad. we don't need to reset since later cpp print before accumulation for i, w in enumerate(model.w_conv): print("[DEBUG] ref wgrad{} :".format(i+1), w.grad.sum().item()) wgrads = [] for w in model.w_conv: wgrads.append(w.grad.float()) model.use_cudnn = True model.zero_grad() c = model(a) c.mean().backward() torch.cuda.synchronize() print("comparing native and channels_last:") print("max error fprop:", (b-c).abs().max().item(), "max elem:", b.abs().max().item()) print("max error dgrad:", (d_grad-a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item()) for i, (w, wgrad) in enumerate(zip(model.w_conv, wgrads)): print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item()) nhwc_a = a_.permute(0,2,3,1).contiguous().cuda().half().requires_grad_() nhwc_model = Bottleneck(32,8,o_channel,stride=stride,explicit_nhwc=True, use_cudnn=True).cuda().half() for p,q in zip(model.parameters(), nhwc_model.parameters()): # model's storage is already in nhwc, we clone and assign to explicit nhwc model q.data.copy_(p.data.permute(0,2,3,1).contiguous()) for p,q in zip(model.buffers(), nhwc_model.buffers()): q.data.copy_(p.data) d = nhwc_model(nhwc_a) d.mean().backward() torch.cuda.synchronize() # reset reference to cudnn channels_last permute #c_s = c.storage().tolist() #d_s = d.storage().tolist() #print(max([x-y for x,y in zip(c_s,d_s)])) c = c.contiguous(memory_format=torch.contiguous_format).permute(0,2,3,1).contiguous() d_grad = a.grad.float().permute(0,2,3,1).contiguous() wgrads = [] for w in model.w_conv: wgrads.append(w.grad.float().permute(0,2,3,1).contiguous()) torch.cuda.synchronize() print("comparing nhwc and channels_last:") print("max error fprop:", (d-c).abs().max().item(), "max elem:", c.abs().max().item()) print("max error dgrad:", (d_grad-nhwc_a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item()) for i, (w, wgrad) in enumerate(zip(nhwc_model.w_conv, wgrads)): print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item()) ================================================ FILE: KoSentenceT5/apex/contrib/csrc/bottleneck/bottleneck.cpp ================================================ #include #include // for getcudnnhandle #include #include #include #include #include #ifdef DEBUG #define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false ) #else #define DEBUG_MSG(str) do { } while ( false ) #endif #ifdef DEBUG_CUDNN #define DEBUG_CUDNN_MSG(buf, str) do { buf << str << std::endl; } while( false ) #else #define DEBUG_CUDNN_MSG(buf, str) do { } while ( false ) #endif #define checkCudnnErr(...) \ do { \ int err = checkCudnnError(__VA_ARGS__, #__VA_ARGS__, __FILE__, __LINE__); \ if (err) { \ return; \ } \ } while (0) int checkCudnnError(cudnnStatus_t code, const char* expr, const char* file, int line) { if (code) { printf("CUDNN error at %s:%d, code=%d (%s) in '%s'\n", file, line, (int)code, cudnnGetErrorString(code), expr); return 1; } return 0; } void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort = true); #define checkCUDAError(val) { checkError((val), #val, __FILE__, __LINE__); } // in-line regular function void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort) { if (code != cudaSuccess) { const char * errorMessage = cudaGetErrorString(code); fprintf(stderr, "CUDA error returned from \"%s\" at %s:%d, Error code: %d (%s)\n", func, file, line, code, errorMessage); if (abort){ cudaDeviceReset(); exit(code); } } } void generateStrides(const int64_t* dimA, int64_t* strideA, int nbDims, cudnnTensorFormat_t filterFormat) { // For INT8x4 and INT8x32 we still compute standard strides here to input // into the cuDNN functions. We will manually scale by resizeFactor in the cpu ref. if (filterFormat == CUDNN_TENSOR_NCHW) { strideA[nbDims - 1] = 1; for (int64_t d = nbDims - 2; d >= 0; d--) { strideA[d] = strideA[d + 1] * dimA[d + 1]; } } else { // Here we assume that the format is CUDNN_TENSOR_NHWC strideA[1] = 1; strideA[nbDims - 1] = strideA[1] * dimA[1]; for (int64_t d = nbDims - 2; d >= 2; d--) { strideA[d] = strideA[d + 1] * dimA[d + 1]; } strideA[0] = strideA[2] * dimA[2]; } } int getFwdConvDilatedFilterDim(int filterDim, int dilation) { return ((filterDim - 1) * dilation) + 1; } int getFwdConvPaddedImageDim(int tensorDim, int pad) { return tensorDim + (2 * pad); } int getFwdConvOutputDim( int tensorDim, int pad, int filterDim, int stride, int dilation) { int p = (getFwdConvPaddedImageDim(tensorDim, pad) - getFwdConvDilatedFilterDim(filterDim, dilation)) / stride + 1; return (p); } enum { X_TENSOR, Y_TENSOR, W_TENSOR, Z_TENSOR, B_TENSOR, AFTERADD_TENSOR, AFTERBIAS_TENSOR, AFTERCONV_TENSOR, OPTIONAL, AFTEROPT_TENSOR, }; using common_conv_descriptors = std::tuple; common_conv_descriptors create_common_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, cudnnConvolutionMode_t mode) { const int convDim = 2; int64_t strideA_padded[4]; int64_t outstrideA_padded[4]; int64_t filterstrideA_padded[4]; generateStrides(w_dim_padded, filterstrideA_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, strideA_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, outstrideA_padded, 4, CUDNN_TENSOR_NHWC); return common_conv_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, strideA_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, outstrideA_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, filterstrideA_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(mode) .setNDims(convDim) .setStrides(convDim, convstrideA) .setPrePadding(convDim, padA) .setPostPadding(convDim, padA) .setDilation(convDim, dilationA) .build()); } using common_convbias_descriptors = std::tuple; common_convbias_descriptors create_conv_bias_add_act_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType) { const int convDim = 2; int64_t b_dim_padded[4]; b_dim_padded[0] = 1; b_dim_padded[1] = y_dim_padded[1]; b_dim_padded[2] = 1; b_dim_padded[3] = 1; int64_t x_stride_padded[4]; int64_t y_stride_padded[4]; int64_t w_stride_padded[4]; int64_t b_stride_padded[4]; generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC); return common_convbias_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, w_stride_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('z') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('b') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setVirtual() .setId('A') // after add .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setVirtual() .setId('B') // after bias .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('C') // after conv .setAlignment(16) .setVirtual() .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('i') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('D') // after optional add .setAlignment(16) .setVirtual() .setDataType(dataType) .build()); } // tensor descriptors used for dgrad enum { X_OR_DX_TENSOR, DY_TENSOR, W_OR_DW_TENSOR, SCALE_TENSOR, RELU_TENSOR, AFTER_DCONV_TENSOR, AFTER_DRELU_TENSOR, }; using dconv_descriptors = std::tuple; dconv_descriptors create_dconv_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType) { const int convDim = 2; int64_t b_dim_padded[4]; b_dim_padded[0] = 1; b_dim_padded[1] = x_dim_padded[1]; b_dim_padded[2] = 1; b_dim_padded[3] = 1; int64_t x_stride_padded[4]; int64_t y_stride_padded[4]; int64_t w_stride_padded[4]; int64_t b_stride_padded[4]; generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC); return dconv_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, w_stride_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('s') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('r') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setVirtual() .setId('A') // after dconv .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setVirtual() .setId('B') // after drelu .setAlignment(16) .setDataType(dataType) .build()); } // create a cache for plan std::unordered_map plan_cache; // TODO: better name std::string getConvFusionString(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, cudnnDataType_t dataType, std::string fusion_string) { for(int i=0;i<4;i++) { fusion_string += 'X'; fusion_string += std::to_string(x_dim_padded[i]); } for(int i=0;i<4;i++) { fusion_string += 'W'; fusion_string += std::to_string(w_dim_padded[i]); } for(int i=0;i<2;i++) { fusion_string += 'P'; fusion_string += std::to_string(padA[i]); } for(int i=0;i<2;i++) { fusion_string += 'S'; fusion_string += std::to_string(convstrideA[i]); } for(int i=0;i<2;i++) { fusion_string += 'D'; fusion_string += std::to_string(dilationA[i]); } fusion_string += 'T'; fusion_string += std::to_string(dataType); return fusion_string; } cudnn_frontend::ExecutionPlan& getOrCreatePlan(cudnnHandle_t handle_, std::stringstream& log_buf, cudnn_frontend::OperationGraph& opGraph, std::string cache_string, bool use_heuristic = true){ auto it = plan_cache.find(cache_string); if (it != plan_cache.end()) { DEBUG_CUDNN_MSG(log_buf, "Found plan in cache"); return it->second; } else { if (use_heuristic){ // TODO: confirm which mode to use auto heuristics = cudnn_frontend::EngineHeuristicsBuilder() .setOperationGraph(opGraph) .setHeurMode(CUDNN_HEUR_MODE_INSTANT) .build(); // try 3 times for now as WAR for no heuristic training int max_tries = 3, count = 0; auto& engine_configs = heuristics.getEngineConfig(max_tries); while(true) { try { plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder() .setHandle(handle_) .setEngineConfig(engine_configs[count], opGraph.getTag()) .build())); break; } catch (cudnn_frontend::cudnnException e) { if (++count == max_tries) throw e; } } }else{ DEBUG_CUDNN_MSG(log_buf, "No plan in cache"); // How many engines support this operation graph ? auto total_engines = opGraph.getEngineCount(); DEBUG_CUDNN_MSG(log_buf, opGraph.describe() << " has " << total_engines << " engines."); // We have to randomly pick one engine from [0, total_engines) // Selecting "0" by default auto engine = cudnn_frontend::EngineBuilder().setGlobalEngineIdx(0).setOperationGraph(opGraph).build(); DEBUG_CUDNN_MSG(log_buf, engine.describe()); auto& knobs = engine.getSupportedKnobs(); for (auto it = std::begin(knobs); it != std::end(knobs); ++it) { DEBUG_CUDNN_MSG(log_buf, it->describe()); } if (knobs.begin() != knobs.end()) { DEBUG_CUDNN_MSG(log_buf, "Updated knob choice"); knobs.begin()->setChoice(knobs.begin()->getMinValue() + 1); DEBUG_CUDNN_MSG(log_buf, knobs.begin()->describe()); } // Createmplacee the requisite engine config auto engine_config = cudnn_frontend::EngineConfigBuilder().setEngine(engine).build(); DEBUG_CUDNN_MSG(log_buf, engine_config.describe()); plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder().setHandle(handle_).setEngineConfig(engine_config).build())); } return plan_cache.find(cache_string)->second; } } void run_conv_scale_bias_add_activation(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrB, at::Half* devPtrI) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the add operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); // Define the bias operation auto biasDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, biasDesc.describe()); // optional add auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); // Define the activation operation auto actDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_RELU_FWD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, actDesc.describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) .setxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create a Add Node with scaling parameters. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(conv_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create a Bias Node. auto bias_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(scale_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(biasDesc) .build(); DEBUG_CUDNN_MSG(log_buf, bias_op.describe()); // Create a optional add Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(bias_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Activation Node. auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(devPtrI ? add_op.getOutputTensor() : bias_op.getOutputTensor()) .setyDesc(std::get(tensors)) .setpwDesc(actDesc) .build(); DEBUG_CUDNN_MSG(log_buf, act_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &scale_op, &bias_op, devPtrI ? &add_op : &act_op, &act_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(devPtrI ? ops.size() : 4, ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB, devPtrI}; int64_t uids[] = {'x', 'y', 'w', 'z', 'b', 'i'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(devPtrI ? 6 : 5, data_ptrs) .setUids(devPtrI ? 6 : 5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_conv_scale_bias(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrB) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the add operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); // Define the bias operation auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) .setxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create a Add Node with scaling parameters. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(conv_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) // TODO: change enum to aftermul .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create a Bias Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(scale_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &scale_op, &add_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB}; int64_t uids[] = {'x', 'y', 'w', 'z', 'b'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(5, data_ptrs) .setUids(5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv_drelu_dscale(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrR) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); // Define the activation backward operation auto actDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_RELU_BWD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, actDesc.describe()); // Define the scale backward operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) .setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // TODO: do we need getOutputTensor(), and what it returns in backward case? // Create an relu backward Node. auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setdyDesc(std::get(tensors)) .setxDesc(std::get(tensors)) .setdxDesc(std::get(tensors)) .setpwDesc(actDesc) .build(); DEBUG_CUDNN_MSG(log_buf, act_op.describe()); // Create a Scale Node. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(std::get(tensors)) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &act_op, &scale_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrR}; int64_t uids[] = {'x', 'y', 'w', 's', 'r'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(5, data_ptrs) .setUids(5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, cudnnBackendDescriptorType_t mode) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node // mode should be one of following // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR auto conv_op_builder = cudnn_frontend::OperationBuilder(mode); if (mode == CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) { conv_op_builder.setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta); } else { conv_op_builder.setxDesc(std::get(tensors)) .setdwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta); } auto conv_op = conv_op_builder.build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW}; int64_t uids[] = {'x', 'y', 'w'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(3, data_ptrs) .setUids(3, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv_add(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrR) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); // Define the add backward operation auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) .setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // TODO: do we need getOutputTensor(), and what it returns in backward case? // Create add Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(std::get(tensors)) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &add_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrR}; int64_t uids[] = {'x', 'y', 'w', 'r'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(4, data_ptrs) .setUids(4, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } // inputs contains x,w,z,b,(i) std::vector bottleneck_forward(bool explicit_nhwc, int stride_1X1, std::vector inputs) { std::cout << std::fixed; // create output vector std::vector outputs; auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast; // setup dimensions int64_t dimA[] = {0, 0, 0, 0}; int64_t filterdimA1[] = {0, 0, 0, 0}; int64_t filterdimA2[] = {0, 0, 0, 0}; int64_t filterdimA3[] = {0, 0, 0, 0}; int64_t filterdimA4[] = {0, 0, 0, 0}; // All dim calculation after this order of n,c,h,w int axis[] {0,1,2,3}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 3; axis[2] = 1; axis[3] = 2; } for (int dim=0;dim<4;dim++) { dimA[dim] = inputs[0].size(axis[dim]); filterdimA1[dim] = inputs[1].size(axis[dim]); filterdimA2[dim] = inputs[2].size(axis[dim]); filterdimA3[dim] = inputs[3].size(axis[dim]); } if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { for (int dim=0;dim<4;dim++) { filterdimA4[dim] = inputs[10].size(axis[dim]); } } // output dim in n,c,h,w used by backend int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below // use these fixed value for test run int64_t padA[] = {0, 0}; int64_t padA1[] = {1, 1}; int64_t dilationA[] = {1, 1}; int64_t convstrideA[] = {1, 1}; int64_t convstride1X1[] = {stride_1X1, stride_1X1}; // compute output from pad/stride/dilation outdimA1[0] = dimA[0]; outdimA1[1] = filterdimA1[0]; for (int dim = 0; dim < 2; dim++) { outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]); } outdimA2[0] = outdimA1[0]; outdimA2[1] = filterdimA2[0]; for (int dim = 0; dim < 2; dim++) { outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]); } outdimA3[0] = outdimA2[0]; outdimA3[1] = filterdimA3[0]; for (int dim = 0; dim < 2; dim++) { outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]); } // Create output tensor in the correct shape in pytorch's view int64_t outdim1[] = {0, 0, 0, 0}; int64_t outdim2[] = {0, 0, 0, 0}; int64_t outdim3[] = {0, 0, 0, 0}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 2; axis[2] = 3; axis[3] = 1; } for (int dim=0;dim<4;dim++) { outdim1[dim] = outdimA1[axis[dim]]; outdim2[dim] = outdimA2[axis[dim]]; outdim3[dim] = outdimA3[axis[dim]]; } // run at::Half* x = inputs[0].data_ptr(); at::Half* w = inputs[1].data_ptr(); at::Half* z = inputs[4].data_ptr(); at::Half* b = inputs[7].data_ptr(); auto out1 = at::empty(outdim1, inputs[0].type(), output_format); at::Half* y1 = out1.data_ptr(); run_conv_scale_bias_add_activation(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, x, w, y1, z, b, nullptr); DEBUG_MSG("[DEBUG] new relu1 : " << out1.to(at::kFloat).sum().item()); w = inputs[2].data_ptr(); z = inputs[5].data_ptr(); b = inputs[8].data_ptr(); auto out2 = at::empty(outdim2, inputs[0].type(), output_format); at::Half* y2 = out2.data_ptr(); run_conv_scale_bias_add_activation(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, y1, w, y2, z, b, nullptr); DEBUG_MSG("[DEBUG] new relu2 : " << out2.to(at::kFloat).sum().item()); // create output of conv3 auto out3 = at::empty(outdim3, inputs[0].type(), output_format); at::Half* y3 = out3.data_ptr(); // create output of conv4 that may exist auto identity = at::empty_like(out3); at::Half* yi = identity.data_ptr(); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){ w = inputs[10].data_ptr(); z = inputs[11].data_ptr(); b = inputs[12].data_ptr(); run_conv_scale_bias(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, x, w, yi, z, b); DEBUG_MSG("[DEBUG] new downsample : " << identity.to(at::kFloat).sum().item()); } else { yi = x; } w = inputs[3].data_ptr(); z = inputs[6].data_ptr(); b = inputs[9].data_ptr(); run_conv_scale_bias_add_activation(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, y2, w, y3, z, b, yi); DEBUG_MSG("[DEBUG] new relu3 : " << out3.to(at::kFloat).sum().item()); outputs.push_back(out1); outputs.push_back(out2); outputs.push_back(out3); return outputs; } std::vector bottleneck_backward(bool explicit_nhwc, int stride_1X1, std::vector inputs) { bool requires_grad = inputs[0].requires_grad(); std::cout << std::fixed; // create output vector std::vector outputs; auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast; // setup dimensions int64_t dimA[] = {0, 0, 0, 0}; int64_t filterdimA1[] = {0, 0, 0, 0}; int64_t filterdimA2[] = {0, 0, 0, 0}; int64_t filterdimA3[] = {0, 0, 0, 0}; int64_t filterdimA4[] = {0, 0, 0, 0}; // All dim calculation after this order of n,c,h,w int axis[] {0,1,2,3}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 3; axis[2] = 1; axis[3] = 2; } for (int dim=0;dim<4;dim++) { dimA[dim] = inputs[0].size(axis[dim]); filterdimA1[dim] = inputs[1].size(axis[dim]); filterdimA2[dim] = inputs[2].size(axis[dim]); filterdimA3[dim] = inputs[3].size(axis[dim]); } if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { for (int dim=0;dim<4;dim++) { filterdimA4[dim] = inputs[14].size(axis[dim]); } } // output dim in n,c,h,w used by backend int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below // use these fixed value for test run int64_t padA[] = {0, 0}; int64_t padA1[] = {1, 1}; int64_t dilationA[] = {1, 1}; int64_t convstrideA[] = {1, 1}; int64_t convstride1X1[] = {stride_1X1, stride_1X1}; // compute output from pad/stride/dilation outdimA1[0] = dimA[0]; outdimA1[1] = filterdimA1[0]; for (int dim = 0; dim < 2; dim++) { outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]); } outdimA2[0] = outdimA1[0]; outdimA2[1] = filterdimA2[0]; for (int dim = 0; dim < 2; dim++) { outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]); } outdimA3[0] = outdimA2[0]; outdimA3[1] = filterdimA3[0]; for (int dim = 0; dim < 2; dim++) { outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]); } // Create output tensor in the correct shape in pytorch's view int64_t outdim1[] = {0, 0, 0, 0}; int64_t outdim2[] = {0, 0, 0, 0}; int64_t outdim3[] = {0, 0, 0, 0}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 2; axis[2] = 3; axis[3] = 1; } for (int dim=0;dim<4;dim++) { outdim1[dim] = outdimA1[axis[dim]]; outdim2[dim] = outdimA2[axis[dim]]; outdim3[dim] = outdimA3[axis[dim]]; } // dconv3+drelu2+dscale2 at::Half* conv_in = inputs[13].data_ptr(); at::Half* dy3 = inputs[10].data_ptr(); DEBUG_MSG("[DEBUG] new dconv3 : " << inputs[10].to(at::kFloat).sum().item()); // wgrad auto wgrad3 = at::empty_like(inputs[3]); at::Half* dw3 = wgrad3.data_ptr(); run_dconv(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, conv_in, dw3, dy3, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad auto grad_out2 = at::empty(outdim2, inputs[0].type(), output_format); at::Half* dy2 = grad_out2.data_ptr(); at::Half* w = inputs[3].data_ptr(); at::Half* z = inputs[5].data_ptr(); at::Half* relu2 = inputs[13].data_ptr(); run_dconv_drelu_dscale(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, dy2, w, dy3, z, relu2); DEBUG_MSG("[DEBUG] new dconv2 : " << grad_out2.to(at::kFloat).sum().item()); // dconv2+drelu1+dscale1 conv_in = inputs[12].data_ptr(); // wgrad auto wgrad2 = at::empty_like(inputs[2]); at::Half* dw2 = wgrad2.data_ptr(); run_dconv(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, conv_in, dw2, dy2, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad auto grad_out1 = at::empty(outdim1, inputs[0].type(), output_format); at::Half* dy1 = grad_out1.data_ptr(); w = inputs[2].data_ptr(); z = inputs[4].data_ptr(); at::Half* relu1 = inputs[12].data_ptr(); // fused dgrad run_dconv_drelu_dscale(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, z, relu1); /* // backward strided conv cannot be fused // if stride == 1 but channel changes, we can fuse here if (stride_1X1 != 1){ // dgrad run_dconv(outdimA1, padA1, convstride1X1, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // mul fused mask grad_out1.mul_(inputs[15]); } else { at::Half* relu1 = inputs[12].data_ptr(); // fused dgrad run_dconv_drelu_dscale(outdimA1, padA1, convstride1X1, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, z, relu1); } */ DEBUG_MSG("[DEBUG] new dconv1 : " << grad_out1.to(at::kFloat).sum().item()); // create grads of conv4 that may exist auto grad_x_conv4 = at::empty_like(inputs[0]); at::Half* dx_conv4 = grad_x_conv4.data_ptr(); at::Tensor wgrad4; // x used for dconv1 and dconv4 wgrad at::Half* x = inputs[0].data_ptr(); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){ w = inputs[14].data_ptr(); at::Half* dy_conv4 = inputs[11].data_ptr(); if (requires_grad) { run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, dx_conv4, w, dy_conv4, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // we don't print here since we can't hook out this grad in pytorch alone to compare, due to addition with dx // DEBUG_MSG("[DEBUG] new dx_identity : " << grad_x_conv4.to(at::kFloat).sum().item()); } // wgrad wgrad4 = at::empty_like(inputs[14]); at::Half* dw4 = wgrad4.data_ptr(); run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, x, dw4, dy_conv4, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); } else { // if there is no downsample, dx_conv4 is fork of drelu3 dx_conv4 = inputs[11].data_ptr(); } // dconv1+add // wgrad auto wgrad1 = at::empty_like(inputs[1]); at::Half* dw1 = wgrad1.data_ptr(); run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, x, dw1, dy1, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad w = inputs[1].data_ptr(); auto grad_x = at::empty_like(inputs[0]); at::Half* dx = grad_x.data_ptr(); // backward strided conv cannot be fused // if stride == 1 but channel changes, we can fuse here if (requires_grad){ if (stride_1X1 != 1){ run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, dx, w, dy1, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // add 2 together grad_x.add_(grad_x_conv4); } else { run_dconv_add(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, dx, w, dy1, dx_conv4); } } DEBUG_MSG("[DEBUG] new dx : " << grad_x.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad1 : " << wgrad1.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad2 : " << wgrad2.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad3 : " << wgrad3.to(at::kFloat).sum().item()); outputs.push_back(grad_x); outputs.push_back(wgrad1); outputs.push_back(wgrad2); outputs.push_back(wgrad3); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { DEBUG_MSG("[DEBUG] new wgrad4 : " << wgrad4.to(at::kFloat).sum().item()); outputs.push_back(wgrad4); } return outputs; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &bottleneck_forward, "Bottleneck block forward"); m.def("backward", &bottleneck_backward, "Bottleneck block backward"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/fmha_api.cpp ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include #include #include "fmha.h" void set_params(Fused_multihead_attention_fprop_params ¶ms, // sizes const size_t b, const size_t s, const size_t h, const size_t d, // device pointers void *qkv_packed_d, void *cu_seqlens_d, void *o_packed_d, void *s_d, float p_dropout) { Data_type acc_type = DATA_TYPE_FP32; Data_type data_type = DATA_TYPE_FP16; // Reset the parameters memset(¶ms, 0, sizeof(params)); // Set the pointers and strides. params.qkv_ptr = qkv_packed_d; params.qkv_stride_in_bytes = get_size_in_bytes(h * 3 * d, data_type); params.o_ptr = o_packed_d; params.o_stride_in_bytes = get_size_in_bytes(h * d, data_type); params.cu_seqlens = static_cast(cu_seqlens_d); // S = softmax(P) params.s_ptr = s_d; params.s_stride_in_bytes = get_size_in_bytes(b * h * s, data_type); // Set the dimensions. params.b = b; params.h = h; params.s = s; params.d = d; // Set the different scale values. const float scale_bmm1 = 1.f / sqrtf(d); constexpr float scale_softmax = 1.f; constexpr float scale_bmm2 = 1.f; set_alpha(params.scale_bmm1, scale_bmm1, acc_type); set_alpha(params.scale_softmax, scale_softmax, acc_type); set_alpha(params.scale_bmm2, scale_bmm2, data_type); // Set this to probability of keeping an element to simplify things. params.p_dropout = 1.f - p_dropout; params.rp_dropout = 1.f / params.p_dropout; TORCH_CHECK(p_dropout < 1.f); set_alpha(params.scale_dropout, params.rp_dropout, data_type); } std::vector mha_fwd(const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i const at::Tensor &cu_seqlens, // b+1 const float p_dropout, const int max_seq_len, const bool is_training, c10::optional gen_) { auto dprops = at::cuda::getCurrentDeviceProperties(); TORCH_CHECK(dprops->major == 8 && dprops->minor == 0); int seq_len = 512; auto launch = &run_fmha_fp16_512_64_sm80; if( max_seq_len <= 128 ) { seq_len = 128; launch = &run_fmha_fp16_128_64_sm80; } else if( max_seq_len <= 256 ) { seq_len = 256; launch = &run_fmha_fp16_256_64_sm80; } else if( max_seq_len <= 384 ) { seq_len = 384; launch = &run_fmha_fp16_384_64_sm80; } else if( max_seq_len <= 512 ) { seq_len = 512; launch = &run_fmha_fp16_512_64_sm80; } else { TORCH_CHECK(false); } constexpr int warps_m = 1; constexpr int warps_n = 4; // this leads to an upper bound const int mmas_m = seq_len / 16 / warps_m; const int mmas_n = seq_len / 16 / warps_n; const int elts_per_thread = 8 * mmas_m * mmas_n; auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.dtype() == torch::kFloat16); TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto opts = qkv.options(); auto ctx = torch::empty({ total, num_heads, head_size }, opts); auto s = torch::empty({ batch_size, num_heads, seq_len, seq_len }, opts); auto gen = at::get_generator_or_default( gen_, at::cuda::detail::getDefaultCUDAGenerator()); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), ctx.data_ptr(), s.data_ptr(), p_dropout); // number of times random will be generated per thread, to offset philox counter in thc random // state int64_t counter_offset = elts_per_thread; at::PhiloxCudaState rng_engine_inputs; if( is_training ) { // See Note [Acquire lock when using random generators] std::lock_guard lock(gen->mutex_); params.philox_args = gen->philox_cuda_state(counter_offset); } launch(params, is_training, stream); return { ctx, s }; } std::vector mha_bwd(const at::Tensor &dout, // total x num_heads, x head_size const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i at::Tensor &softmax, // b x h x s x s softmax and dmask - will be overwritten with dP const at::Tensor &cu_seqlens, // b+1 const float p_dropout, // probability to drop const int max_seq_len // max sequence length to choose the kernel ) { auto dprops = at::cuda::getCurrentDeviceProperties(); TORCH_CHECK(dprops->major == 8 && dprops->minor == 0); int seq_len = 512; auto launch = &run_fmha_dgrad_fp16_512_64_sm80; if( max_seq_len <= 128 ) { seq_len = 128; launch = &run_fmha_dgrad_fp16_128_64_sm80; } else if( max_seq_len <= 256 ) { seq_len = 256; launch = &run_fmha_dgrad_fp16_256_64_sm80; } else if( max_seq_len <= 384 ) { seq_len = 384; launch = &run_fmha_dgrad_fp16_384_64_sm80; } else if( max_seq_len <= 512 ) { seq_len = 512; launch = &run_fmha_dgrad_fp16_512_64_sm80; } else { TORCH_CHECK(false); } auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.dtype() == torch::kFloat16); TORCH_CHECK(dout.dtype() == torch::kFloat16); TORCH_CHECK(softmax.dtype() == torch::kFloat16); TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32); TORCH_CHECK(qkv.is_cuda()); TORCH_CHECK(cu_seqlens.is_cuda()); TORCH_CHECK(qkv.is_contiguous()); TORCH_CHECK(cu_seqlens.is_contiguous()); TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto dqkv = torch::empty_like(qkv); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), dout.data_ptr(), // we set o_ptr to dout softmax.data_ptr(), // softmax gets overwritten by dP! p_dropout); // we're re-using these scales Data_type acc_type = DATA_TYPE_FP32; set_alpha(params.scale_bmm1, 1.f, acc_type); set_alpha(params.scale_softmax, 1.f / sqrtf(head_size), acc_type); set_alpha(params.scale_bmm2, 1.f, DATA_TYPE_FP16); params.dqkv_ptr = dqkv.data_ptr(); launch(params, stream); return { dqkv, softmax }; } std::vector mha_fwd_nl(const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i const at::Tensor &cu_seqlens, // b+1 const float p_dropout, const int max_seq_len, const bool is_training, c10::optional gen_) { int seq_len = 512; auto launch = &run_fmha_fp16_512_64_sm80_nl; TORCH_CHECK(max_seq_len == seq_len); constexpr int warps_m = 1; constexpr int warps_n = 4; // this leads to an upper bound const int mmas_m = seq_len / 16 / warps_m; const int mmas_n = seq_len / 16 / warps_n; // static_assert( mmas_m == 32 ); // static_assert( mmas_n == 4 ); const int elts_per_thread = 8 * mmas_m * mmas_n; auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto opts = qkv.options(); auto ctx = torch::empty({ total, num_heads, head_size }, opts); auto s = torch::empty({ batch_size, num_heads, seq_len, seq_len }, opts); auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), ctx.data_ptr(), s.data_ptr(), p_dropout); // number of times random will be generated per thread, to offset philox counter in thc random // state int64_t counter_offset = elts_per_thread; at::PhiloxCudaState rng_engine_inputs; if( is_training ) { // See Note [Acquire lock when using random generators] std::lock_guard lock(gen->mutex_); params.philox_args = gen->philox_cuda_state(counter_offset); } int num_chunks = 3; if(batch_size == 3) { num_chunks = 2; } launch(params, is_training, num_chunks, stream); return { ctx, s }; } std::vector mha_bwd_nl(const at::Tensor &dout, // total x num_heads, x head_size const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i at::Tensor &softmax, // b x h x s x s softmax and dmask - will be overwritten with dP const at::Tensor &cu_seqlens, // b+1 const float p_dropout, // probability to drop const int max_seq_len // max sequence length to choose the kernel ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); int seq_len = 512; auto launch = &run_fmha_dgrad_fp16_512_64_sm80_nl; auto opts = qkv.options(); auto dqkv = torch::empty_like(qkv); int num_chunks = 2; if( batch_size == 1 ) { num_chunks = 4; }else if( batch_size == 2 ) { num_chunks = 3; } auto dkv = torch::empty({total, num_chunks, 2, num_heads, head_size}, opts); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), dout.data_ptr(), // o_ptr = dout softmax.data_ptr(), // softmax gets overwritten by dP! p_dropout); params.dkv_ptr = dkv.data_ptr(); Data_type acc_type = DATA_TYPE_FP32; set_alpha(params.scale_bmm1, 1.f, acc_type); set_alpha(params.scale_softmax, 1.f / sqrtf(head_size), acc_type); set_alpha(params.scale_bmm2, 1.f, DATA_TYPE_FP16); params.dqkv_ptr = dqkv.data_ptr(); launch(params, num_chunks, stream); //SPLIT-K reduction of num_chunks dK, dV parts // The equivalent of the following Pytorch code: // using namespace torch::indexing; // at::Tensor view_out = dqkv.index({Slice(), Slice(1, None, None)}); // torch::sum_out(view_out, dkv, 1); const int hidden_size = num_heads * head_size; fmha_run_noloop_reduce( dqkv.data_ptr(), dkv.data_ptr(), cu_seqlens.data_ptr(), hidden_size, batch_size, total, num_chunks, stream); return { dqkv, softmax, dkv }; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.doc() = "Fused Multi-head Self-attention for BERT"; m.def("fwd", &mha_fwd, "Forward pass"); m.def("bwd", &mha_bwd, "Backward pass"); m.def("fwd_nl", &mha_fwd_nl, "Forward pass (small-batch)"); m.def("bwd_nl", &mha_bwd_nl, "Backward pass (small-batch)"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/gemm.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #define FMHA_DIV_UP(m, n) (((m) + (n)-1) / (n)) namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type_, int NUM_ELTS_, int BITS_PER_ELT_, int ALIGNMENT_ > struct Fragment_base_ { // The data type. using Data_type = Data_type_; // default input type using Input_type_ = Data_type_; // Does it store the array of elements. enum { HAS_ELTS = BITS_PER_ELT_ >= 8 }; // The number of elements. enum { NUM_ELTS = NUM_ELTS_ }; // The size of element in bits. enum { BITS_PER_ELT = BITS_PER_ELT_ }; // The size of byte of a single register. enum { BYTES_PER_REG = 4 }; // The size in bits. enum { BITS_PER_REG = BYTES_PER_REG * 8 }; // The number of registers needed to store the fragment. enum { NUM_REGS = Div_up::VALUE }; // The size in bytes (as returned by sizeof(Fragment_base<>). enum { SIZE_IN_BYTES = NUM_REGS * BYTES_PER_REG }; // The alignment. enum { ALIGNMENT = ALIGNMENT_ > 0 ? ALIGNMENT_ : Min::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The type of the elements. typename Data_type_, // The number of elements. int NUM_ELTS_, // The alignment if you want to force a value -- use 0 otherwise. int ALIGNMENT_ = 0, // The base class. typename Base_ = Fragment_base_ > struct alignas(static_cast(Base_::ALIGNMENT)) Fragment : public Base_ { // The size of a load/store. enum { BYTES_PER_LOAD_STORE = Base_::NUM_REGS * sizeof(uint32_t) }; // Clear the fragment. Using PTX in that code seems to produce better SASS... inline __device__ void clear() { #pragma unroll for( int ii = 0; ii < Base_::NUM_REGS; ++ii ) { asm volatile("mov.u32 %0, 0; \n" : "=r"(this->reg(ii)) : ); } } // Immutable access to a register. inline __device__ const uint32_t& reg(int ii) const { return this->regs_[ii]; } // Mutable access to a register. inline __device__ uint32_t& reg(int ii) { return this->regs_[ii]; } uint32_t regs_[Base_::NUM_REGS]; // Immutable access to the elements. inline __device__ const Data_type_& elt(int ii) const { return reinterpret_cast(&this->regs_[0])[ii]; } // Mutable access to the elements. inline __device__ Data_type_& elt(int ii) { return reinterpret_cast(&this->regs_[0])[ii]; } // Immutable access to the elements with a cast. template< typename Cast_type > inline __device__ const Cast_type& elt_as(int ii) const { return reinterpret_cast(&this->regs_[0])[ii]; } // Mutable access to the elements. template< typename Cast_type > inline __device__ Cast_type& elt_as(int ii) { return reinterpret_cast(&this->regs_[0])[ii]; } // Add another fragment. inline __device__ void add(const Fragment &other) { #pragma unroll for( int ii = 0; ii < NUM_ELTS_; ++ii ) { this->elt(ii) += other.elt(ii); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Layout > struct Fragment_a : public Fragment { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Layout > struct Fragment_b : public Fragment { }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Fragment_accumulator : public Fragment { // The base class. using Base = Fragment; // Add two fragments. template< typename Other_fragment_ > inline __device__ void add(const Other_fragment_ &other) { for( int ii = 0; ii < Base::NUM_ELTS; ++ii ) { this->elt(ii) = this->elt(ii) + other.elt(ii); } } // Do the HMMA. template< typename Layout_a, typename Layout_b > inline __device__ void mma(const Fragment_a &a, const Fragment_b &b) { asm volatile( \ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \ " {%0, %1, %2, %3}, \n" \ " {%4, %5, %6, %7}, \n" \ " {%8, %9}, \n" \ " {%0, %1, %2, %3}; \n" \ : "+f"( elt(0)), "+f"( elt(1)), "+f"( elt(2)), "+f"( elt(3)) : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3)) , "r"(b.reg(0)), "r"(b.reg(1))); asm volatile( \ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \ " {%0, %1, %2, %3}, \n" \ " {%4, %5, %6, %7}, \n" \ " {%8, %9}, \n" \ " {%0, %1, %2, %3}; \n" \ : "+f"( elt(4)), "+f"( elt(5)), "+f"( elt(6)), "+f"( elt(7)) : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3)) , "r"(b.reg(2)), "r"(b.reg(3))); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Fragment, int M, int N > inline __device__ void clear(Fragment (&frag)[M][N]) { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ni = 0; ni < N; ++ni ) { frag[mi][ni].clear(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Accumulator_type, int WARPS_K > struct Clear_accumulator { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int WARPS_K > struct Clear_accumulator { template< typename Acc, int M, int N > static inline __device__ void apply(Acc (&acc)[M][N], bool = false) { fmha::clear(acc); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void gemm(Acc (&acc)[M][N], const A (&a)[M], const B (&b)[N]) { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ni = 0; ni < N; ++ni ) { acc[mi][ni].mma(a[mi], b[ni]); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The number of rows in the CTA tile. int M_, // The number of cols in the CTA tile. int N_, // The number of elements in the the K dimension of the GEMM loop. int K_, // The number of rows of warps. int WARPS_M_, // The number of cols of warps. int WARPS_N_, // The number of warps in the K dimension of the GEMM loop. int WARPS_K_> struct Cta_tile_ { enum { M = M_, N = N_, K = K_ }; // The number of warps. enum { WARPS_M = WARPS_M_, WARPS_N = WARPS_N_, WARPS_K = WARPS_K_ }; // The number of warps per CTA. enum { WARPS_PER_CTA = WARPS_M * WARPS_N * WARPS_K }; // The number of threads per warp. enum { THREADS_PER_WARP = 32 }; // The number of threads per CTA. enum { THREADS_PER_CTA = WARPS_PER_CTA * THREADS_PER_WARP }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Hmma_tile { // The number of elements computed with a single warp-MMA. enum { M_PER_MMA = 16, N_PER_MMA = 16, K_PER_MMA = 16 }; // The number of elements computed with a single CTA-MMA. enum { M_PER_MMA_PER_CTA = M_PER_MMA * Cta_tile::WARPS_M, N_PER_MMA_PER_CTA = N_PER_MMA * Cta_tile::WARPS_N, K_PER_MMA_PER_CTA = K_PER_MMA * Cta_tile::WARPS_K }; // The number of MMAs needed to compute the GEMM. enum { MMAS_M = Div_up::VALUE, MMAS_N = Div_up::VALUE, MMAS_K = Div_up::VALUE, }; // The number of elements computed per warp. enum { M_PER_WARP = MMAS_M * M_PER_MMA, N_PER_WARP = MMAS_N * N_PER_MMA, K_PER_WARP = MMAS_K * K_PER_MMA, }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// using A_type = uint16_t; using B_type = uint16_t; using C_type = uint16_t; using Accumulator_type = float; using Epilogue_type = float; constexpr int BITS_PER_ELEMENT_A = sizeof(A_type) * 8; constexpr int BITS_PER_ELEMENT_B = sizeof(B_type) * 8; constexpr int BITS_PER_ELEMENT_C = sizeof(C_type) * 8; //////////////////////////////////////////////////////////////////////////////////////////////////// template using Cta_tile_extd = Cta_tile_; //////////////////////////////////////////////////////////////////////////////////////////////////// template using Cta_tile_with_k_with_padding = Cta_tile_extd::VALUE, Cta_tile_::WARPS_M, Cta_tile_::WARPS_N, Cta_tile_::WARPS_K>; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/gmem_tile.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The number of bits per element. int BITS_PER_ELEMENT, // The number of rows of Q, K or V loaded by this tile. int ROWS, // The number of columns. int COLS, // The number of matrics. int NUM_MATS = 3 > struct Gmem_tile_qkv { // The size of each LDG. enum { BYTES_PER_LDG = 16 }; // The size of a row in bytes. enum { BYTES_PER_ROW = COLS * BITS_PER_ELEMENT / 8 }; // The number of threads to load a "row" of the matrix. enum { THREADS_PER_ROW = BYTES_PER_ROW / BYTES_PER_LDG }; // The number of "rows" loaded per LDG. enum { ROWS_PER_LDG = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // The number of LDGs needed to load a chunk of the Q matrix. enum { LDGS = fmha::Div_up::VALUE }; // Ctor. template< typename Params, typename BInfo > inline __device__ Gmem_tile_qkv(const Params ¶ms, int qkv_offset, const BInfo &binfo, int tidx) : params_qkv_stride_in_bytes_(params.qkv_stride_in_bytes) , actual_seqlen(binfo.actual_seqlen) , qkv_ptr_(reinterpret_cast(params.qkv_ptr)) { // Compute the position in the sequence (within the CTA for the moment). int row = tidx / THREADS_PER_ROW; // Compute the position of the thread in the row. int col = tidx % THREADS_PER_ROW; // Store the row as we need it to disable the loads. row_ = row; // The row offset in the batched GEMM. For each seq element, we store QKV in that order. int64_t row_offset = (int64_t)row * params.qkv_stride_in_bytes; // Add the block index. row_offset += (int64_t)((binfo.sum_s * NUM_MATS + qkv_offset) * binfo.h + binfo.bidh) * BYTES_PER_ROW; // Assemble the final pointer. qkv_ptr_ += row_offset + col * BYTES_PER_LDG; } // Store data to shared memory. template< typename Smem_tile > inline __device__ void commit(Smem_tile &smem_tile) { smem_tile.store(fetch_); } // Load data from memory. template< typename Smem_tile > inline __device__ void load(Smem_tile &smem_tile) { const void *ptrs[LDGS]; uint32_t preds[LDGS]; #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { ptrs[ii] = qkv_ptr_ + (int64_t)ii * ROWS_PER_LDG * params_qkv_stride_in_bytes_; preds[ii] = ((row_ + ii * ROWS_PER_LDG) < min(ROWS, actual_seqlen)); fetch_[ii] = make_uint4(0, 0, 0, 0); } // not packing predicates removes restrictions (e.g. FP16 384, 4 warps) Ldg_functor fct(fetch_, ptrs); #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { fct.load(ii, preds[ii]); } } // Store data to memory. inline __device__ void store(const uint4 (&data)[LDGS]) { #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { char *ptr = qkv_ptr_ + (int64_t)ii * ROWS_PER_LDG * params_qkv_stride_in_bytes_; if( (row_ + ii * ROWS_PER_LDG) < min(ROWS, actual_seqlen) ) { fmha::stg(ptr, data[ii]); } } } // Move the pointer to the next location. inline __device__ void move() { qkv_ptr_ += (int64_t)ROWS * params_qkv_stride_in_bytes_; actual_seqlen -= ROWS; } // The stride between rows for the QKV matrice. int64_t params_qkv_stride_in_bytes_; // The pointer. char *qkv_ptr_; // The fetch registers. uint4 fetch_[LDGS]; // Keep track of the row the thread is processing as we move the tile. int row_; // The length of the sequence loaded by that memory tile. int actual_seqlen; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile > struct Gmem_tile_o { // The mma tile. using Mma_tile = fmha::Hmma_tile; // The size of each element. enum { BYTES_PER_ELEMENT = 2 }; // The size of a row in bytes. enum { BYTES_PER_ROW = Cta_tile::N * BYTES_PER_ELEMENT }; // The number of threads to store a "row" of the matrix. enum { THREADS_PER_ROW = 16 }; // The size of each STG. enum { BYTES_PER_STG = BYTES_PER_ROW / THREADS_PER_ROW }; // The number of "rows" stored per iteration of the loop. The output of 1 MMA. enum { ROWS = Cta_tile::M }; // The number of "rows" stored per iteration of the loop. The output of 1 MMA. enum { ROWS_PER_LOOP = ROWS <= 64 ? ROWS : (int)Mma_tile::M_PER_MMA_PER_CTA }; // The number of outter loop for the stores. enum { LOOPS = ROWS / ROWS_PER_LOOP }; // The number of "rows" stored per STG. enum { ROWS_PER_STG = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Do we have to guard against partial writes/reads. enum { HAS_INCOMPLETE_STG = Cta_tile::M % ROWS_PER_STG != 0 }; // The number of STGs needed to store a chunk of the Q matrix. enum { STGS_PER_LOOP = fmha::Div_up::VALUE }; // The number of STGs needed to store a chunk of the Q matrix in total. enum { STGS = STGS_PER_LOOP * LOOPS }; // Ctor. template inline __device__ Gmem_tile_o(const Params ¶ms, const BInfo &binfo, int tidx) : params_o_stride_in_bytes_(params.o_stride_in_bytes) , actual_seqlen_(binfo.actual_seqlen) , o_ptr_(reinterpret_cast(params.o_ptr)) { // Compute the position in the sequence (within the CTA for the moment). int row = tidx / THREADS_PER_ROW; // Compute the position of the thread in the row. int col = tidx % THREADS_PER_ROW; // Store the row as we need it to disable loads. row_ = row; // The row offset in the batched GEMM. int64_t row_offset = (int64_t)row * params.o_stride_in_bytes + binfo.bidx * BYTES_PER_ROW; // Assemble the final pointer. o_ptr_ += row_offset + col * BYTES_PER_STG; // Is that thread active on the last STG? if( HAS_INCOMPLETE_STG ) { is_active_for_last_stg_ = row + (STGS - 1) * ROWS_PER_STG < Cta_tile::M; } } // Store data to global memory. inline __device__ void store(const uint4 (&src)[STGS_PER_LOOP], int mi) { #pragma unroll for( int ii = 0; ii < STGS_PER_LOOP; ++ii ) { int jj = mi * STGS_PER_LOOP + ii; if( this->row_ + jj * ROWS_PER_STG >= this->actual_seqlen_ ) { break; } float x = reinterpret_cast(src[ii].x); float y = reinterpret_cast(src[ii].y); float z = reinterpret_cast(src[ii].z); float w = reinterpret_cast(src[ii].w); uint2 out = float4_to_half4(x, y, z, w); if( !HAS_INCOMPLETE_STG || (jj < STGS - 1 || this->is_active_for_last_stg_) ) { fmha::stg(this->o_ptr_ + jj * ROWS_PER_STG * this->params_o_stride_in_bytes_, out); } } } // Move the pointer to the next location. inline __device__ void move() { row_ += ROWS; o_ptr_ += (int64_t)ROWS * params_o_stride_in_bytes_; } // The stride between rows for the QKV matrice. int64_t params_o_stride_in_bytes_; // The pointer. char *o_ptr_; // Is the thread active for the last STG? int is_active_for_last_stg_; // Keep track of the row to disable loads. int row_; // The length of the sequence loaded by that memory tile. int actual_seqlen_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, int BYTES_PER_ELEMENT > struct Gmem_tile_mma_sd { // The mma tile. using Mma_tile = fmha::Hmma_tile; // Each STG stores 8 elements. enum { BYTES_PER_STG = BYTES_PER_ELEMENT * 8 }; // The number of MMAs in the M dimension. enum { MMAS_M = Mma_tile::MMAS_M }; // The number of MMAs in the N dimension. enum { MMAS_N = Mma_tile::MMAS_N }; // The number of rows computed per MMA per thread block. enum { M_PER_MMA_PER_CTA = Mma_tile::M_PER_MMA_PER_CTA }; // The number of cols computed per MMA per thread block. enum { N_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA }; // The number of threads per block. enum { THREADS_PER_CTA = Cta_tile::THREADS_PER_CTA }; // The size of each row in bytes. I.e. how many bytes are stored per STG. enum { BYTES_PER_ROW = THREADS_PER_CTA * BYTES_PER_STG }; // The fixed sequence length. enum { SEQLEN = Cta_tile::N }; // The distance between two blocks (in bytes). enum { BLOCK_STRIDE_BYTES = SEQLEN * SEQLEN * BYTES_PER_ELEMENT }; // The distance between elements stored per loop (in bytes). enum { LOOP_STRIDE_BYTES = MMAS_M * MMAS_N * BYTES_PER_ROW }; // The type of elements stored per STG. using Type = typename fmha::Uint_from_size_in_bytes::Type; // Ctor. template inline __device__ Gmem_tile_mma_sd(void *ptr, const Params ¶ms, const int tidx) : ptr_(static_cast(ptr)) { // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The block index. size_t bidx = bidb * params.h + bidh; // Set store location for each thread at the beginning of the loop ptr_ += bidx * BLOCK_STRIDE_BYTES + tidx * BYTES_PER_STG; } // Store to global memory. inline __device__ void store(const Type &data, const int mi, const int ni) { size_t offset = (mi * MMAS_N + ni) * BYTES_PER_ROW; fmha::stg(ptr_ + offset, data); } // Load from global memory. inline __device__ void load(Type &data, const int mi, const int ni) { size_t offset = (mi * MMAS_N + ni) * BYTES_PER_ROW; fmha::ldg(data, ptr_ + offset); } // Move to the next tile. inline __device__ void move() { ptr_ += LOOP_STRIDE_BYTES; } // The pointer in global memory. char *ptr_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, typename Base = Gmem_tile_mma_sd > struct Gmem_tile_mma_s : public Base { // The number of mmas in the vertical dimension. enum { M = Base::MMAS_M }; // The number of mmas in the horizontal dimension. enum { N = Base::MMAS_N }; // The type of the vectors stored by each STG. using Type = typename Base::Type; // Ctor. template< typename Params > inline __device__ Gmem_tile_mma_s(void *ptr, const Params ¶ms, const int tidx) : Base(ptr, params, tidx) { } // Store to global memory. template inline __device__ void store(const float (&softmax)[2 * M][4 * N], const Mask &mask) { #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { float tmp00 = softmax[2 * mi + 0][4 * ni + 0]; float tmp01 = softmax[2 * mi + 0][4 * ni + 1]; float tmp02 = softmax[2 * mi + 0][4 * ni + 2]; float tmp03 = softmax[2 * mi + 0][4 * ni + 3]; float tmp10 = softmax[2 * mi + 1][4 * ni + 0]; float tmp11 = softmax[2 * mi + 1][4 * ni + 1]; float tmp12 = softmax[2 * mi + 1][4 * ni + 2]; float tmp13 = softmax[2 * mi + 1][4 * ni + 3]; uint4 dst; dst.x = fmha::float2_to_half2(tmp00, tmp01); dst.y = fmha::float2_to_half2(tmp02, tmp03); dst.z = fmha::float2_to_half2(tmp10, tmp11); dst.w = fmha::float2_to_half2(tmp12, tmp13); if( mask.is_valid(mi, ni, 0, 0) ) { Base::store(dst, mi, ni); } } } } // Load from global memory. template inline __device__ void load(uint4 (®s)[M][N], const Mask &mask) { #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { regs[mi][ni] = make_uint4(0, 0, 0, 0); if( mask.is_valid(mi, ni, 0, 0) ) { Base::load(regs[mi][ni], mi, ni); } } } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The base class. typename Base = fmha::Gmem_tile_qkv > struct Gmem_tile_dout : public Base { // Ctor. template inline __device__ Gmem_tile_dout(const Params ¶ms, const BInfo &binfo, int tidx) : Base(params, 0, binfo, tidx) { this->qkv_ptr_ = reinterpret_cast(params.o_ptr); this->params_qkv_stride_in_bytes_ = params.o_stride_in_bytes; // needed for move // Compute the position of the thread in the row. int col = tidx % Base::THREADS_PER_ROW; // The row offset in the batched GEMM. For each seq element, we store O in that order. int64_t row_offset = (int64_t)this->row_ * params.o_stride_in_bytes + binfo.bidx * Base::BYTES_PER_ROW; // Assemble the final pointer. this->qkv_ptr_ += row_offset + col * Base::BYTES_PER_LDG; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, typename Base = fmha::Gmem_tile_o > struct Gmem_tile_dq : public Base { // Ctor. template inline __device__ Gmem_tile_dq(const Params ¶ms, const BInfo &binfo, int tidx) : Base(params, binfo, tidx) { this->o_ptr_ = reinterpret_cast(params.dqkv_ptr); this->params_o_stride_in_bytes_ = params.qkv_stride_in_bytes; // needed for move // Compute the position of the thread in the row. int col = tidx % Base::THREADS_PER_ROW; // The row offset in the batched GEMM. For each seq element, we store O in that order. int64_t row_offset = (int64_t)this->row_ * params.qkv_stride_in_bytes + (binfo.sum_s * 3 * binfo.h + binfo.bidh) * Base::BYTES_PER_ROW; // Assemble the final pointer. this->o_ptr_ += row_offset + col * Base::BYTES_PER_STG; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/kernel_traits.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once //////////////////////////////////////////////////////////////////////////////////////////////////// template struct FMHA_kernel_traits { // The CTA description for the 1st GEMM. using Cta_tile_p = fmha::Cta_tile_extd; // The CTA description for the 2nd GEMM. using Cta_tile_o = fmha::Cta_tile_extd; // Do we use one buffer for K and V. enum { SHARE_SMEM_FOR_K_AND_V = (FLAGS & 0x8u) != 0u }; // The global memory tile to load Q. using Gmem_tile_q = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle Q. using Smem_tile_q = fmha::Smem_tile_a; // The global memory tile to load K. using Gmem_tile_k = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle K. using Smem_tile_k = fmha::Smem_tile_b; // The global memory tile to load V. using Gmem_tile_v = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle V. using Smem_tile_v = fmha::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = fmha::Gmem_tile_o; // The shared memory tile for O. using Smem_tile_o = fmha::Smem_tile_o; // The global memory tile to load/store S. using Gmem_tile_s = fmha::Gmem_tile_mma_s; // The shared memory tile to transpose S. using Smem_tile_st = fmha::Smem_tile_mma_transposed; using Gmem_tile_do = fmha::Gmem_tile_dout; // Make sure the number of threads match. static_assert((int)Gmem_tile_o::THREADS_PER_ROW == (int)Smem_tile_o::THREADS_PER_ROW, ""); // The number of threads. enum { THREADS = Cta_tile_p::THREADS_PER_CTA }; // Make sure the number of threads matches both CTAs. static_assert((int)THREADS == (int)Cta_tile_o::THREADS_PER_CTA, ""); // The amount of shared memory needed to load Q and K. enum { BYTES_PER_SMEM_QK = Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE }; // The extra amount of shared memory needed to load V. enum { BYTES_PER_SMEM_V = SHARE_SMEM_FOR_K_AND_V ? 0u : Smem_tile_v::BYTES_PER_TILE }; // The amount of shared memory needed for Q, K and V.. enum { BYTES_PER_SMEM_QKV = BYTES_PER_SMEM_QK + BYTES_PER_SMEM_V }; // The amount of shared memory needed to load Q and store O. enum { BYTES_PER_SMEM_QO = Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE }; // The amount of shared memory needed for Q, K, V and O. enum { BYTES_PER_SMEM = fmha::Max::VALUE }; // Make sure we have enough shared memory. static_assert(Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE <= BYTES_PER_SMEM, ""); }; //////////////////////////////////////////////////////////////////////////////////////////////////// ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/mask.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { template struct Mask { using Mma_tile = fmha::Hmma_tile; template __device__ Mask(const Params ¶ms, const BInfo &blockInfo, int tidx) { actual_seqlen = blockInfo.actual_seqlen; const int warp = tidx / Cta_tile::THREADS_PER_WARP; const int lane = tidx % Cta_tile::THREADS_PER_WARP; static_assert(Cta_tile::WARPS_K == 1, ""); // find the warp in the Cta tile const int warp_n = (warp / Cta_tile::WARPS_M); const int warp_m = (warp % Cta_tile::WARPS_M); // decompose warp into 8x4 tile const int quad = lane / 4; const int tid = (lane % 4) * 2; row = warp_m * 16 + quad; col = warp_n * 16 + tid; } inline __device__ bool is_valid(const int mi, const int ni, const int ii, const int jj) const { // ii and jj iterate over the 2x4 fragment const bool col_valid = (ni * Mma_tile::N_PER_MMA_PER_CTA + col + (jj & 2) * 4 + (jj & 1)) < actual_seqlen; //&& (row + mi * Mma_tile::M_PER_MMA_PER_CTA + ii * 8) < actual_seqlen; return col_valid; // return row_valid && col_valid; } inline __device__ void load(int it) { row_offset = it * Cta_tile::M + row; } int row_offset; int row; int col; int actual_seqlen; }; } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/smem_tile.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The description of the tile computed by this CTA. typename Cta_tile, // The number of rows in the 2D shared memory buffer. int M_, // The number of cols. int N_, // The size in bits of each element. int BITS_PER_ELEMENT_, // The number of bytes per STS. int BYTES_PER_STS_ = 16, // The number of buffers. (Used in multistage and double buffer cases.) int BUFFERS_PER_TILE_ = 1, // Do we enable the fast path for LDS.128 and friends. int ENABLE_LDS_FAST_PATH_ = 0, // The number of rows that are used for the XOR swizzling to allow fast STS/LDS. int ROWS_PER_XOR_PATTERN_ = 8, // The number of cols that are used for the XOR swizzling to allow fast STS/LDS. int COLS_PER_XOR_PATTERN_ = 1, // Use or not predicates bool USE_PREDICATES_ = true > struct Smem_tile_without_skews { // The size in bits of each element. enum { BITS_PER_ELEMENT = BITS_PER_ELEMENT_ }; // The size in bytes of a single STS. enum { BYTES_PER_STS = BYTES_PER_STS_ }; // The number of elements per STS. enum { ELEMENTS_PER_STS = BYTES_PER_STS * 8 / BITS_PER_ELEMENT }; // To support arbitrary N, we pad some values to a power-of-2. enum { N_WITH_PADDING = Next_power_of_two::VALUE }; // The number of bytes per row without packing of rows. enum { BYTES_PER_ROW_BEFORE_PACKING = N_WITH_PADDING * BITS_PER_ELEMENT / 8 }; // The number of bytes per row -- we want at least 128B per row. enum { BYTES_PER_ROW = Max::VALUE }; // The number of rows in shared memory (two rows may be packed into a single one). enum { ROWS = M_ * BYTES_PER_ROW_BEFORE_PACKING / BYTES_PER_ROW }; // The number of threads per row. enum { THREADS_PER_ROW_UNBOUNDED = BYTES_PER_ROW / BYTES_PER_STS }; // The number of threads per row. enum { THREADS_PER_ROW = Min::VALUE }; // The number of STS per row. enum { STS_PER_ROW = BYTES_PER_ROW / THREADS_PER_ROW / BYTES_PER_STS }; // It must be at least one. static_assert(STS_PER_ROW >= 1, ""); // The number of rows written with a single STS. enum { ROWS_PER_STS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Make sure we write to at least one row per STS. Thanks Dr. Obvious ;) static_assert(ROWS_PER_STS >= 1, ""); // The number of STS needed to store all rows. enum { STS_PER_COL = Div_up::VALUE }; // The number of STS in total. enum { STS = STS_PER_COL * STS_PER_ROW }; // The size of one buffer in bytes in shared memory. enum { BYTES_PER_BUFFER = STS * BYTES_PER_STS * Cta_tile::THREADS_PER_CTA }; // The number of buffers. enum { BUFFERS_PER_TILE = BUFFERS_PER_TILE_ }; // The size in bytes of total buffers. enum { BYTES_PER_TILE = BYTES_PER_BUFFER * BUFFERS_PER_TILE }; // The boundary for smem_read_offset and smem_write_offset increment. enum { BYTES_PER_TILE_INC_BOUNDARY = BYTES_PER_TILE - BYTES_PER_BUFFER }; // Do we enable the LDS.128 fast path? enum { ENABLE_LDS_FAST_PATH = ENABLE_LDS_FAST_PATH_ }; static_assert(ENABLE_LDS_FAST_PATH == 0); // The number of rows that are used for the XOR swizzling to allow fast STS/LDS. enum { ROWS_PER_XOR_PATTERN = ROWS_PER_XOR_PATTERN_ }; // The number of cols that are used for the XOR swizzling to allow fast STS/LDS. enum { COLS_PER_XOR_PATTERN = COLS_PER_XOR_PATTERN_ * 16 / BYTES_PER_STS }; // Use or not predicates enum { USE_PREDICATES = USE_PREDICATES_ }; // The type of elements that are stored in shared memory by each thread. using Store_type = typename Uint_from_size_in_bytes::Type; // Ctor. inline __device__ Smem_tile_without_skews(void *smem, int tidx) : smem_(__nvvm_get_smem_pointer(smem)) { // The row written by a thread. See doc/mma_smem_layout.xlsx. int smem_write_row = tidx / THREADS_PER_ROW; // The XOR pattern. int smem_write_xor = smem_write_row % ROWS_PER_XOR_PATTERN * COLS_PER_XOR_PATTERN; // Compute the column and apply the XOR pattern. int smem_write_col = (tidx % THREADS_PER_ROW) ^ smem_write_xor; // The offset. this->smem_write_offset_ = smem_write_row*BYTES_PER_ROW + smem_write_col*BYTES_PER_STS; // TODO: Why not merge it with the read offset? this->smem_read_buffer_ = __shfl_sync(0xffffffff, 0, 0); this->smem_write_buffer_ = __shfl_sync(0xffffffff, 0, 0); } // Compute the store pointers. template< int N > inline __device__ void compute_store_pointers(uint32_t (&ptrs)[N]) { #pragma unroll for( int ii = 0; ii < N; ++ii ) { // Decompose the STS into row/col. int row = ii / STS_PER_ROW; int col = ii % STS_PER_ROW; // Assemble the offset. int offset = smem_write_offset_ + row*ROWS_PER_STS*BYTES_PER_ROW; // Take the column into account. if( STS_PER_ROW > 1 ) { offset += col*THREADS_PER_ROW*BYTES_PER_STS; } // Apply the XOR pattern if needed. if( ROWS_PER_STS < ROWS_PER_XOR_PATTERN ) { const int m = row * ROWS_PER_STS % ROWS_PER_XOR_PATTERN; offset ^= m * COLS_PER_XOR_PATTERN * BYTES_PER_STS; } // Assemble the final pointer :) ptrs[ii] = smem_ + offset + smem_write_buffer_; } } inline __device__ void debug_reset() { for( int buffer = 0; buffer < BYTES_PER_TILE; buffer += BYTES_PER_BUFFER) { for( int row = 0; row < ROWS; ++row ) { for( int col = 0; col < BYTES_PER_ROW; col += 4 ) { if( threadIdx.x == 0 ) { uint32_t val = 0x0; sts(val, smem_ + row*BYTES_PER_ROW + col + buffer); } } } } } // Print the content of the tile (only for debug ;)). inline __device__ void debug_print() const { for( int buffer = 0; buffer < BYTES_PER_TILE; buffer += BYTES_PER_BUFFER) { for( int row = 0; row < ROWS; ++row ) { for( int col = 0; col < BYTES_PER_ROW; col += 4 ) { if( threadIdx.x == 0 ) { uint32_t val; lds(val, smem_ + row*BYTES_PER_ROW + col + buffer); printf("block=(x=%2d, y=%2d, z=%2d) (smem_=%2d, buffer=%2d, row=%2d, byte=%4d)=0x%08x\n", blockIdx.x, blockIdx.y, blockIdx.z, smem_, buffer, row, col, val); } } } } } // Move the read offset to next buffer. inline __device__ void move_to_next_read_buffer() { if( BUFFERS_PER_TILE > 1 && smem_read_buffer_ >= BYTES_PER_TILE_INC_BOUNDARY ) { this->smem_read_buffer_ -= BYTES_PER_TILE_INC_BOUNDARY; } else if( BUFFERS_PER_TILE > 1 ) { this->smem_read_buffer_ += BYTES_PER_BUFFER; } } // Move the read offset to next buffer. TODO: Remove this member function!!! inline __device__ void move_next_read_buffer() { this->move_to_next_read_buffer(); } // Move the read offset to next N buffer (circular-buffer). inline __device__ void move_to_next_read_buffer(int N) { if( BUFFERS_PER_TILE > 1 ) { this->smem_read_buffer_ += N * BYTES_PER_BUFFER; this->smem_read_buffer_ -= smem_read_buffer_ >= BYTES_PER_TILE ? BYTES_PER_TILE : 0; } } // Move the read offset to next N buffer (circular-buffer). TODO: Remove this member function!!! inline __device__ void move_next_read_buffer(int N) { this->move_to_next_read_buffer(N); } // Move the write offset to next buffer. inline __device__ void move_to_next_write_buffer() { if( BUFFERS_PER_TILE > 1 && smem_write_buffer_ >= BYTES_PER_TILE_INC_BOUNDARY ) { this->smem_write_buffer_ -= BYTES_PER_TILE_INC_BOUNDARY; } else if( BUFFERS_PER_TILE > 1 ) { this->smem_write_buffer_ += BYTES_PER_BUFFER; } } // Move the write offset to next buffer. TODO: Remove that member function! inline __device__ void move_next_write_buffer() { this->move_to_next_write_buffer(); } // Move the read offset. inline __device__ void move_read_offset(int delta) { this->smem_read_offset_ += delta; } // Move the write offset. inline __device__ void move_write_offset(int delta) { this->smem_write_offset_ += delta; } // Store to the tile in shared memory. template< int N > inline __device__ void store(const Store_type (&data)[N], uint64_t = 0) { uint32_t smem_ptrs[N]; this->compute_store_pointers(smem_ptrs); sts(smem_ptrs, data); } // Store to the tile in shared memory. template< int N, int M > inline __device__ void store(const Store_type (&data)[N], uint32_t (&preds)[M], uint64_t = 0) { uint32_t smem_ptrs[N]; this->compute_store_pointers(smem_ptrs); sts(smem_ptrs, data, preds); } // Store to the tile in shared memory. template< int N > inline __device__ void store(const Store_type (&data)[N], uint32_t preds, uint64_t = 0) { this->store(data, preds); } // Store to the tile in shared memory. template< int N > inline __device__ void store(const void* (&gmem_ptrs)[N], uint32_t preds, uint64_t = 0) { uint32_t tmp[1] = { preds }; this->store(gmem_ptrs, tmp); } // The shared memory pointer. uint32_t smem_; // The read offset. Reserve 4 offsets if needed. int smem_read_offset_; // The write offset. int smem_write_offset_; // The buffer base offset for read. int smem_read_buffer_; // The buffer base offset for write. int smem_write_buffer_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The layout of the tile. typename Layout, // The size of the STS. int BYTES_PER_STS = 16, // The number of buffers per tile. int BUFFERS_PER_TILE = 1, // Use or not predicates bool USE_PREDICATES = true > struct Smem_tile_a { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K, int MMAS_K_WITH_PADDING > struct Compute_reset_mask { // The potential mask. enum { HALF = MMAS_K_WITH_PADDING / 2 }; // The remainder. enum { MOD = MMAS_K % HALF }; // The final value. enum { VALUE = (MMAS_K == MOD ? 0 : HALF) | Compute_reset_mask::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K_WITH_PADDING > struct Compute_reset_mask<0, MMAS_K_WITH_PADDING> { enum { VALUE = 0 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K > struct Compute_reset_mask { enum { VALUE = MMAS_K - 1 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_a { // The size in bits. enum { N_IN_BITS = N * fmha::BITS_PER_ELEMENT_A }; // The number of rows. enum { VALUE = N_IN_BITS <= 256 ? 2 : (N_IN_BITS <= 512 ? 4 : 8) }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_row_a : public Rows_per_xor_pattern_a { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_row_a::VALUE > struct Smem_tile_row_a : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_a; // When we use padding to reach a power of two, special care has to be taken. using Cta_tile_with_padding = Cta_tile_with_k_with_padding; // The number of MMAs. using Mma_tile_with_padding = fmha::Hmma_tile; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // Ctor. inline __device__ Smem_tile_row_a(void *smem, int tidx) : Base(smem, tidx) { // For documentation on the layout, see doc/mma_smem_layout.xlsx. // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(WARPS_M == 1); static_assert(WARPS_N == 4 || WARPS_N == 8); static_assert(WARPS_K == 1); static_assert(Base::ROWS_PER_XOR_PATTERN == 8); // The row and column read by the thread. int smem_read_row = (tidx & 0x0f); int smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Load from shared memory. inline __device__ void load(Fragment (&a)[Mma_tile::MMAS_M], int ki) { #pragma unroll for( int mi = 0; mi < Mma_tile::MMAS_M; ++mi ) { // Jump by as many matrix rows as needed (a row in smem may pack multiple matrix rows). int offset = mi * Mma_tile::M_PER_MMA_PER_CTA * Base::BYTES_PER_ROW_BEFORE_PACKING; // Load using LDSM.M88.4. uint4 tmp; ldsm(tmp, this->smem_ + this->smem_read_offset_ + this->smem_read_buffer_ + offset); // Store the value into the fragment. a[mi].reg(0) = tmp.x; a[mi].reg(1) = tmp.y; a[mi].reg(2) = tmp.z; a[mi].reg(3) = tmp.w; } // Move the offset to the next possition. See doc/mma_smem_layout.xlsx. static_assert(Mma_tile_with_padding::MMAS_K < 64, "Not implemented"); if( Mma_tile_with_padding::MMAS_K >= 32 && ki % 16 == 15 ) { this->smem_read_offset_ ^= 31 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 16 && ki % 8 == 7 ) { this->smem_read_offset_ ^= 15 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 8 && ki % 4 == 3 ) { this->smem_read_offset_ ^= 7 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 4 && ki % 2 == 1 ) { this->smem_read_offset_ ^= 3 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= 1 * BYTES_PER_LDS * 2; } } // Reset the read offset. inline __device__ void reset_read_offset() { // The number of MMAs in the K dimension. enum { MMAS_K = Mma_tile::MMAS_K }; // The number of MMAs in the K dimension when we include padding. enum { MMAS_K_WITH_PADDING = Mma_tile_with_padding::MMAS_K }; // Assemble the mask. enum { MASK = Compute_reset_mask::VALUE }; // Reset the read offset. this->smem_read_offset_ ^= MASK * BYTES_PER_LDS * 2; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_a : public Smem_tile_row_a { // The base class. using Base = Smem_tile_row_a; // Ctor. inline __device__ Smem_tile_a(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The layout of the tile. typename Layout, // The size of the STS. int BYTES_PER_STS = 16, // The number of buffers per tile. int BUFFERS_PER_TILE = 1, // Use or not predicates bool USE_PREDICATES = true > struct Smem_tile_b { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_b { // The size in bits. enum { N_IN_BITS = N * fmha::BITS_PER_ELEMENT_B }; // The number of rows. enum { VALUE = N_IN_BITS <= 256 ? 2 : (N_IN_BITS <= 512 ? 4 : 8) }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_col_b : public Rows_per_xor_pattern_b { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_col_b::VALUE > struct Smem_tile_col_b : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_b< Col>; // When we use padding to reach a power of two, special care has to be taken. using Cta_tile_with_padding = Cta_tile_with_k_with_padding< Cta_tile>; // The number of MMAs. using Mma_tile_with_padding = fmha::Hmma_tile; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // The number of STS per thread enum { STS_PER_THREAD_ = Base::ROWS * Base::THREADS_PER_ROW / Cta_tile::THREADS_PER_CTA }; // The number of STS per thread must be at least 1. enum { STS_PER_THREAD = Max<1, STS_PER_THREAD_>::VALUE }; // Ctor. inline __device__ Smem_tile_col_b(void *smem, int tidx) : Base(smem, tidx) { // For documentation on the layout, see doc/mma_smem_layout.xlsx. // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(Base::ROWS_PER_XOR_PATTERN == 8); static_assert(WARPS_M == 1); static_assert(WARPS_N == 4 || WARPS_N == 8); static_assert(WARPS_K == 1); // The masks to select the warps. const int WARP_MASK_N = Warp_masks::N; // The divisor for the warps. const int WARP_DIV_N = WARPS_M * 1 * Cta_tile::THREADS_PER_WARP; // The row and column read by the thread. int smem_read_row = (tidx & WARP_MASK_N) / WARP_DIV_N * Mma_tile::N_PER_MMA + (tidx & 0x07) + (tidx & 0x10) / 2; int smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & 0x08) / 8; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Jump by as many matrix rows as needed (a row in smem may pack multiple matrix rows). int offset = ni * Mma_tile::N_PER_MMA_PER_CTA * Base::BYTES_PER_ROW_BEFORE_PACKING; // Load using LDSM.M88.4. uint4 tmp; ldsm(tmp, this->smem_ + this->smem_read_offset_ + this->smem_read_buffer_ + offset); // Store the value into the fragment. b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; } // Move the offset to the next possition. See doc/mma_smem_layout.xlsx. static_assert(Mma_tile_with_padding::MMAS_K < 64, "Not implemented"); if( Mma_tile_with_padding::MMAS_K >= 32 && ki % 16 == 15 ) { this->smem_read_offset_ ^= 31 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 16 && ki % 8 == 7 ) { this->smem_read_offset_ ^= 15 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 8 && ki % 4 == 3 ) { this->smem_read_offset_ ^= 7 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 4 && ki % 2 == 1 ) { this->smem_read_offset_ ^= 3 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= 1 * BYTES_PER_LDS * 2; } } // Reset the read offset. inline __device__ void reset_read_offset() { // The number of MMAs in the K dimension. enum { MMAS_K = Mma_tile::MMAS_K }; // The number of MMAs in the K dimension when we include padding. enum { MMAS_K_WITH_PADDING = Mma_tile_with_padding::MMAS_K }; // Assemble the mask. enum { MASK = Compute_reset_mask::VALUE }; // Reset the read offset. this->smem_read_offset_ ^= MASK * BYTES_PER_LDS * 2; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_b< Cta_tile, Col, BYTES_PER_STS, BUFFERS_PER_TILE > : public Smem_tile_col_b { // The base class. using Base = Smem_tile_col_b< Cta_tile, BYTES_PER_STS, BUFFERS_PER_TILE>; // Ctor. inline __device__ Smem_tile_b(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_row_b : public Rows_per_xor_pattern_b< N> { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_row_b::VALUE, // How many cols to use for the XOR pattern to avoid bank conflicts? int COLS_PER_XOR_PATTERN_ = 1 > struct Smem_tile_row_b : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_b; // Can we use LDSM? No if the data type is 32-bit large. enum { USE_LDSMT = fmha::BITS_PER_ELEMENT_B == 16 }; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = USE_LDSMT ? 16 : 4 }; // The number of elements per LDS. enum { ELEMENTS_PER_LDS = BYTES_PER_LDS * 8 / fmha::BITS_PER_ELEMENT_B }; // The number of STS per thread enum { STS_PER_THREAD_ = Base::ROWS * Base::THREADS_PER_ROW / Cta_tile::THREADS_PER_CTA }; // The number of STS per thread must be at least 1. enum { STS_PER_THREAD = Max<1, STS_PER_THREAD_>::VALUE }; // Ctor. inline __device__ Smem_tile_row_b(void *smem, int tidx) : Base(smem, tidx) { // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(WARPS_K == 1); static_assert(WARPS_M == 4 || WARPS_M == 8); static_assert(WARPS_N == 1); // The masks to select the warps. const int WARP_MASK_N = Warp_masks::N; const int WARP_MASK_K = Warp_masks::K; // The divisor for the warps. const int WARP_DIV_N = WARPS_M * 1 * Cta_tile::THREADS_PER_WARP; const int WARP_DIV_K = WARPS_M * WARPS_N * Cta_tile::THREADS_PER_WARP; // The row/col read by the thread. int smem_read_row, smem_read_col; static_assert(USE_LDSMT); static_assert(Base::ROWS_PER_XOR_PATTERN == 8); smem_read_row = (tidx & WARP_MASK_K) / WARP_DIV_K * Mma_tile::MMAS_K * 16 + (tidx & 0x07) + (tidx & 0x08); smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & WARP_MASK_N) / WARP_DIV_N * 2 + (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; // Fill zeroes for group conv } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // The size of each element in bits. const int BITS_PER_ELT = fmha::BITS_PER_ELEMENT_B; // The size in bytes of the data needed to compute an MMA per CTA. const int BYTES_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA * BITS_PER_ELT / 8; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( BYTES_PER_MMA_PER_CTA >= 128 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } else if( BYTES_PER_MMA_PER_CTA == 64 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Reset smem_read_offset for odd MMAS_N > 1 (npo2 kernels) if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 && Mma_tile::MMAS_N % 2 == 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { // The size of each element in bits. const int BITS_PER_ELT = fmha::BITS_PER_ELEMENT_B; // The size in bytes of the data needed to compute an MMA per CTA. const int BYTES_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA * BITS_PER_ELT / 8; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Prepare the offset. int offset = ki * Base::ROWS_PER_XOR_PATTERN * 2 * Base::BYTES_PER_ROW; if ( BYTES_PER_MMA_PER_CTA == 32 ) { offset += this->smem_read_offset_; } else if ( BYTES_PER_MMA_PER_CTA == 64 ) { offset += this->smem_read_offset_ + (ni/2) * BYTES_PER_MMA_PER_CTA * 2; } else { offset += this->smem_read_offset_ + (ni ) * BYTES_PER_MMA_PER_CTA; } // Load the data using LDSM.MT88.2. uint32_t ptr = this->smem_ + this->smem_read_buffer_ + offset; uint4 tmp; if( USE_LDSMT ) { ldsmt(tmp, ptr); } else { lds(tmp.x, (ptr ) + 0*Base::BYTES_PER_ROW); lds(tmp.y, (ptr ) + 4*Base::BYTES_PER_ROW); lds(tmp.z, (ptr ^ 32) + 0*Base::BYTES_PER_ROW); lds(tmp.w, (ptr ^ 32) + 4*Base::BYTES_PER_ROW); } // Store those values in the fragment. b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; // Move the pointer for the next ni. I expect the compiler to not recompute those. if( BYTES_PER_MMA_PER_CTA >= 128 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } else if( BYTES_PER_MMA_PER_CTA == 64 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Reset smem_read_offset for odd MMAS_N > 1 (npo2 kernels) if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 && Mma_tile::MMAS_N % 2 == 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_b : public Smem_tile_row_b { // The base class. using Base = Smem_tile_row_b; // Ctor. inline __device__ Smem_tile_b(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_v : public fmha::Smem_tile_without_skews { // The base class. using Base = Smem_tile_without_skews; // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The fragment. using Fragment = Fragment_b< fmha::Col>; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // Ctor. inline __device__ Smem_tile_v(void *smem, int tidx) : Base(smem, tidx) { // The row/col read by the thread. int read_row, read_col; static_assert(Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 1 && (Cta_tile::WARPS_K == 4 || Cta_tile::WARPS_K == 8)); read_row = (tidx & 0xe0) / 2 + (tidx & 0x0f); read_col = (tidx & 0x07); read_col ^= (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = read_row * Base::BYTES_PER_ROW + read_col * BYTES_PER_LDS; } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Jump by 16 * #warps row. int row = ki * 16 * Cta_tile::WARPS_K; // Load the data using LDSM.MT88.2. uint4 tmp; fmha::ldsmt(tmp, this->smem_ + this->smem_read_offset_ + row * Base::BYTES_PER_ROW); b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; // Move the pointer for the next ni. I expect the compiler to not recompute those. if( Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else { assert(false); // Not implemented! } } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_o { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The accumulators. using Accumulator = fmha::Fragment_accumulator; // The accumulators. using Data_type = typename Accumulator::Data_type; // The size of each element. enum { BYTES_PER_ELEMENT = sizeof(Data_type) }; // The size of each STS. enum { BYTES_PER_STS = 8 }; // The size of each row in shared memory. enum { BYTES_PER_ROW = Cta_tile::N * Cta_tile::WARPS_K * BYTES_PER_ELEMENT }; // The size of each LDS. enum { BYTES_PER_LDS = 16 }; enum { THREADS_PER_ROW = 16 }; // The number of rows. enum { ROWS = Cta_tile::M }; // The number of "rows" to process per loop iteration (in the "epilogue"). enum { ROWS_PER_LOOP = ROWS <= 64 ? ROWS : (int)Mma_tile::M_PER_MMA_PER_CTA }; // The number of outer loops. enum { LOOPS = ROWS / ROWS_PER_LOOP }; // Make sure it matches our expectations. static_assert(LOOPS == 1 || LOOPS == (int)Mma_tile::MMAS_M, ""); // The number of rows loaded per LDS. enum { ROWS_PER_LDS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Do we have to guard against partial writes/reads. enum { HAS_INCOMPLETE_LDS = ROWS_PER_LOOP % ROWS_PER_LDS != 0 }; // The total number of LDS per loop. enum { LDS_PER_LOOP = fmha::Div_up::VALUE }; // The amount of shared memory. enum { BYTES_PER_TILE = ROWS_PER_LOOP * BYTES_PER_ROW }; // The write pointer. uint32_t smem_write_, smem_read_; // Is the thread active for the last LDS of the series? int is_active_for_last_lds_; static_assert(BYTES_PER_ROW == 64 * 4 * Cta_tile::WARPS_K); static_assert(LOOPS == 1 || LOOPS == (int)Mma_tile::MMAS_M, ""); // Ctor. inline __device__ Smem_tile_o(void *smem, int tidx) { // Get a 32-bit value for the shared memory address. uint32_t smem_ = __nvvm_get_smem_pointer(smem); static_assert(Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 1 && (Cta_tile::WARPS_K == 4 || Cta_tile::WARPS_K == 8)); int write_row = (tidx & 0x1c) / 4; int write_col = (tidx); // Assemble the write pointer. smem_write_ = smem_ + write_row * BYTES_PER_ROW + write_col * BYTES_PER_STS; // The element read by each thread. int read_row = tidx / THREADS_PER_ROW; int read_col = tidx % THREADS_PER_ROW; // Take the XOR pattern into account for the column. read_col ^= 2 * (read_row & 0x7); // Assemble the read pointer. this->smem_read_ = smem_ + read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; // Is that thread active on the last LDS? if( HAS_INCOMPLETE_LDS ) { this->is_active_for_last_lds_ = read_row + (LDS_PER_LOOP - 1) * ROWS_PER_LDS < Cta_tile::M; } } // Load the output fragments. inline __device__ void load(uint4 (&out)[LDS_PER_LOOP]) const { #pragma unroll for( int ii = 0; ii < LDS_PER_LOOP; ++ii ) { // Load the elements before the reduction (split-K). uint4 tmp[Cta_tile::WARPS_K]; #pragma unroll for( int jj = 0; jj < Cta_tile::WARPS_K; ++jj ) { int imm = ii * ROWS_PER_LDS * BYTES_PER_ROW + jj * Cta_tile::N * BYTES_PER_ELEMENT; if( !HAS_INCOMPLETE_LDS || (ii < LDS_PER_LOOP - 1 || this->is_active_for_last_lds_) ) { fmha::lds(tmp[jj], this->smem_read_ + imm); } } // Perform the reduction. out[ii] = tmp[0]; #pragma unroll for( int jj = 1; jj < Cta_tile::WARPS_K; ++jj ) { out[ii] = fmha::fadd4(out[ii], tmp[jj]); } } } // Store the accumulators. template inline __device__ void store(const Accumulator (&acc)[M][N], int mi) { enum { M_PER_MMA = Mma_tile::M_PER_MMA_PER_CTA }; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // The number of MMAs that are stored per loop iteration. enum { MMAS_M_PER_LOOP = Mma_tile::MMAS_M / LOOPS }; // Store 1st column of the different MMAs. #pragma unroll for( int mj = 0; mj < MMAS_M_PER_LOOP; ++mj ) { // Precompute the immediates to jump between rows. int row_0 = (mj * M_PER_MMA + 0) * BYTES_PER_ROW; int row_1 = (mj * M_PER_MMA + 8) * BYTES_PER_ROW; uint2 tmp0, tmp1; tmp0.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(0); tmp0.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(1); tmp1.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(2); tmp1.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(3); // Store. fmha::sts(this->smem_write_ + row_0, tmp0); fmha::sts(this->smem_write_ + row_1, tmp1); } // Swizzle the write pointer using a XOR of 16B. this->smem_write_ ^= 32; // Store 2nd column of the different MMAs. #pragma unroll for( int mj = 0; mj < MMAS_M_PER_LOOP; ++mj ) { // Precompute the immediates to jump between rows. int row_0 = (mj * M_PER_MMA + 0) * BYTES_PER_ROW; int row_1 = (mj * M_PER_MMA + 8) * BYTES_PER_ROW; uint2 tmp0, tmp1; tmp0.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(4); tmp0.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(5); tmp1.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(6); tmp1.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(7); // Store. fmha::sts(this->smem_write_ + row_0, tmp0); fmha::sts(this->smem_write_ + row_1, tmp1); } // Cancel the previous XOR of 1 + swizzle the write pointer using a XOR of 32B or 64B. this->smem_write_ ^= (ni & 1) ? 7 * 32 : 3 * 32; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_mma { using Mma_tile = fmha::Hmma_tile; using Fragment = fmha::Fragment_a; enum { COLS = Cta_tile::N }; enum { BYTES_PER_ELT = 2 }; enum { BYTES_PER_STS = 4 }; enum { BYTES_PER_ROW = COLS * BYTES_PER_ELT }; // TODO enum { BYTES_PER_TILE = Cta_tile::M * BYTES_PER_ROW }; enum { WARPS_M = Cta_tile::WARPS_M }; enum { WARPS_N = Cta_tile::WARPS_N }; enum { WARPS_K = Cta_tile::WARPS_K }; static_assert(WARPS_K == 1); inline __device__ Smem_tile_mma(char *smem, int tidx) { smem_ = __nvvm_get_smem_pointer(smem); int write_col, write_row; static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8) || (WARPS_M == 4 || WARPS_N == 8) || WARPS_N == 1); if( WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8) ) { write_row = (tidx & 0x1c) / 4; write_col = (tidx & 0xe0) / 4 + (tidx & 0x03); } else { write_row = (tidx & 0xe0) / 2 + (tidx & 0x1c) / 4; write_col = (tidx & 0x03); } write_col ^= (write_row & 0x07) * 4; write_offset_ = write_row * BYTES_PER_ROW + write_col * BYTES_PER_STS; } template inline __device__ void store(const uint4 (®s)[M][N]) { static_assert(COLS == Cta_tile::N); for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = write_offset_ + mi * WARPS_M * 16 * BYTES_PER_ROW + ni * WARPS_N * 16 * BYTES_PER_ELT; fmha::sts(smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].x); fmha::sts(smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].z); offset ^= 4 * BYTES_PER_STS; fmha::sts(smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].y); fmha::sts(smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].w); } } } uint32_t smem_; uint32_t write_offset_; uint32_t warp_m; uint32_t warp_n; uint32_t lane; }; template< typename Cta_tile, typename Base = Smem_tile_mma< Cta_tile>> struct Smem_tile_mma_transposed : public Base { enum { BYTES_PER_LDS = 16 }; enum { BYTES_PER_ROW = Base::BYTES_PER_ROW }; enum { BYTES_PER_ELT = Base::BYTES_PER_ELT }; enum { WARPS_M = Base::WARPS_M }; enum { WARPS_N = Base::WARPS_N }; static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8)); using Fragment = typename Base::Fragment; inline __device__ Smem_tile_mma_transposed(char *smem, int tidx) : Base(smem, tidx) { static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8)); int read_row, read_col; read_row = (tidx & 0x0f); read_col = (tidx & 0xe0) / 16 + (tidx & 0x1c) / 16; read_col ^= (read_row & 0x07); read_offset_ = read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; } template inline __device__ void load(Fragment (&frag)[M][N]) { static_assert(Base::COLS == Cta_tile::N); for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = read_offset_ + mi * WARPS_M * 16 * BYTES_PER_ROW + ni * WARPS_N * 16 * BYTES_PER_ELT; uint4 dst; fmha::ldsmt(dst, this->smem_ + offset); frag[mi][ni].reg(0) = dst.x; frag[mi][ni].reg(1) = dst.z; // Fragment A regs col major! frag[mi][ni].reg(2) = dst.y; frag[mi][ni].reg(3) = dst.w; } } } uint32_t read_offset_; }; template< typename Cta_tile, typename Base = Smem_tile_mma< Cta_tile>> struct Smem_tile_mma_epilogue : public Base { enum { BYTES_PER_LDS = 16 }; enum { BYTES_PER_ROW = Base::BYTES_PER_ROW }; enum { BYTES_PER_ELT = Base::BYTES_PER_ELT }; enum { THREADS_PER_ROW = BYTES_PER_ROW / BYTES_PER_LDS }; static_assert(THREADS_PER_ROW * BYTES_PER_LDS == BYTES_PER_ROW); enum { ROWS_PER_LDS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; enum { NUM_LDS = Cta_tile::M / ROWS_PER_LDS }; static_assert(NUM_LDS * ROWS_PER_LDS == Cta_tile::M); enum { WARPS_M = Base::WARPS_M }; enum { WARPS_N = Base::WARPS_N }; static_assert((WARPS_M == 4 || WARPS_N == 8) || WARPS_N == 1); using Acc = fmha::Fragment_accumulator; inline __device__ Smem_tile_mma_epilogue(char *smem, int tidx) : Base(smem, tidx) { const int read_row = tidx / THREADS_PER_ROW; int read_col = tidx % THREADS_PER_ROW; read_col ^= (read_row & 0x07); read_offset_ = read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; } inline __device__ void load(uint4 (&data)[NUM_LDS]) { for( int ii = 0; ii < NUM_LDS; ii++ ) { size_t offset = read_offset_ + ii * ROWS_PER_LDS * BYTES_PER_ROW; fmha::lds(data[ii], this->smem_ + offset); } } template inline __device__ void store(const Acc (&acc)[M][N]){ #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { // 1st row - 4 elements per row. float tmp00 = acc[mi][ni].elt(0); float tmp01 = acc[mi][ni].elt(1); float tmp02 = acc[mi][ni].elt(4); float tmp03 = acc[mi][ni].elt(5); // 2nd row - 4 elements per row. float tmp10 = acc[mi][ni].elt(2); float tmp11 = acc[mi][ni].elt(3); float tmp12 = acc[mi][ni].elt(6); float tmp13 = acc[mi][ni].elt(7); uint32_t x = fmha::float2_to_half2(tmp00, tmp01); uint32_t y = fmha::float2_to_half2(tmp02, tmp03); uint32_t z = fmha::float2_to_half2(tmp10, tmp11); uint32_t w = fmha::float2_to_half2(tmp12, tmp13); size_t offset = (this->write_offset_ ^ (ni * 32)) + mi * WARPS_M * 16 * BYTES_PER_ROW; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, x); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, z); offset ^= 4 * Base::BYTES_PER_STS; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, y); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, w); } } } template inline __device__ void store(const uint4 (®s)[M][N]) { for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = (this->write_offset_ ^ (ni * 32)) + mi * WARPS_M * 16 * BYTES_PER_ROW; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].x); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].z); offset ^= 4 * Base::BYTES_PER_STS; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].y); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].w); } } } uint32_t read_offset_; }; } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/softmax.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// struct Sum_ { enum { IS_SUM = 1 }; static inline __device__ float apply(float x, float y) { return x + y; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Max_ { enum { IS_SUM = 0 }; static inline __device__ float apply(float x, float y) { return x > y ? x : y; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ float apply_exp_(float x, float max) { return __expf(x - max); } //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Softmax_base { // The Mma tile. using Mma_tile = fmha::Hmma_tile; // The number of MMAs in M/N dimensions. enum { MMAS_M = Mma_tile::MMAS_M }; enum { MMAS_N = Mma_tile::MMAS_N }; // The number of groups of warp such that we have at most 4 warps writing consecutive elements. enum { GROUPS = fmha::Div_up::VALUE }; // The number of elements that we are going to store per row. enum { ELEMENTS_PER_ROW = Cta_tile::WARPS_N / GROUPS }; // The number of rows. enum { ROWS = Cta_tile::M * GROUPS }; // The total number of elements. enum { ELEMENTS = ROWS * ELEMENTS_PER_ROW }; // Ctor. template inline __device__ Softmax_base(const Params ¶ms, void *smem, int bidb, int tidx) : // packed_mask_ptr_(reinterpret_cast(params.packed_mask_ptr)), smem_(reinterpret_cast(smem)), tidx_(tidx) { // Move to the 1st mask loaded by the thread+ tidx; // packed_mask_ptr_ += bidb * params.packed_mask_stride_in_bytes + tidx * sizeof(uint32_t); // Extract the position in the warp. int warp = tidx / Cta_tile::THREADS_PER_WARP; int lane = tidx % Cta_tile::THREADS_PER_WARP; // Decompose the warp index into M and N. int warp_m = warp % Cta_tile::WARPS_M; int warp_n = warp / Cta_tile::WARPS_M; // Decompose the warp-n index into group/position-inside-the-group. int warp_g = warp_n / ELEMENTS_PER_ROW; int warp_i = warp_n % ELEMENTS_PER_ROW; // The location written by the threads. int write_row = warp_g * (ROWS / GROUPS) + warp_m * Mma_tile::M_PER_MMA + lane / 4; int write_col = warp_i; // Assemble the write pointer. smem_write_ = &smem_[write_row * ELEMENTS_PER_ROW + write_col]; // Assemble the read pointer. smem_read_ = &smem_[warp_m * Mma_tile::M_PER_MMA + lane / 4]; } template inline __device__ void apply_mask(const Mask &mask) { #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ii = 0; ii < 2; ++ii ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { #pragma unroll for( int jj = 0; jj < 4; ++jj ) { if( !mask.is_valid(mi, ni, ii, jj) ) { elt_[2 * mi + ii][4 * ni + jj] = -INFINITY; } } } } } } // Apply the exp to all the elements. inline __device__ void apply_exp(const float (&max)[MMAS_M * 2]) { #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N * 4; ++ni ) { elt_[mi][ni] = apply_exp_(elt_[mi][ni], max[mi]); } } } // Do a CTA-wide reduction. template inline __device__ void reduce_1x4(float (&dst)[MMAS_M * 2]) { #if defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) if( Functor::IS_SUM ) { // Apply the summation inside the thread. float tmp[MMAS_M * 2][2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { tmp[mi][0] = 0.f; tmp[mi][1] = 0.f; #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { tmp[mi][0] += elt_[mi][4 * ni + 0]; tmp[mi][0] += elt_[mi][4 * ni + 1]; tmp[mi][1] += elt_[mi][4 * ni + 2]; tmp[mi][1] += elt_[mi][4 * ni + 3]; } dst[mi] = tmp[mi][0] + tmp[mi][1]; } } else #endif // defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) { // Apply the functor for each row inside a thread. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = elt_[mi][0]; #pragma unroll for( int ni = 1; ni < MMAS_N * 4; ++ni ) { dst[mi] = Functor::apply(dst[mi], elt_[mi][ni]); } } } // Apply the functor for each row inside each group of 4 threads. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 1)); __syncwarp(); dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 2)); __syncwarp(); } // Store the different values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { if( tidx_ % 4 == 0 ) { smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 0) * ELEMENTS_PER_ROW] = dst[2 * mi + 0]; smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 8) * ELEMENTS_PER_ROW] = dst[2 * mi + 1]; } } // Make sure the values are in shared memory. __syncthreads(); // Load 8 values (one for each warp). The /8 corresponds to /(4*2) where 4 is from the // float4. float4 tmp[1]; if( tidx_ < Cta_tile::M ) { tmp[0] = reinterpret_cast(&smem_[0 * ELEMENTS / 2])[tidx_]; } // Compute the reduction of those 8 values in a binary-tree fashion. tmp[0].x = Functor::apply(tmp[0].x, tmp[0].y); tmp[0].z = Functor::apply(tmp[0].z, tmp[0].w); tmp[0].x = Functor::apply(tmp[0].x, tmp[0].z); // Make sure we can write to shared memory. __syncthreads(); // Store the value back to shared memory. if( tidx_ < Cta_tile::M ) { smem_[tidx_] = tmp[0].x; } // Make sure the data is in shared memory. __syncthreads(); // Finally read the values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { dst[2 * mi + 0] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 0]; dst[2 * mi + 1] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 8]; } } // Do a CTA-wide reduction. template inline __device__ void reduce_1x8(float (&dst)[MMAS_M * 2]) { #if defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) if( Functor::IS_SUM ) { // Apply the summation inside the thread. float tmp[MMAS_M * 2][2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { tmp[mi][0] = 0.f; tmp[mi][1] = 0.f; #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { tmp[mi][0] += elt_[mi][4 * ni + 0]; tmp[mi][0] += elt_[mi][4 * ni + 1]; tmp[mi][1] += elt_[mi][4 * ni + 2]; tmp[mi][1] += elt_[mi][4 * ni + 3]; } dst[mi] = tmp[mi][0] + tmp[mi][1]; } } else #endif // defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) { // Apply the functor for each row inside a thread. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = elt_[mi][0]; #pragma unroll for( int ni = 1; ni < MMAS_N * 4; ++ni ) { dst[mi] = Functor::apply(dst[mi], elt_[mi][ni]); } } } // Apply the functor for each row inside each group of 4 threads. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 1)); __syncwarp(); dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 2)); __syncwarp(); } // Store the different values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { if( tidx_ % 4 == 0 ) { smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 0) * ELEMENTS_PER_ROW] = dst[2 * mi + 0]; smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 8) * ELEMENTS_PER_ROW] = dst[2 * mi + 1]; } } // Make sure the values are in shared memory. __syncthreads(); // Load 8 values (one for each warp). The /8 corresponds to /(4*2) where 4 is from the // float4. float4 tmp[2]; if( tidx_ < Cta_tile::M ) { tmp[0] = reinterpret_cast(&smem_[0 * ELEMENTS / 2])[tidx_]; tmp[1] = reinterpret_cast(&smem_[1 * ELEMENTS / 2])[tidx_]; } // Compute the reduction of those 8 values in a binary-tree fashion. tmp[0].x = Functor::apply(tmp[0].x, tmp[0].y); tmp[0].z = Functor::apply(tmp[0].z, tmp[0].w); tmp[1].x = Functor::apply(tmp[1].x, tmp[1].y); tmp[1].z = Functor::apply(tmp[1].z, tmp[1].w); tmp[0].x = Functor::apply(tmp[0].x, tmp[0].z); tmp[1].x = Functor::apply(tmp[1].x, tmp[1].z); tmp[0].x = Functor::apply(tmp[0].x, tmp[1].x); // Make sure we can write to shared memory. __syncthreads(); // Store the value back to shared memory. if( tidx_ < Cta_tile::M ) { smem_[tidx_] = tmp[0].x; } // Make sure the data is in shared memory. __syncthreads(); // Finally read the values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { dst[2 * mi + 0] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 0]; dst[2 * mi + 1] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 8]; } } // Do a CTA-wide reduction. template inline __device__ void reduce(float (&dst)[MMAS_M * 2]) { static_assert(Cta_tile::WARPS_M == 1 && (Cta_tile::WARPS_N == 4 || Cta_tile::WARPS_N == 8)); if( Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 4 ) { reduce_1x4(dst); } else if( Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 8 ) { reduce_1x8(dst); } else { assert(false); } // Make sure we are done reading from shared memory. __syncthreads(); } // Scale all the elements. inline __device__ void scale(const float (&sum)[MMAS_M * 2]) { // Precompute the inverse sum to normalize. Without -use_fast_math, it makes a huge deal. float inv_sum[MMAS_M * 2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { inv_sum[mi] = (sum[mi] == 0.f || sum[mi] != sum[mi]) ? 1.f : 1.f / sum[mi]; } // Update the values. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N * 4; ++ni ) { elt_[mi][ni] *= inv_sum[mi]; } } } // The pointer to the mask. const char *packed_mask_ptr_; // Shared memory for the CTA-wide reduction. float *smem_, *smem_write_, *smem_read_; // The current thread index. int tidx_; // The elements. float elt_[MMAS_M * 2][MMAS_N * 4]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Softmax : public Softmax_base { // The base class. using Base = Softmax_base; // The fragment. using Fragment_a = fmha::Fragment_a; static_assert(Fragment_a::NUM_REGS == 4); // The MMAs. enum { MMAS_M = Base::MMAS_M }; enum { MMAS_N = Base::MMAS_N }; // The accumulators. using Accumulator = fmha::Fragment_accumulator; using Accumulator_out = Fragment; static_assert(Accumulator_out::NUM_REGS == 4); static_assert(std::is_same::value); // Ctor. template inline __device__ Softmax(const Params ¶ms, void *smem, int bidb, int tidx) : Base(params, smem, bidb, tidx), params_scale_bmm1_(params.scale_bmm1) { } // Store the tile after softmax. template inline __device__ void store(Gmem_tile &gmem_tile) { Accumulator_out acc[MMAS_M][MMAS_N]; #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { // The elements. float tmp_00 = this->elt_[2 * mi + 0][4 * ni + 0]; float tmp_01 = this->elt_[2 * mi + 0][4 * ni + 1]; float tmp_02 = this->elt_[2 * mi + 0][4 * ni + 2]; float tmp_03 = this->elt_[2 * mi + 0][4 * ni + 3]; float tmp_10 = this->elt_[2 * mi + 1][4 * ni + 0]; float tmp_11 = this->elt_[2 * mi + 1][4 * ni + 1]; float tmp_12 = this->elt_[2 * mi + 1][4 * ni + 2]; float tmp_13 = this->elt_[2 * mi + 1][4 * ni + 3]; // Transform to accumulators. acc[mi][ni].reg(0) = fmha::float2_to_half2(tmp_00, tmp_01); acc[mi][ni].reg(1) = fmha::float2_to_half2(tmp_10, tmp_11); acc[mi][ni].reg(2) = fmha::float2_to_half2(tmp_02, tmp_03); acc[mi][ni].reg(3) = fmha::float2_to_half2(tmp_12, tmp_13); } } // Delegate to the gmem tile to store. gmem_tile.store(acc); } // Pack the data to a fragment for the next GEMM. template inline __device__ void pack(Fragment_a (&dst)[K][M]) const { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ki = 0; ki < K; ++ki ) { // 1st row - 4 elements per row. float tmp_00 = this->elt_[2 * mi + 0][4 * ki + 0]; float tmp_01 = this->elt_[2 * mi + 0][4 * ki + 1]; float tmp_02 = this->elt_[2 * mi + 0][4 * ki + 2]; float tmp_03 = this->elt_[2 * mi + 0][4 * ki + 3]; // 2nd row - 4 elements per row. float tmp_10 = this->elt_[2 * mi + 1][4 * ki + 0]; float tmp_11 = this->elt_[2 * mi + 1][4 * ki + 1]; float tmp_12 = this->elt_[2 * mi + 1][4 * ki + 2]; float tmp_13 = this->elt_[2 * mi + 1][4 * ki + 3]; // Pack to 4 registers. dst[ki][mi].reg(0) = fmha::float2_to_half2(tmp_00, tmp_01); dst[ki][mi].reg(1) = fmha::float2_to_half2(tmp_10, tmp_11); dst[ki][mi].reg(2) = fmha::float2_to_half2(tmp_02, tmp_03); dst[ki][mi].reg(3) = fmha::float2_to_half2(tmp_12, tmp_13); } } } // Scale FP32 fragments inline __device__ void unpack(const Accumulator (&acc)[MMAS_M][MMAS_N]) { const float scalef = reinterpret_cast(this->params_scale_bmm1_); #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { // 1st row - 4 elements per row. this->elt_[2 * mi + 0][4 * ni + 0] = acc[mi][ni].elt(0) * scalef; this->elt_[2 * mi + 0][4 * ni + 1] = acc[mi][ni].elt(1) * scalef; this->elt_[2 * mi + 0][4 * ni + 2] = acc[mi][ni].elt(4) * scalef; this->elt_[2 * mi + 0][4 * ni + 3] = acc[mi][ni].elt(5) * scalef; // 2nd row - 4 elements per row. this->elt_[2 * mi + 1][4 * ni + 0] = acc[mi][ni].elt(2) * scalef; this->elt_[2 * mi + 1][4 * ni + 1] = acc[mi][ni].elt(3) * scalef; this->elt_[2 * mi + 1][4 * ni + 2] = acc[mi][ni].elt(6) * scalef; this->elt_[2 * mi + 1][4 * ni + 3] = acc[mi][ni].elt(7) * scalef; } } } const uint32_t params_scale_bmm1_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha/utils.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr); //////////////////////////////////////////////////////////////////////////////////////////////////// namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// struct Row {}; struct Col {}; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, bool = (M & (M-1)) == 0 > struct Next_power_of_two { }; template< int M > struct Next_power_of_two< M, true > { enum { VALUE = M }; }; template<> struct Next_power_of_two< 3, false> { enum { VALUE = 4 }; }; template<> struct Next_power_of_two< 5, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 6, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 7, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 9, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 10, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 11, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 12, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 13, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 14, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 15, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 24, false> { enum { VALUE = 32 }; }; template<> struct Next_power_of_two< 48, false> { enum { VALUE = 64 }; }; template<> struct Next_power_of_two< 80, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two< 96, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two<112, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two<144, false> { enum { VALUE = 256 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, bool = (N & (N-1)) == 0 > struct Prev_power_of_two { }; template< int N > struct Prev_power_of_two< N, true > { enum { VALUE = N }; }; template<> struct Prev_power_of_two< 3, false> { enum { VALUE = 2 }; }; template<> struct Prev_power_of_two< 5, false> { enum { VALUE = 4 }; }; template<> struct Prev_power_of_two< 6, false> { enum { VALUE = 4 }; }; template<> struct Prev_power_of_two< 7, false> { enum { VALUE = 4 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, int N > struct Div_up { enum { VALUE = (M + N-1) / N }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B > struct Max { enum { VALUE = A >= B ? A : B }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B, int C > struct Max_3 { enum { VALUE = Max::VALUE, C>::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B > struct Min { enum { VALUE = A <= B ? A : B }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int SIZE_IN_BYTES > struct Uint_from_size_in_bytes { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<1> { using Type = uint8_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<2> { using Type = uint16_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<4> { using Type = uint32_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<8> { using Type = uint2; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<16> { using Type = uint4; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int WARPS_M, int WARPS_N, int WARPS_K > struct Warp_masks { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Warp_masks<8, 1, 1> { enum { M = 0xe0, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<4, 2, 1> { enum { M = 0x60, N = 0x80, K = 0x00 }; }; template<> struct Warp_masks<4, 1, 2> { enum { M = 0x60, N = 0x00, K = 0x80 }; }; template<> struct Warp_masks<4, 1, 1> { enum { M = 0x60, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<2, 4, 1> { enum { M = 0x20, N = 0xc0, K = 0x00 }; }; template<> struct Warp_masks<2, 2, 2> { enum { M = 0x20, N = 0x40, K = 0x80 }; }; template<> struct Warp_masks<2, 2, 1> { enum { M = 0x20, N = 0x40, K = 0x00 }; }; template<> struct Warp_masks<2, 1, 2> { enum { M = 0x20, N = 0x00, K = 0x40 }; }; template<> struct Warp_masks<2, 1, 1> { enum { M = 0x20, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<1, 8, 1> { enum { M = 0x00, N = 0xe0, K = 0x00 }; }; template<> struct Warp_masks<1, 4, 2> { enum { M = 0x00, N = 0x60, K = 0x80 }; }; template<> struct Warp_masks<1, 4, 1> { enum { M = 0x00, N = 0x60, K = 0x00 }; }; template<> struct Warp_masks<1, 2, 2> { enum { M = 0x00, N = 0x20, K = 0x40 }; }; template<> struct Warp_masks<1, 2, 1> { enum { M = 0x00, N = 0x20, K = 0x00 }; }; template<> struct Warp_masks<1, 1, 4> { enum { M = 0x00, N = 0x00, K = 0x60 }; }; template<> struct Warp_masks<1, 1, 2> { enum { M = 0x00, N = 0x00, K = 0x20 }; }; template<> struct Warp_masks<1, 1, 1> { enum { M = 0x00, N = 0x00, K = 0x00 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename T > inline __device__ __host__ T div_up(T m, T n) { return (m + n-1) / n; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline int clz(int x) { for( int i = 31; i >= 0; --i ) { if( (1 << i) & x ) { return 31 - i; } } return 32; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline int find_log_2(int x, bool round_up = false) { int a = 31 - clz(x); if( round_up ) { a += (x & (x-1)) ? 1 : 0; } return a; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hadd2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("add.f16x2 %0, %1, %2;\n" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hmin2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("min.f16x2 %0, %1, %2;" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hmul2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("mul.f16x2 %0, %1, %2;\n" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hmul4(uint2 a, uint2 b) { uint2 c; c.x = hmul2(a.x, b.x); c.y = hmul2(a.y, b.y); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hmul8(uint4 a, uint4 b) { uint4 c; c.x = hmul2(a.x, b.x); c.y = hmul2(a.y, b.y); c.z = hmul2(a.z, b.z); c.w = hmul2(a.w, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hmul8(uint32_t a, uint4 b) { uint4 c; c.x = hmul2(a, b.x); c.y = hmul2(a, b.y); c.z = hmul2(a, b.z); c.w = hmul2(a, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hrelu2(uint32_t x, uint32_t lb = 0) { uint32_t res; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile( "max.f16x2 %0, %1, %2;\n" : "=r"(res) : "r"(x), "r"(lb)); #else const uint32_t zero = 0u; asm volatile( \ "{\n" \ "\t .reg .f16x2 sela;\n" \ "\t set.gtu.u32.f16x2 sela, %1, %2;\n" \ "\t and.b32 %0, sela, %1;\n" "}\n" : "=r"(res) : "r"(x), "r"(zero)); #endif return res; } static inline __device__ uint32_t habs2(uint32_t x) { uint32_t res; asm volatile( "abs.f16x2 %0, %1;\n" : "=r"(res) : "r"(x)); return res; } //////////////////////////////////////////////////////////////////////////////////////////////////// // template< typename T > static inline __device__ T clamp(T x, T lb, T ub) { return x < lb ? lb : (x > ub ? ub : x); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t clamp_to_zero(uint16_t x) { uint16_t mask; asm volatile("set.gtu %0, %1, 0;" : "=h"(mask) : "h"(x)); return mask & x; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t float_to_half(float f) { uint16_t h; asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float2_to_half2(float a, float b) { uint32_t c; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n" : "=r"(c) : "f"(b), "f"(a)); #else uint16_t lo = float_to_half(a); uint16_t hi = float_to_half(b); asm volatile("mov.b32 %0, {%1, %2};\n" : "=r"(c) : "h"(lo), "h"(hi)); #endif return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float_to_half2(float a) { return float2_to_half2(a,a); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float2_to_half2(const float2 &f) { return float2_to_half2(f.x, f.y); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 float4_to_half4(float x, float y, float z, float w) { uint2 d; d.x = float2_to_half2(x, y); d.y = float2_to_half2(z, w); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hfma2(uint32_t a, uint32_t b, uint32_t c) { uint32_t d; asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n" : "=r"(d) : "r"(a), "r"(b), "r"(c)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hfma2_relu(uint32_t a, uint32_t b, uint32_t c) { uint32_t d; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile("fma.rn.f16x2.relu %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); #else d = hrelu2(hfma2(a, b, c)); #endif return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t h0_h0(uint32_t x) { uint32_t y; asm volatile("{.reg .f16 lo, hi; mov.b32 {lo, hi}, %1; mov.b32 %0, {lo, lo};}\n" : "=r"(y) : "r"(x)); return y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float h0_to_float(uint32_t h2) { float f; asm volatile("{\n" \ ".reg .f16 lo, hi;\n" \ "mov.b32 {lo, hi}, %1;\n" \ "cvt.f32.f16 %0, lo;\n" \ "}\n" : "=f"(f) : "r"(h2)); return f; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t h1_h1(uint32_t x) { uint32_t y; asm volatile("{.reg .f16 lo, hi; mov.b32 {lo, hi}, %1; mov.b32 %0, {hi, hi};}\n" : "=r"(y) : "r"(x)); return y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hadd(uint16_t a, uint16_t b) { uint16_t d; asm volatile("add.f16 %0, %1, %2;" : "=h"(d) : "h"(a), "h"(b)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hadd(uint32_t a, uint32_t b) { return hadd2(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hadd4(uint2 a, uint2 b) { uint2 c; c.x = hadd2(a.x, b.x); c.y = hadd2(a.y, b.y); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hadd(uint2 a, uint2 b) { return hadd4(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hadd8(uint4 a, uint4 b) { uint4 c; c.x = hadd2(a.x, b.x); c.y = hadd2(a.y, b.y); c.z = hadd2(a.z, b.z); c.w = hadd2(a.w, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 fadd4(uint4 a, uint4 b) { float4 c; c.x = reinterpret_cast(a.x) + reinterpret_cast(b.x); c.y = reinterpret_cast(a.y) + reinterpret_cast(b.y); c.z = reinterpret_cast(a.z) + reinterpret_cast(b.z); c.w = reinterpret_cast(a.w) + reinterpret_cast(b.w); return reinterpret_cast(c); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hadd(uint4 a, uint4 b) { return hadd8(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float half_to_float(uint16_t h) { float f; asm volatile("cvt.f32.f16 %0, %1;\n" : "=f"(f) : "h"(h)); return f; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float2 half2_to_float2(uint32_t x) { uint16_t lo, hi; asm volatile("mov.b32 {%0, %1}, %2;\n" : "=h"(lo), "=h"(hi) : "r"(x)); return make_float2(half_to_float(lo), half_to_float(hi)); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ void half2_to_float2(float &x, float &y, uint32_t h) { float2 tmp = half2_to_float2(h); x = tmp.x; y = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hfma(uint16_t a, uint16_t b, uint16_t c) { uint16_t d; asm volatile("fma.rn.f16 %0, %1, %2, %3;" : "=h"(d) : "h"(a), "h"(b), "h"(c)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hmul(uint16_t a, uint16_t b) { uint16_t d; asm volatile("mul.f16 %0, %1, %2;" : "=h"(d) : "h"(a), "h"(b)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float sigmoid(float x) { return 1.f / (1.f + expf(-x)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint16_t &dst) { dst = uint16_t(0); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint32_t &dst) { dst = 0u; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint2 &dst) { dst = make_uint2(0u, 0u); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint4 &dst) { dst = make_uint4(0u, 0u, 0u, 0u); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // P R E D I C A T E P A C K I N G // //////////////////////////////////////////////////////////////////////////////////////////////////// enum { BYTES_PER_REG = 4, PREDS_PER_BYTE = 4, PREDS_PER_REG = BYTES_PER_REG * PREDS_PER_BYTE }; //////////////////////////////////////////////////////////////////////////////////////////////////// // // G E N E R I C P R E D I C A T E D L D G S T S // //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M, typename Functor > inline __device__ void load_(Functor &fct, const uint32_t (&preds)[M]) { // The number of complete bytes (where we use all the predicates in a byte). enum { COMPLETE = N / PREDS_PER_BYTE }; // Make sure we did allocate enough predicates. static_assert(Div_up::VALUE <= M, ""); // The remainder. enum { REMAINDER = N - COMPLETE * PREDS_PER_BYTE }; // Make sure we got the math right and the remainder is between 0 and 3. static_assert(REMAINDER >= 0 && REMAINDER <= 3, ""); // The mask to extract the predicates. enum { COMPLETE_MASK = (1 << PREDS_PER_BYTE) - 1 }; // Clear the fetch registers. #pragma unroll for( int ii = 0; ii < N; ++ii ) { fct.clear(ii); } // Run complete steps. bool p[PREDS_PER_BYTE]; #pragma unroll for( int ii = 0; ii < COMPLETE; ++ii ) { // The predicate. uint32_t reg = preds[ii / BYTES_PER_REG]; // Extract the predicates. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { uint32_t mask = 1u << (ii % BYTES_PER_REG * 8 + jj); p[jj] = (reg & mask) != 0u; } // Issue the loads. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { fct.load(ii * PREDS_PER_BYTE + jj, p[jj]); } } // Skip the rest of the code if we do not have a remainder. if( REMAINDER > 0 ) { // The mask to extract the predicates. enum { REMAINDER_MASK = (1 << REMAINDER) - 1 }; // The predicate register. uint32_t reg = preds[COMPLETE / BYTES_PER_REG]; // Extract the predicates. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { uint32_t mask = 1u << (COMPLETE % BYTES_PER_REG * 8 + jj); p[jj] = (reg & mask) != 0u; } // Issue the loads. #pragma unroll for( int ii = 0; ii < REMAINDER; ++ii ) { fct.load(COMPLETE * PREDS_PER_BYTE + ii, p[ii]); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, typename Functor > inline __device__ void load_(Functor &fct, uint32_t preds) { uint32_t tmp[1] = { preds }; load_(fct, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D G // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint8_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint16_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint32_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint2 &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint4 &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N > struct Ldg_functor { // Ctor. inline __device__ Ldg_functor(Data_type (&fetch)[N], const void* (&ptrs)[N]) : fetch_(fetch), ptrs_(ptrs) { } // Clear the element. inline __device__ void clear(int ii) { fmha::clear(fetch_[ii]); } // Trigger the loads. inline __device__ void load(int ii, bool p) { if( p ) { ldg(fetch_[ii], ptrs_[ii]); } } // The fetch registers. Data_type (&fetch_)[N]; // The pointers. const void* (&ptrs_)[N]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N, int M > inline __device__ void ldg_(Data_type (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { Ldg_functor fct(fetch, ptrs); load_(fct, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint8_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint16_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint32_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint2 (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint4 (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D S // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint16_t &dst, uint32_t ptr) { asm volatile("ld.shared.b16 %0, [%1];\n" : "=h"(dst) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint32_t &dst, uint32_t ptr) { asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint2 &dst, uint32_t ptr) { asm volatile("ld.shared.v2.b32 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint4 &dst, uint32_t ptr) { asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x) , "=r"(dst.y) , "=r"(dst.z) , "=r"(dst.w) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D S M // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint32_t &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x1.shared.b16 {%0}, [%1];\n" : "=r"(dst) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint32_t &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x1.trans.shared.b16 {%0}, [%1];\n" : "=r"(dst) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint2 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x2.shared.b16 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint2 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint4 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x), "=r"(dst.y), "=r"(dst.z), "=r"(dst.w) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint4 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x), "=r"(dst.y), "=r"(dst.z), "=r"(dst.w) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// // // S T G // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint8_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint16_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint32_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint2 val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint4 val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // S T S // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint16_t val) { asm volatile("st.shared.b16 [%0], %1;\n" : : "r"(ptr), "h"(val)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint32_t val) { asm volatile("st.shared.b32 [%0], %1;\n" : : "r"(ptr), "r"(val)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint2 val) { asm volatile("st.shared.v2.b32 [%0], {%1, %2};\n" : : "r"(ptr) , "r"(val.x) , "r"(val.y)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint4 val) { asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" : : "r"(ptr) , "r"(val.x) , "r"(val.y) , "r"(val.z) , "r"(val.w)); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N > inline __device__ void sts_(uint32_t (&ptrs)[N], const Data_type (&data)[N]) { #pragma unroll for( int ii = 0; ii < N; ++ii ) { sts(ptrs[ii], data[ii]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint16_t (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint32_t (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint2 (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint4 (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include constexpr int TOTAL_DIM = 0; constexpr int THREE_DIM = 1; constexpr int H_DIM = 2; constexpr int D_DIM = 3; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Qkv_params { // The QKV matrices. void *qkv_ptr; // The stride between rows of the Q, K and V matrices. size_t qkv_stride_in_bytes; // The number of heads. int h; }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Fused_multihead_attention_fprop_params : public Qkv_params { // The dQKV matrices. void *dqkv_ptr; // Temporary for dKV. void *dkv_ptr; // The O matrix (output). void *o_ptr; // The stride between rows of O. int64_t o_stride_in_bytes; // The pointer to the S matrix, overwritten by the dP matrix (bwd). void *s_ptr; // The stride between rows of the S matrix. int64_t s_stride_in_bytes; // The dimensions. int b, s, d; // The scaling factors for the kernel. uint32_t scale_bmm1, scale_softmax, scale_bmm2; // array of length b+1 holding starting offset of each sequence. int *cu_seqlens; // The dropout probability (probability of keeping an activation). float p_dropout; // Scale factor of 1 / (1 - p_dropout). float rp_dropout; // Scale factor of 1 / (1 - p_dropout), in half2. uint32_t scale_dropout; // Random state. at::PhiloxCudaState philox_args; }; //////////////////////////////////////////////////////////////////////////////////////////////////// void run_fmha_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_dgrad_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const bool is_training, const int num_chunks, cudaStream_t stream); void run_fmha_dgrad_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const int num_chunks, cudaStream_t stream); void fmha_run_noloop_reduce(void *out, const void *in, const int *cu_seqlens, const int hidden_size, const int batch_size, const int total, const int num_chunks, cudaStream_t stream); ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_128_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 128, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_128_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 128 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_128_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_128_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_256_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 256, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_256_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 256 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_256_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_256_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_384_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 384, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_384_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 384 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_384_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_384_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_512_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" #include "fmha_dgrad_kernel_1xN_reload_nl.h" using Kernel_traits = FMHA_kernel_traits< 512, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_512_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } template __global__ void fmha_dgrad_fp16_512_64_sm80_nl_kernel(Fused_multihead_attention_fprop_params params){ fmha::compute_dv_1xN_nl(params); fmha::compute_dq_dk_1xN_nl(params); } void run_fmha_dgrad_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 512 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_512_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_512_64_sm80_kernel<<>>(params); } void run_fmha_dgrad_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const int num_chunks, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 512 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); auto kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<2>; if( num_chunks == 2 ) { kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<2>; }else if( num_chunks == 3 ) { kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<3>; } else { assert(false && "Unsupperted number of chunks"); } if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b, num_chunks); kernel<<>>(params); FMHA_CHECK_CUDA(cudaPeekAtLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_kernel_1xN_reload.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void compute_dv_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dv = fmha::Cta_tile_extd; static_assert(Cta_tile_dv::M == 512 || Cta_tile_dv::M == 384 || Cta_tile_dv::M == 256 || Cta_tile_dv::M == 128); static_assert(Cta_tile_dv::N == 64); static_assert(Cta_tile_dv::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dv = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. // using Smem_tile_q = typename Kernel_traits::Smem_tile_q; using Smem_tile_q = fmha::Smem_tile_a; // The shared memory tile to reload Q as fragment b. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dV. using Gmem_tile_dv = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle dV. using Smem_tile_dv = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dv::NUM_LDS == Gmem_tile_dv::LDGS); static_assert(Smem_tile_dv::THREADS_PER_ROW == Gmem_tile_dv::THREADS_PER_ROW); using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; using Gmem_tile_do = typename Kernel_traits::Gmem_tile_do; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_do gmem_q(params, binfo, tidx); // treating dout as Q // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 2, binfo, tidx); // treating V as K // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dv::MMAS_N]; static_assert(Smem_tile_qt::Fragment::NUM_REGS == 4); static_assert(Mma_tile_dv::MMAS_K == 1); smem_qt.load(frag_qt[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[2][Mma_tile_p::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax( params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_st::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dv[Mma_tile_dv::MMAS_M][Mma_tile_dv::MMAS_N]; fmha::Clear_accumulator::apply(acc_dv); enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Load over the entire sequence length. for( int l = 0; l < STEPS; l++ ) { const int loop = l * Cta_tile_p::M; if( loop >= binfo.actual_seqlen ) break; // Load S uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Store s * dmask to smem for transpose smem_s.store(s_regs); // Declare the accumulators for the 1st gemm. // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Trigger the load for the next Q values. We're using double buffering, so reading qt is safe if( l < STEPS - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); float s_mat[2 * M][4 * N]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 0], s_mat[2 * mi + 0][4 * ni + 1], dst.x); fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 2], s_mat[2 * mi + 0][4 * ni + 3], dst.y); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 0], s_mat[2 * mi + 1][4 * ni + 1], dst.z); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 2], s_mat[2 * mi + 1][4 * ni + 3], dst.w); } } #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { float & s_dmask = s_mat[2 * mi + ii][4 * ni + jj]; const bool drop = reinterpret_cast(s_dmask) & 0x80000000; const float d_s = drop ? 0.f : softmax.elt_[2 * mi + ii][4 * ni + jj] * params.rp_dropout; s_dmask = fabsf(s_dmask); softmax.elt_[2 * mi + ii][4 * ni + jj] = d_s * fabsf(s_dmask); } } } } float p_sum[2 * M]; softmax.template reduce(p_sum); const float scalef = reinterpret_cast(params.scale_softmax); #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { softmax.elt_[2 * mi + ii][4 * ni + jj] -= p_sum[2 * mi + ii] * (s_mat[2 * mi + ii][4 * ni + jj]) ; softmax.elt_[2 * mi + ii][4 * ni + jj] *= scalef; } } } } typename Smem_tile_st::Fragment frag_s[Mma_tile_dv::MMAS_K][Mma_tile_dv::MMAS_M]; smem_s.load(frag_s); for( int ki = 0; ki < Mma_tile_dv::MMAS_K; ki++ ) { for( int mi = 0; mi < Mma_tile_dv::MMAS_M; mi++ ) { for( int ii = 0; ii < Smem_tile_st::Fragment::NUM_REGS; ii++ ) { frag_s[ki][mi].reg(ii) = fmha::hmul2(frag_s[ki][mi].reg(ii), params.scale_dropout); frag_s[ki][mi].reg(ii) = fmha::hrelu2(frag_s[ki][mi].reg(ii)); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); #pragma unroll for( int ki = 1; ki < Mma_tile_dv::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dv::MMAS_K; fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure we are reading from the correct buffer. smem_q.move_to_next_read_buffer(); smem_qt.move_to_next_read_buffer(); // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); smem_k.load(frag_k[0], 0); smem_qt.load(frag_qt[0], 0); } // Outer loop over the sequence length. // Epilogue swizzle for dV Smem_tile_dv smem_dv(&smem_[Kernel_traits::Smem_tile_q::BYTES_PER_TILE], tidx); smem_dv.store(acc_dv); __syncthreads(); uint4 dv_out[Smem_tile_dv::NUM_LDS]; smem_dv.load(dv_out); Qkv_params dv_params; dv_params.qkv_ptr = params.dqkv_ptr; dv_params.qkv_stride_in_bytes = params.qkv_stride_in_bytes; dv_params.h = params.h; Gmem_tile_dv gmem_dv(dv_params, 2, binfo, tidx); gmem_dv.store(dv_out); } template inline __device__ void compute_dq_dk_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dk = fmha::Cta_tile_extd; static_assert(Cta_tile_dk::M == 512 || Cta_tile_dk::M == 384 || Cta_tile_dk::M == 256 || Cta_tile_dk::M == 128); static_assert(Cta_tile_dk::N == 64); static_assert(Cta_tile_dk::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; using Mma_tile_o = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dk = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_v; // K is used like V in fprop // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. // using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; using Gmem_tile_o = fmha::Gmem_tile_dq; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dK. using Gmem_tile_dk = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle dK. using Smem_tile_dk = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dk::NUM_LDS == Gmem_tile_dk::LDGS); static_assert(Smem_tile_dk::THREADS_PER_ROW == Gmem_tile_dk::THREADS_PER_ROW); // The shared memory tile to reload Q transposed. using Smem_tile_qt = fmha::Smem_tile_b; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; static_assert(M == Mma_tile_o::MMAS_M); static_assert(N == Mma_tile_o::MMAS_K); // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Load dP uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); gmem_s.move(); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dk::MMAS_N]; smem_qt.load(frag_qt[0], 0); typename Smem_tile_k::Fragment frag_k[2][Mma_tile_o::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; enum { THREADS_PER_ROW = 32 }; enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dk[Mma_tile_dk::MMAS_M][Mma_tile_dk::MMAS_N]; fmha::Clear_accumulator::apply(acc_dk); // Load over the entire sequence length. for( int l=0;l= binfo.actual_seqlen ) break; // Pack dP as Fragment_a fmha::Fragment_a frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; frag_p[ni][mi].reg(0) = dst.x; // row 0, cols 0,1 frag_p[ni][mi].reg(1) = dst.z; // row 8, cols 0,1 frag_p[ni][mi].reg(2) = dst.y; // row 0, cols 8,9 frag_p[ni][mi].reg(3) = dst.w; // row 8, cols 8,9 } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. dQ = dP x dK #pragma unroll for( int ki = 1; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_o::MMAS_K; fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Store dP to smem for transpose smem_s.store(s_regs); if(l < STEPS - 1) { // Load next part of S gmem_s.load(s_regs, mask); gmem_s.move(); smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); typename Smem_tile_st::Fragment frag_s[Mma_tile_dk::MMAS_K][Mma_tile_dk::MMAS_M]; smem_s.load(frag_s); #pragma unroll for( int ki = 1; ki < Mma_tile_dk::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dk::MMAS_K; fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if( l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_qt.load(frag_qt[0], 0); smem_k.load(frag_k[0], 0); } // Outer loop over the sequence length. // Epilogue swizzle for dK Smem_tile_dk smem_dk(&smem_[0], tidx); smem_dk.store(acc_dk); __syncthreads(); uint4 dk_out[Smem_tile_dk::NUM_LDS]; smem_dk.load(dk_out); Qkv_params dk_params; dk_params.qkv_ptr = params.dqkv_ptr; dk_params.qkv_stride_in_bytes = params.qkv_stride_in_bytes; dk_params.h = params.h; Gmem_tile_dk gmem_dk(dk_params, 1, binfo, tidx); gmem_dk.store(dk_out); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_dgrad_kernel_1xN_reload_nl.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void compute_dv_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dv = fmha::Cta_tile_extd; static_assert(Cta_tile_dv::M == 512 || Cta_tile_dv::M == 384 || Cta_tile_dv::M == 256 || Cta_tile_dv::M == 128); static_assert(Cta_tile_dv::N == 64); static_assert(Cta_tile_dv::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dv = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = fmha::Smem_tile_a; // The shared memory tile to reload Q as fragment b. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store dV. using Gmem_tile_dv = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle dV. using Smem_tile_dv = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dv::NUM_LDS == Gmem_tile_dv::LDGS); static_assert(Smem_tile_dv::THREADS_PER_ROW == Gmem_tile_dv::THREADS_PER_ROW); using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; using Gmem_tile_do = typename Kernel_traits::Gmem_tile_do; // Shared memory. extern __shared__ char smem_[]; // The block index for the chunk. const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_do gmem_q(params, binfo, tidx); // treating dout as Q // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 2, binfo, tidx); // treating V as K // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); using Noloop = Noloop_traits; Noloop nl_traits(bidc); nl_traits.move_all(gmem_q, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dv::MMAS_N]; static_assert(Smem_tile_qt::Fragment::NUM_REGS == 4); static_assert(Mma_tile_dv::MMAS_K == 1); smem_qt.load(frag_qt[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[2][Mma_tile_p::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax( params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_st::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dv[Mma_tile_dv::MMAS_M][Mma_tile_dv::MMAS_N]; fmha::Clear_accumulator::apply(acc_dv); // Load over the entire sequence length. for(int l = 0; l < nl_traits.num_steps_;l++) { const int loop = nl_traits.offset_loop_count(l); if( loop >= binfo.actual_seqlen ) break; uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } smem_s.store(s_regs); // Declare the accumulators for the 1st gemm. // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Trigger the load for the next Q values. We're using double buffering, so reading qt is safe if(l < nl_traits.num_steps_ - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); float s_mat[2 * M][4 * N]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 0], s_mat[2 * mi + 0][4 * ni + 1], dst.x); fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 2], s_mat[2 * mi + 0][4 * ni + 3], dst.y); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 0], s_mat[2 * mi + 1][4 * ni + 1], dst.z); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 2], s_mat[2 * mi + 1][4 * ni + 3], dst.w); } } #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { float & s_dmask = s_mat[2 * mi + ii][4 * ni + jj]; const bool drop = reinterpret_cast(s_dmask) & 0x80000000; const float d_s= drop ? 0.f : softmax.elt_[2 * mi + ii][4 * ni + jj] * params.rp_dropout; s_dmask = fabsf(s_dmask); softmax.elt_[2 * mi + ii][4 * ni + jj] = d_s * (s_dmask); } } } } float p_sum[2 * M]; softmax.template reduce(p_sum); const float scalef = reinterpret_cast(params.scale_softmax); #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { softmax.elt_[2 * mi + ii][4 * ni + jj] -= p_sum[2 * mi + ii] * (s_mat[2 * mi + ii][4 * ni + jj]) ; softmax.elt_[2 * mi + ii][4 * ni + jj] *= scalef; } } } } typename Smem_tile_st::Fragment frag_s[Mma_tile_dv::MMAS_K][Mma_tile_dv::MMAS_M]; smem_s.load(frag_s); for( int ki = 0; ki < Mma_tile_dv::MMAS_K; ki++ ) { for( int mi = 0; mi < Mma_tile_dv::MMAS_M; mi++ ) { for( int ii = 0; ii < Smem_tile_st::Fragment::NUM_REGS; ii++ ) { frag_s[ki][mi].reg(ii) = fmha::hmul2(frag_s[ki][mi].reg(ii), params.scale_dropout); frag_s[ki][mi].reg(ii) = fmha::hrelu2(frag_s[ki][mi].reg(ii)); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); static_assert(Mma_tile_dv::MMAS_K == 1); // DEBUG #pragma unroll for( int ki = 1; ki < Mma_tile_dv::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dv::MMAS_K; fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < nl_traits.num_steps_ - 1) { gmem_q.commit(smem_q); } // Make sure we are reading from the correct buffer. smem_q.move_to_next_read_buffer(); smem_qt.move_to_next_read_buffer(); // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); smem_k.load(frag_k[0], 0); smem_qt.load(frag_qt[0], 0); } // Outer loop over the sequence length. // Epilogue for dV = (S * D)' * dout'. We're fully exposed to this! // Epilogue swizzle for dV Smem_tile_dv smem_dv(&smem_[Kernel_traits::Smem_tile_q::BYTES_PER_TILE], tidx); smem_dv.store(acc_dv); __syncthreads(); uint4 dv_out[Smem_tile_dv::NUM_LDS]; smem_dv.load(dv_out); Qkv_params dv_params; dv_params.qkv_ptr = params.dkv_ptr; dv_params.qkv_stride_in_bytes = params.h * 2 * CHUNKS * params.d * sizeof(half); dv_params.h = params.h; Gmem_tile_dv gmem_dv(dv_params, nl_traits.get_idx_dv(), binfo, tidx); gmem_dv.store(dv_out); } template inline __device__ void compute_dq_dk_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dk = fmha::Cta_tile_extd; static_assert(Cta_tile_dk::M == 512 || Cta_tile_dk::M == 384 || Cta_tile_dk::M == 256 || Cta_tile_dk::M == 128); static_assert(Cta_tile_dk::N == 64); static_assert(Cta_tile_dk::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; using Mma_tile_o = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dk = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_v; // K is used like V in fprop // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = Gmem_tile_dq; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dK. using Gmem_tile_dk = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle dK. using Smem_tile_dk = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dk::NUM_LDS == Gmem_tile_dk::LDGS); static_assert(Smem_tile_dk::THREADS_PER_ROW == Gmem_tile_dk::THREADS_PER_ROW); // The shared memory tile to reload Q transposed. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load dP, stored in S using Gmem_tile_s = Gmem_tile_mma_s; // The shared memory tile to transpose dP. using Smem_tile_st = Smem_tile_mma_transposed; using Noloop = Noloop_traits; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; static_assert(M == Mma_tile_o::MMAS_M); static_assert(N == Mma_tile_o::MMAS_K); // Shared memory. extern __shared__ char smem_[]; const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q (as B). Smem_tile_qt smem_qt(&smem_[0], tidx); // Allocate the global memory tile loader for dP. Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Allocate the shared memory tile loader for dP. Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); Noloop nl_traits(bidc); nl_traits.move_all(gmem_q, gmem_o, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_qt); // Trigger the loads for K. gmem_k.load(smem_k); uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_qt); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dk::MMAS_N]; smem_qt.load(frag_qt[0], 0); typename Smem_tile_k::Fragment frag_k[2][Mma_tile_o::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; enum { THREADS_PER_ROW = 32 }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dk[Mma_tile_dk::MMAS_M][Mma_tile_dk::MMAS_N]; fmha::Clear_accumulator::apply(acc_dk); // Load over the entire sequence length. for(int l=0;l < nl_traits.num_steps_; l++) { // Pack dP as Fragment_a fmha::Fragment_a frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; frag_p[ni][mi].reg(0) = dst.x; frag_p[ni][mi].reg(1) = dst.z; frag_p[ni][mi].reg(2) = dst.y; frag_p[ni][mi].reg(3) = dst.w; } } smem_s.store(s_regs); if(l < nl_traits.num_steps_- 1) { // Load next part of S gmem_s.move(); gmem_s.load(s_regs, mask); // Trigger the load for the next Q values. smem_qt.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_qt); } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. dQ = dP x dK #pragma unroll for( int ki = 1; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_o::MMAS_K; fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } static_assert(Gmem_tile_o::LOOPS == 1); //DEBUG // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); typename Smem_tile_st::Fragment frag_s[Mma_tile_dk::MMAS_K][Mma_tile_dk::MMAS_M]; smem_s.load(frag_s); static_assert(Mma_tile_dk::MMAS_K == 1); // DEBUG #pragma unroll for( int ki = 1; ki < Mma_tile_dk::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dk::MMAS_K; fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < nl_traits.num_steps_- 1) { gmem_q.commit(smem_qt); __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_qt.load(frag_qt[0], 0); smem_k.load(frag_k[0], 0); } } // Outer loop over the sequence length. // Epilogue for dK = dP' * dq. We're fully exposed to this! // Epilogue swizzle for dK Smem_tile_dk smem_dk(&smem_[0], tidx); smem_dk.store(acc_dk); __syncthreads(); uint4 dk_out[Smem_tile_dk::NUM_LDS]; smem_dk.load(dk_out); Qkv_params dk_params; dk_params.qkv_ptr = params.dkv_ptr; dk_params.qkv_stride_in_bytes = params.h * 2 * CHUNKS * params.d * sizeof(half); dk_params.h = params.h; Gmem_tile_dk gmem_dk(dk_params, nl_traits.get_idx_dk(), binfo, tidx); gmem_dk.store(dk_out); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_128_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" using Kernel_traits = FMHA_kernel_traits< 128, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_128_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_128_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_128_64_sm80_train_kernel : &fmha_fprop_fp16_128_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_256_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" using Kernel_traits = FMHA_kernel_traits< 256, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_256_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_256_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_256_64_sm80_train_kernel : &fmha_fprop_fp16_256_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_384_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN_reload_v.h" using Kernel_traits = FMHA_kernel_traits< 384, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_384_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_384_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_384_64_sm80_train_kernel : &fmha_fprop_fp16_384_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_v + smem_size_o + smem_size_softmax; if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_512_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" #include "fmha_fprop_kernel_1xN_nl.h" using Kernel_traits = FMHA_kernel_traits< 512, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_512_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_512_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } template __global__ void fmha_fprop_fp16_512_64_sm80_train_nl_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN_nl(params); } template __global__ void fmha_fprop_fp16_512_64_sm80_predict_nl_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN_nl(params); } void run_fmha_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_kernel : &fmha_fprop_fp16_512_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } void run_fmha_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const bool is_training, const int num_chunks, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<2> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<2>; if( num_chunks == 2 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<2> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<2>; } else if( num_chunks == 3 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<3> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<3>; } else if( num_chunks == 4 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<4> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<4>; } else { assert(false && "Unsupported num_chunks"); } constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b, num_chunks); kernel<<>>(params); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); // Make sure the data is in shared memory. __syncthreads(); } // Load the fragments for V. We keep the data in registers during the entire kernel. typename Smem_tile_v::Fragment frag_v[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { smem_v.load(frag_v[ki], ki); } enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax< Cta_tile_p, Kernel_traits>; Softmax softmax(params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Load over the entire sequence length. for( int l = 0; l < STEPS; l++ ) { const int loop = l * Cta_tile_p::M; if( loop >= binfo.actual_seqlen ) break; // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Load the mask for that iteration. mask.load(l); // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V && l == 0 ) { // if we share K and V, it could be that V was not fully read yet but we write into smem for reduction __syncthreads(); } // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from // pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } // Trigger the load for the next Q values. if(l < STEPS - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } using Frag_p = fmha::Fragment_a< fmha::Row>; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { fmha::gemm(acc_o, frag_p[ki], frag_v[ki]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if(l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN_nl.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store S/D. using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Noloop = Noloop_traits; // Shared memory. extern __shared__ char smem_[]; const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; Noloop nl_traits(bidc); const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); nl_traits.move_all(gmem_q, gmem_o, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); // Make sure the data is in shared memory. __syncthreads(); } // Load the fragments for V. We keep the data in registers during the entire kernel. typename Smem_tile_v::Fragment frag_v[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { smem_v.load(frag_v[ki], ki); } enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax(params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); // The number of threads per row. enum { THREADS_PER_ROW = 32 }; // Load over the entire sequence length. for(int l = 0; l < nl_traits.num_steps_;l++) { // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Trigger the load for the next Q values. if( l < nl_traits.num_steps_- 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Load the mask for that iteration. mask.load(nl_traits.loop_offset_ + l); // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V && l == 0 ) { // if we share K and V, it could be that V was not fully read yet but we write into smem for reduction __syncthreads(); } // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } using Frag_p = fmha::Fragment_a; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { fmha::gemm(acc_o, frag_p[ki], frag_v[ki]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if( l < nl_traits.num_steps_- 1) { gmem_q.commit(smem_q); __syncthreads(); smem_q.load(frag_q[0], 0); } } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN_reload_v.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); static_assert(2 * Mma_tile_p::MMAS_M * 4 * Mma_tile_p::MMAS_N <= 64); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[0], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[0]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } static_assert(Kernel_traits::SHARE_SMEM_FOR_K_AND_V); static_assert(Smem_tile_k::BYTES_PER_TILE == Smem_tile_v::BYTES_PER_TILE); // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[Smem_tile_v::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_v::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[1][Mma_tile_p::MMAS_M]; // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); } enum { BITS_PER_ELT_S = sizeof(typename fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax< Cta_tile_p, Kernel_traits>; Softmax softmax(params, &smem_[Smem_tile_v::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); constexpr int SMEM_BYTES_SOFTMAX = Softmax::ELEMENTS * sizeof(float); static_assert(SMEM_BYTES_SOFTMAX == Cta_tile_p::M * Cta_tile_p::WARPS_N * sizeof(float)); enum { THREADS_PER_ROW = 32 }; const float pinv = 1.f / params.p_dropout; // Load over the entire sequence length. for( int loop = 0, outer = 0; loop < Cta_tile_p::N; loop += Cta_tile_p::M, outer++ ) { if( loop >= binfo.actual_seqlen ) break; // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[0], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[0], frag_k[ki]); } // Load the mask for that iteration. mask.load(outer); // Convert from the accumulator typ e to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); static_assert(2 * Mma_tile_p::MMAS_M * 4 * Mma_tile_p::MMAS_N <= 64); // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); __syncthreads(); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from // pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } // Trigger the load for the next Q values. if( loop + Cta_tile_p::M < Cta_tile_p::N ) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } typename Smem_tile_v::Fragment frag_v[1][Mma_tile_o::MMAS_N]; using Frag_p = fmha::Fragment_a< fmha::Row>; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of V values. smem_v.load(frag_v[0], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki], frag_v[0]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Always sync after last iter: shared smem_q and smem_o! __syncthreads(); // Output the values. gmem_o.store(out, ii); } // same smem as o // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if( loop + Cta_tile_p::M < Cta_tile_p::N ) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_kernel.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template struct BlockInfoPadded { template __device__ BlockInfoPadded(const Params ¶ms, const int bidb, const int bidh, const int tidx) : bidb(bidb), bidh(bidh), h(params.h) { // The block index. sum_s = params.cu_seqlens[bidb]; actual_seqlen = params.cu_seqlens[bidb + 1] - sum_s; bidx = sum_s * params.h + bidh; tidx_global = (bidb * params.h + bidh) * THREADS_PER_CTA + tidx; } __device__ bool stop_early() const { return actual_seqlen == 0; } int actual_seqlen; int bidx; int sum_s; int bidh; int bidb; int tidx_global; int h; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Noloop_traits{ // Interpretation of Cta_tile dims, i.e. Cta_tile_p: enum{ STEP = Cta_tile::M }; enum{ SEQLEN = Cta_tile::N }; // The size of the subsequence this CTA is processing enum { SUBSEQ = SEQLEN / CHUNKS }; static_assert(SUBSEQ * CHUNKS == SEQLEN); // The number of steps to process the subsequence enum { NUM_STEPS = SUBSEQ / STEP }; static_assert(NUM_STEPS * Cta_tile::M == SUBSEQ); inline __device__ Noloop_traits(const int bidc) : loop_offset_(NUM_STEPS * bidc) , bidc_(bidc) { } template inline __device__ void move_all(Tiles & ... tiles) const { using expand_type = int[]; for( int s = 0; s < loop_offset_; s++ ) { expand_type{ (tiles.move(), 0)... }; } } inline __device__ int get_idx_dk() const { //return bidc_; return bidc_ * 2 + 0; } inline __device__ int get_idx_dv() const { //return CHUNKS + bidc_; return bidc_ * 2 + 1; } inline __device__ int offset_loop_count(const int l) { // convert loop counter to position in the outer sequence return (loop_offset_ + l) * STEP; } const int loop_offset_; const uint32_t bidc_; const int num_steps_ = NUM_STEPS; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Noloop_traits<3, Cta_tile>{ // Interpretation of Cta_tile dims, i.e. Cta_tile_p: enum{ STEP = Cta_tile::M }; enum{ SEQLEN = Cta_tile::N }; static_assert(STEP == 16 && SEQLEN == 512); inline __device__ Noloop_traits(const int bidc) : bidc_(bidc) , num_steps_(bidc < 2 ? 11 : 10) , loop_offset_(bidc * 11) { } template inline __device__ void move_all(Tiles & ... tiles) const { using expand_type = int[]; for( int s = 0; s < loop_offset_; s++ ) { expand_type{ (tiles.move(), 0)... }; } } inline __device__ int get_idx_dk() const { //return bidc_; return bidc_ * 2 + 0; } inline __device__ int get_idx_dv() const { //return CHUNKS + bidc_; return bidc_ * 2 + 1; } inline __device__ int offset_loop_count(const int l) { // convert loop counter to position in the outer sequence return (loop_offset_ + l) * STEP; } const int loop_offset_; const uint32_t bidc_; const int num_steps_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_noloop_reduce.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" inline __device__ float4 ldg128(const void *ptr) { return *static_cast(ptr); } inline __device__ void stg128(void *ptr, const float4 &data) { *static_cast(ptr) = data; } template __global__ __launch_bounds__(THREADS) void fmha_noloop_reduce_kernel(void *__restrict__ out, const void *__restrict__ in, const int *__restrict__ cu_seqlens, const int batch_size) { enum { BYTES_PER_LDG = 16 }; enum { NUM_ELTS = BYTES_PER_LDG / sizeof(T) }; // One CTA hidden vector for K and V enum { BYTES_PER_ROW = HIDDEN_SIZE * sizeof(T) * 2 }; // The stride in bytes in dQKV enum { OUT_STRIDE_BYTES = 3 * HIDDEN_SIZE * sizeof(T) }; // The offset in bytes in dQKV to the dKV part for non-interleaved heads enum { OUT_OFFSET_KV_BYTES = HIDDEN_SIZE * sizeof(T) }; static_assert(BYTES_PER_ROW == HIDDEN_SIZE * 2 * sizeof(T)); // Size in bytes of the input tile enum { BYTES_PER_TILE = CHUNKS * BYTES_PER_ROW }; enum { BYTES_PER_CTA = THREADS * BYTES_PER_LDG }; enum { LDGS = BYTES_PER_ROW / BYTES_PER_CTA }; static_assert(BYTES_PER_CTA * LDGS == BYTES_PER_ROW); union Vec_t { float4 raw; T elt[NUM_ELTS]; }; // ZERO-OUT invalid positions in dQKV const int total = cu_seqlens[batch_size]; if(blockIdx.x >= total){ enum { BYTES_PER_QKV_ROW = 3 * HIDDEN_SIZE * sizeof(T) }; enum { STGS = BYTES_PER_QKV_ROW / BYTES_PER_LDG }; const float4 zeros = make_float4(0.f, 0.f, 0.f, 0.f); char *base_ptr = static_cast(out) + blockIdx.x * OUT_STRIDE_BYTES; for(int tidx = threadIdx.x; tidx < STGS; tidx += THREADS){ stg128(base_ptr + tidx * BYTES_PER_LDG, zeros); } return; } // SETUP const int offset_in = blockIdx.x * BYTES_PER_TILE + threadIdx.x * BYTES_PER_LDG; const char *ptr_in = static_cast(in) + offset_in; const int offset_out = blockIdx.x * OUT_STRIDE_BYTES + threadIdx.x * BYTES_PER_LDG; char *ptr_out = static_cast(out) + OUT_OFFSET_KV_BYTES + offset_out; // LOAD Vec_t local_in[CHUNKS][LDGS]; #pragma unroll for( int c = 0; c < CHUNKS; c++ ) { #pragma unroll for( int l = 0; l < LDGS; l++ ) { int offset = c * BYTES_PER_ROW + l * BYTES_PER_CTA; local_in[c][l].raw = ldg128(ptr_in + offset); } } // UNPACK float acc[LDGS][NUM_ELTS]; #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { acc[l][e] = float(local_in[0][l].elt[e]); } } // COMPUTE #pragma unroll for( int c = 1; c < CHUNKS; c++ ) { #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { acc[l][e] += float(local_in[c][l].elt[e]); } } } // PACK Vec_t local_out[LDGS]; #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { local_out[l].elt[e] = T(acc[l][e]); } } // STORE #pragma unroll for( int l = 0; l < LDGS; l++ ) { const int offset = l * BYTES_PER_CTA; stg128(ptr_out + offset, local_out[l].raw); } } void fmha_run_noloop_reduce(void *out, const void *in, const int *cu_seqlens, const int hidden_size, const int batch_size, const int total, const int num_chunks, cudaStream_t stream) { const int blocks = total; if(hidden_size == 1024){ constexpr int HIDDEN_SIZE = 1024; constexpr int THREADS = 256; if( num_chunks == 2 ) { fmha_noloop_reduce_kernel<<>>(out, in, cu_seqlens, batch_size); } else if( num_chunks == 3 ) { fmha_noloop_reduce_kernel<<>>(out, in, cu_seqlens, batch_size); } else { assert(false && "Unsupported num_chunks"); } }else{ assert(false && "Unsupported hidden_size"); } FMHA_CHECK_CUDA(cudaPeekAtLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/fmha/src/fmha_utils.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include //////////////////////////////////////////////////////////////////////////////////////////////////// #define FMHA_CHECK_CUDA( call ) \ do { \ cudaError_t status_ = call; \ if( status_ != cudaSuccess ) { \ fprintf( stderr, \ "CUDA error (%s:%d): %s\n", \ __FILE__, \ __LINE__, \ cudaGetErrorString( status_ ) ); \ exit( 1 ); \ } \ } while( 0 ) //////////////////////////////////////////////////////////////////////////////////////////////////// enum Data_type { DATA_TYPE_FP16, DATA_TYPE_FP32, DATA_TYPE_INT32, DATA_TYPE_INT8 }; //////////////////////////////////////////////////////////////////////////////////////////////////// static inline void set_alpha( uint32_t &alpha, float norm, Data_type dtype ) { if( dtype == DATA_TYPE_FP16 ) { half x = __float2half_rn( norm ); uint16_t h = reinterpret_cast( x ); ushort2 h2 = { h, h }; alpha = reinterpret_cast( h2 ); } else if( dtype == DATA_TYPE_FP32 ) { alpha = reinterpret_cast( norm ); } else if( dtype == DATA_TYPE_INT32 ) { int32_t inorm = static_cast( norm ); alpha = reinterpret_cast( inorm ); } else { assert( false ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline size_t get_size_in_bytes( size_t n, Data_type dtype ) { switch( dtype ) { case DATA_TYPE_FP32: return n * 4; case DATA_TYPE_FP16: return n * 2; case DATA_TYPE_INT32: return n * 4; case DATA_TYPE_INT8: return n; default: assert( false ); return 0; } } //////////////////////////////////////////////////////////////////////////////////////////////////// ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/batch_norm.cu ================================================ #include #include #include #include "THC/THC.h" #include "batch_norm.h" #include #include "compat.h" #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) static size_t round_up_to_multiple(size_t x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; } // TODO: Stop manually allocating CUDA memory; allocate an ATen byte // tensor instead. struct Workspace { Workspace(size_t size) : size(size), data(NULL) { data = THCudaMalloc(at::globalContext().lazyInitCUDA(), size); } Workspace(const Workspace&) = delete; Workspace(Workspace&&) = default; Workspace& operator=(Workspace&&) = default; ~Workspace() { if (data) { THCudaFree(at::globalContext().lazyInitCUDA(), data); } } size_t size; void* data; }; // Return {y} at::Tensor nhwc_bn_fwd_train( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwd(stream, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return y; } at::Tensor nhwc_bn_fwd_eval( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon, const bool fuse_relu) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(nullptr); workspace.push_back(nullptr); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwdInference(stream, fuse_relu); return y; } std::vector nhwc_bn_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { // shape const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // outputs at::Tensor x_grad, scale_grad, bias_grad; // Allocate outputs x_grad = at::empty_like(x); scale_grad = at::empty_like(scale); bias_grad = at::empty_like(bias); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), x_grad.DATA_PTR(), nullptr, dy.DATA_PTR()); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {scale_grad.DATA_PTR(), bias_grad.DATA_PTR()}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); bn->dgrad(stream, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return std::vector{x_grad, scale_grad, bias_grad}; } int nhwc_bn_fwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNorm::smem_driven_fwd_occupancy(device_id, 2); } int nhwc_bn_bwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNorm::smem_driven_bwd_occupancy(device_id, 2); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/batch_norm.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm.h * \brief CUDA NHWC Batch Normalization code * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ #include #include #include #include #include "nhwc_batch_norm_kernel.h" #include "cuda_utils.h" #define VERBOSE_DEFAULT false class NhwcBatchNorm { public: NhwcBatchNorm() { name_ = "nhwc_batchnorm"; createTensorDescriptor(&X_tensor_desc_); createTensorDescriptor(&Y_tensor_desc_); } ~NhwcBatchNorm() { destroyTensorDescriptor(X_tensor_desc_); destroyTensorDescriptor(Y_tensor_desc_); } void die() { std::cerr << "batchnorm not initialized" << std::endl; exit(-1); } void fwd(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void dgrad(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void fwdInference(cudaStream_t stream, bool use_relu); dim3 calc_fwd_grid(int *loop, const int grid_dim_x); dim3 calc_bwd_grid(int *loop, const int grid_dim_x); void setInputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w, int bn_group) { m_ = n * h * w; int m_bn_adjusted = m_ * bn_group; c_ = c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. svar_inv_count_ = 1.f / m_bn_adjusted; // factor to scale sum of squared errors to get running variance. Should be 1/(nhw-1). int divisor = m_bn_adjusted - 1; // nhw == 1 is unlikely, but by setting the rvar_inv_count_ == 1.f, we avoid running var infs. rvar_inv_count_ = divisor == 0 ? 1.f : 1.f / divisor; setTensorDescriptor(X_tensor_desc_, format, data_type, n, c, h, w); } void setOutputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w) { setTensorDescriptor(Y_tensor_desc_, format, data_type, n, c, h, w); } const std::vector numWorkspaceBytes() const; void setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes); void setInputOutputPointers(void* X, void* dX, void* Y, void *dY) { X_ = X; dX_ = dX; Y_ = Y; dY_ = dY; } // Sets the pointers for the scale and weight (in that order) data and derivative buffers. void setWeightPointers(const std::vector& weight_pointers, const std::vector& deriv_pointers) { assert(weight_pointers.size() == 2); assert(deriv_pointers.size() == 2); scale_ = static_cast(weight_pointers[0]); bias_ = static_cast(weight_pointers[1]); dscale_ = static_cast(deriv_pointers[0]); dbias_ = static_cast(deriv_pointers[1]); } // Sets the pointers for the population mean and variance buffers, in that order. void setParameterPointers(const std::vector& param_pointers) { assert(param_pointers.size() == 2); population_mean_ = static_cast(param_pointers[0]); population_variance_ = static_cast(param_pointers[1]); } void setConstants(const double exp_avg_factor, const double eps) { exp_avg_factor_ = exp_avg_factor; eps_ = eps; } void processCudnnStatus(const cudnnStatus_t& status, const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { if (status != CUDNN_STATUS_SUCCESS) LOG(FATAL) << string << " " << cudnnGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudnnGetErrorString(status); } void checkCudaStatus(const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { cudaError_t status = cudaGetLastError(); if (status != cudaSuccess) LOG(FATAL) << string << " " << cudaGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudaGetErrorString(status); } size_t size_retired_ctas(int grid_y) const { // Note that the value of max_grid_y to handle known GPUs is about 160. const int max_grid_y = 1024; if (grid_y > max_grid_y) LOG(INFO) << "GPU capabilities exceeds assumptions."; const int retired_cta_bytes = max_grid_y * 2 * sizeof(int); // Since the region will be initialized once and used for many kernels, // the idea is to return an ample size that will cover all uses. return retired_cta_bytes; } cudnnTensorDescriptor_t X_tensor_desc_ = nullptr; cudnnTensorDescriptor_t Y_tensor_desc_ = nullptr; void* X_ = nullptr; void* dX_ = nullptr; void* Y_ = nullptr; void* dY_ = nullptr; // Learned scale and bias weights. float* scale_ = nullptr; float* dscale_ = nullptr; float* bias_ = nullptr; float* dbias_ = nullptr; // Computed population mean and variance parameters. float* population_mean_ = nullptr; float* population_variance_ = nullptr; // Workspace buffers for minibatch mean and variance (computed in fwd, needed by bwd). float* minibatch_mean_ = nullptr; float* minibatch_variance_ = nullptr; int m_ = 0; // Number of values per channel that BN is normalizing. int c_ = 0; // Number of channels over which BN is normalizing. float svar_inv_count_ = 0.f; // factor to scale sum of squared errors to get saved variance float rvar_inv_count_ = 0.f; // factor to scale sum of squared errors to get running variance double exp_avg_factor_ = 0.; double eps_ = 0.; std::string name_; private: void setTensorDescriptor(cudnnTensorDescriptor_t descriptor, cudnnTensorFormat_t format, cudnnDataType_t data_type, int n, int c, int h, int w) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnSetTensor4dDescriptor(descriptor, format, data_type, n, c, h, w); processCudnnStatus(status, "set tensor descriptor"); } void createTensorDescriptor(cudnnTensorDescriptor_t *descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnCreateTensorDescriptor(descriptor); processCudnnStatus(status, "create tensor_descriptor"); } void destroyTensorDescriptor(cudnnTensorDescriptor_t descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnDestroyTensorDescriptor(descriptor); processCudnnStatus(status, "destroy tensor_descriptor"); } protected: float *partial_sums_ = nullptr; int *partial_counts_ = nullptr; int *retired_ctas_ = nullptr; void _setFwdParams(NhwcBatchNormFwdParams *params) const; void _setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const; void _setBwdParams(NhwcBatchNormBwdParams *params) const; // @todo: ability to configure these? // Kernel params static const int USE_ONLINE_APPROACH = 1; static const int THREADS_PER_CTA = 512; static const int THREADS_PER_PIXEL = 16; static const int C_ELEMENTS_PER_CTA = 64; static const int ELEMENTS_PER_LDG = C_ELEMENTS_PER_CTA / THREADS_PER_PIXEL; static const int MAX_SMEM_WITHOUT_OPT_IN = 48 * 1024; typedef uint16_t StorageType; //typedef float StorageType; // increasing this to 6 causes spills in fwd kernel! static const int PIXELS_PER_THREAD_IN_REGISTERS_FWD = 5; static const int PIXELS_PER_THREAD_IN_REGISTERS_BWD = 3; static const int PIXELS_PER_THREAD_IN_SMEM_FWD = 10; static const int PIXELS_PER_THREAD_IN_SMEM_BWD = 5; static const int PIXELS_PER_THREAD_FWD = PIXELS_PER_THREAD_IN_REGISTERS_FWD + \ PIXELS_PER_THREAD_IN_SMEM_FWD; static const int PIXELS_PER_THREAD_BWD = PIXELS_PER_THREAD_IN_REGISTERS_BWD + \ PIXELS_PER_THREAD_IN_SMEM_BWD; static const int PIXELS_PER_THREAD_FWD_INFERENCE = 4; // Derived params static const size_t SMEM_SIZE_FWD = PIXELS_PER_THREAD_IN_SMEM_FWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*sizeof(StorageType); static const size_t SMEM_SIZE_BWD = PIXELS_PER_THREAD_IN_SMEM_BWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*2*sizeof(StorageType); static const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; static const int PIXELS_PER_CTA_FWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD; static const int PIXELS_PER_CTA_BWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_BWD; static const int PIXELS_PER_CTA_FWD_INFERENCE = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD_INFERENCE; // max grid.y in case of group bn is limited by exchange buffer size static const int MAX_GBN_BLOCK_Y = 256; // Helper function to launch the forward kernel. // We calculate (based on smem usage) the achievable occupancy and make sure we run a kernel // version that was compiled with that occupancy in its launch bounds. This way, we avoid // needless register spills. void _fwdKernelLauncher(cudaStream_t stream, NhwcBatchNormFwdParams params, dim3 grid_dim, int outer_loops, bool use_relu, const int occupancy, const bool coop) { #define LAUNCH_FWD_KERNEL(OUTER_LOOPS, USE_RELU, USE_ADD_RELU, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_FWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto fwd_func = nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(fwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " fwd ser coop kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using FWD_FUNC = decltype(nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } else { \ cudaLaunchKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } \ checkCudaStatus(name_ + " fwd ser coop kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1 && use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, true, false, 2, coop); else LAUNCH_FWD_KERNEL(1, true, false, 1, coop); } else if (outer_loops == 1 && !use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, false, false, 2, coop); else LAUNCH_FWD_KERNEL(1, false, false, 1, coop); } else if (use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, true, false, 2, coop); else LAUNCH_FWD_KERNEL(0, true, false, 1, coop); } else { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, false, false, 2, coop); else LAUNCH_FWD_KERNEL(0, false, false, 1, coop); } #undef LAUNCH_FWD_KERNEL } // Helper function to launch the backward kernel. void _bwdKernelLauncher(cudaStream_t stream, NhwcBatchNormBwdParams params, dim3 grid_dim, int outer_loops, bool use_relu, const int occupancy, const bool coop) { #define LAUNCH_BWD_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto bwd_func = nhwc_batch_norm_bwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " bwd coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_FUNC = decltype(nhwc_batch_norm_bwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd coop serial kernel"); \ } while (0) #define LAUNCH_BWD_RELU_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto bwd_relu_func = nhwc_batch_norm_bwd_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_relu_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " bwd-relu coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_RELU_FUNC = decltype(nhwc_batch_norm_bwd_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd-relu coop serial kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1 && use_relu) { if (occupancy >= 2) LAUNCH_BWD_RELU_KERNEL(1, 2, coop); else LAUNCH_BWD_RELU_KERNEL(1, 1, coop); } else if (outer_loops == 1 && !use_relu) { if (occupancy >= 2) LAUNCH_BWD_KERNEL(1, 2, coop); else LAUNCH_BWD_KERNEL(1, 1, coop); } else if (use_relu) { if (occupancy >= 2) LAUNCH_BWD_RELU_KERNEL(0, 2, coop); else LAUNCH_BWD_RELU_KERNEL(0, 1, coop); } else { if (occupancy >= 2) LAUNCH_BWD_KERNEL(0, 2, coop); else LAUNCH_BWD_KERNEL(0, 1, coop); } #undef LAUNCH_BWD_KERNEL } public: // Calculate the expected fwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_fwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int fwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int fwd_smem_bytes = SMEM_SIZE_FWD + fwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / fwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } // Calculate the expected bwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_bwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int bwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int bwd_smem_bytes = SMEM_SIZE_BWD + bwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / bwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } }; const std::vector NhwcBatchNorm::numWorkspaceBytes() const { assert(c_ > 0); // choose the max memory required between fwd/bwd passes int grid_x_fwd = div_up(m_, PIXELS_PER_CTA_FWD); int grid_x_bwd = div_up(m_, PIXELS_PER_CTA_BWD); int grid_x = max(grid_x_fwd, grid_x_bwd); int grid_y = div_up(c_, C_ELEMENTS_PER_CTA); const size_t num_mean_bytes = c_ * sizeof(float); const size_t num_variance_bytes = num_mean_bytes; const size_t size_sums = grid_y*grid_x*THREADS_PER_PIXEL*\ ELEMENTS_PER_LDG*2*sizeof(float); const size_t size_counts = grid_y*grid_x*sizeof(int); return {num_mean_bytes, num_variance_bytes, size_retired_ctas(grid_y), size_sums, size_counts}; } void NhwcBatchNorm::setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes) { assert(workspace.size() == 5); assert(num_workspace_bytes.size() == 5); minibatch_mean_ = static_cast(workspace[0]); minibatch_variance_ = static_cast(workspace[1]); retired_ctas_ = static_cast(workspace[2]); partial_sums_ = static_cast(workspace[3]); partial_counts_ = static_cast(workspace[4]); } void NhwcBatchNorm::_setFwdParams(NhwcBatchNormFwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = nullptr; params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_running_mean = population_mean_; params->gmem_running_var = population_variance_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->gmem_relu_bitmask = nullptr; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->rvar_inv_count = rvar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_counts = partial_counts_; params->gmem_retired_ctas = retired_ctas_; params->var_eps = eps_; params->outer_loops = 0; params->exp_avg_factor = static_cast(exp_avg_factor_); params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNorm::_setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = nullptr; params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_mean = population_mean_; params->gmem_var = population_variance_; params->nhw = m_; params->c = c_; params->var_eps = eps_; } void NhwcBatchNorm::_setBwdParams(NhwcBatchNormBwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dy = static_cast(dY_); params->gmem_dst = static_cast(dX_); params->gmem_dst1 = nullptr; params->gmem_relu_bitmask = nullptr; params->gmem_dscale = dscale_; params->gmem_dbias = dbias_; params->gmem_scale = scale_; params->gmem_bias = bias_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_retired_ctas = retired_ctas_; params->outer_loops = 0; params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNorm::fwdInference(cudaStream_t stream, bool use_relu) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr // && minibatch_mean_ != nullptr // && minibatch_variance_ != nullptr && population_mean_ != nullptr && population_variance_ != nullptr && X_ != nullptr // && dX_ != nullptr && Y_ != nullptr // && dY_ != nullptr // && dscale_ != nullptr // && dbias_ != nullptr && partial_sums_ != nullptr && partial_counts_ != nullptr; if (!ptrs_are_set) die(); dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD_INFERENCE); grid_dim.y = div_up(c_, C_ELEMENTS_PER_CTA); // @todo: maybe just move this inside initialize routine? NhwcBatchNormFwdInferenceParams params; _setFwdInferenceParams(¶ms); if (use_relu) { nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference-relu kernel"); } else { nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference kernel"); } } dim3 NhwcBatchNorm::calc_fwd_grid(int *loop, const int grid_dim_x) { dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD); int c_blks = div_up(c_, C_ELEMENTS_PER_CTA); unsigned int max_grid_x = grid_dim_x; if (grid_dim.x <= max_grid_x) { *loop = 1; if (max_grid_x / grid_dim.x > 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y> 1); dim3 grid_dim = calc_fwd_grid(¶ms.outer_loops, grid_dim_x); _fwdKernelLauncher(stream, params, grid_dim, params.outer_loops, use_relu, occupancy, coop); } void NhwcBatchNorm::dgrad(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && (bias_ != nullptr || !use_relu) && minibatch_mean_ != nullptr && minibatch_variance_ != nullptr // && population_mean_ != nullptr // && population_variance_ != nullptr && X_ != nullptr && dX_ != nullptr // && Y_ != nullptr && dY_ != nullptr && dscale_ != nullptr && dbias_ != nullptr; if (!ptrs_are_set) die(); // reset of retired_cta_count no longer needed NhwcBatchNormBwdParams params; _setBwdParams(¶ms); params.my_data = my_data; params.pair_datas[0] = pair_data; params.pair_datas[1] = pair_data2; params.pair_datas[2] = pair_data3; params.magic = magic; params.sync_iters = (bn_group==8)?3:(bn_group >> 1); params.wgrad_coeff = 1.0 / bn_group; dim3 grid_dim = calc_bwd_grid(¶ms.outer_loops, grid_dim_x); _bwdKernelLauncher(stream, params, grid_dim, params.outer_loops, use_relu, occupancy, coop); } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/batch_norm_add_relu.cu ================================================ #include #include #include #include "THC/THC.h" #include "batch_norm_add_relu.h" #include #include "compat.h" //FIXME move the common stuff to common h file #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) static size_t round_up_to_multiple(size_t x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; } // TODO: Stop manually allocating CUDA memory; allocate an ATen byte // tensor instead. struct Workspace { Workspace(size_t size) : size(size), data(NULL) { data = THCudaMalloc(at::globalContext().lazyInitCUDA(), size); } Workspace(const Workspace&) = delete; Workspace(Workspace&&) = default; Workspace& operator=(Workspace&&) = default; ~Workspace() { if (data) { THCudaFree(at::globalContext().lazyInitCUDA(), data); } } size_t size; void* data; }; // Return {y} at::Tensor nhwc_bn_addrelu_fwd_train( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr, z.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); workspace.push_back(bitmask.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwd(stream, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return y; } at::Tensor nhwc_bn_addrelu_fwd_eval( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr, z.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(nullptr); workspace.push_back(nullptr); workspace.push_back(nullptr); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwdInference(stream); return y; } std::vector nhwc_bn_addrelu_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { // shape const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // outputs at::Tensor x_grad, z_grad, scale_grad, bias_grad; // Allocate outputs x_grad = at::empty_like(x); z_grad = at::empty_like(x); scale_grad = at::empty_like(scale); bias_grad = at::empty_like(bias); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), x_grad.DATA_PTR(), nullptr, dy.DATA_PTR(), nullptr, z_grad.DATA_PTR()); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {scale_grad.DATA_PTR(), bias_grad.DATA_PTR()}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); workspace.push_back(bitmask.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); bn->dgrad(stream, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return std::vector{x_grad, z_grad, scale_grad, bias_grad}; } int nhwc_bn_addrelu_fwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNormAddRelu::smem_driven_fwd_occupancy(device_id, 2); } int nhwc_bn_addrelu_bwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNormAddRelu::smem_driven_bwd_occupancy(device_id, 2); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/batch_norm_add_relu.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm_add_relu.h * \brief CUDA NHWC Batch Normalization code with fused addition * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Maxim Milakov, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ #include #include #include #include #include "nhwc_batch_norm_kernel.h" #include "cuda_utils.h" #define VERBOSE_DEFAULT false class NhwcBatchNormAddRelu { public: NhwcBatchNormAddRelu() { name_ = "nhwc_batchnormaddrelu"; createTensorDescriptor(&X_tensor_desc_); createTensorDescriptor(&Y_tensor_desc_); } ~NhwcBatchNormAddRelu() { destroyTensorDescriptor(X_tensor_desc_); destroyTensorDescriptor(Y_tensor_desc_); } void die() { std::cerr << "batchnormaddrelu not initialized" << std::endl; exit(-1); } void fwd(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void dgrad(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void fwdInference(cudaStream_t stream); dim3 calc_fwd_grid(int *loop, const int grid_dim_x); dim3 calc_bwd_grid(int *loop, const int grid_dim_x); void setInputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w, int bn_group) { m_ = n * h * w; int m_bn_adjusted = m_ * bn_group; c_ = c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. svar_inv_count_ = 1.f / m_bn_adjusted; // factor to scale sum of squared errors to get running variance. Should be 1/(nhw-1). int divisor = m_bn_adjusted - 1; // nhw == 1 is unlikely, but by setting the rvar_inv_count_ == 1.f, we avoid running var infs. rvar_inv_count_ = divisor == 0 ? 1.f : 1.f / divisor; setTensorDescriptor(X_tensor_desc_, format, data_type, n, c, h, w); } void setOutputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w) { setTensorDescriptor(Y_tensor_desc_, format, data_type, n, c, h, w); } const std::vector numWorkspaceBytes() const; void setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes); void setInputOutputPointers(void* X, void* dX, void* Y, void *dY, void* addend, void* dAddend) { X_ = X; dX_ = dX; Y_ = Y; dY_ = dY; addend_ = addend; dAddend_ = dAddend; } // Sets the pointers for the scale and weight (in that order) data and derivative buffers. void setWeightPointers(const std::vector& weight_pointers, const std::vector& deriv_pointers) { assert(weight_pointers.size() == 2); assert(deriv_pointers.size() == 2); scale_ = static_cast(weight_pointers[0]); bias_ = static_cast(weight_pointers[1]); dscale_ = static_cast(deriv_pointers[0]); dbias_ = static_cast(deriv_pointers[1]); } // Sets the pointers for the population mean and variance buffers, in that order. void setParameterPointers(const std::vector& param_pointers) { assert(param_pointers.size() == 2); population_mean_ = static_cast(param_pointers[0]); population_variance_ = static_cast(param_pointers[1]); } void setConstants(const double exp_avg_factor, const double eps) { exp_avg_factor_ = exp_avg_factor; eps_ = eps; } void processCudnnStatus(const cudnnStatus_t& status, const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { if (status != CUDNN_STATUS_SUCCESS) LOG(FATAL) << string << " " << cudnnGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudnnGetErrorString(status); } void checkCudaStatus(const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { cudaError_t status = cudaGetLastError(); if (status != cudaSuccess) LOG(FATAL) << string << " " << cudaGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudaGetErrorString(status); } size_t size_retired_ctas(int grid_y) const { // Note that the value of max_grid_y to handle known GPUs is about 160. const int max_grid_y = 1024; if (grid_y > max_grid_y) LOG(INFO) << "GPU capabilities exceeds assumptions."; const int retired_cta_bytes = max_grid_y * 2 * sizeof(int); // Since the region will be initialized once and used for many kernels, // the idea is to return an ample size that will cover all uses. return retired_cta_bytes; } cudnnTensorDescriptor_t X_tensor_desc_ = nullptr; cudnnTensorDescriptor_t Y_tensor_desc_ = nullptr; void* X_ = nullptr; void* dX_ = nullptr; void* Y_ = nullptr; void* dY_ = nullptr; void* addend_ = nullptr; void* dAddend_ = nullptr; // Learned scale and bias weights. float* scale_ = nullptr; float* dscale_ = nullptr; float* bias_ = nullptr; float* dbias_ = nullptr; // Computed population mean and variance parameters. float* population_mean_ = nullptr; float* population_variance_ = nullptr; // Workspace buffers for minibatch mean and variance (computed in fwd, needed by bwd). float* minibatch_mean_ = nullptr; float* minibatch_variance_ = nullptr; int m_ = 0; // Number of values per channel that BN is normalizing. int c_ = 0; // Number of channels over which BN is normalizing. float svar_inv_count_ = 0.f; // factor to scale sum of squared errors to get saved variance float rvar_inv_count_ = 0.f; // factor to scale sum of squared errors to get running variance double exp_avg_factor_ = 0.; double eps_ = 0.; std::string name_; private: void setTensorDescriptor(cudnnTensorDescriptor_t descriptor, cudnnTensorFormat_t format, cudnnDataType_t data_type, int n, int c, int h, int w) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnSetTensor4dDescriptor(descriptor, format, data_type, n, c, h, w); processCudnnStatus(status, "set tensor descriptor"); } void createTensorDescriptor(cudnnTensorDescriptor_t *descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnCreateTensorDescriptor(descriptor); processCudnnStatus(status, "create tensor_descriptor"); } void destroyTensorDescriptor(cudnnTensorDescriptor_t descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnDestroyTensorDescriptor(descriptor); processCudnnStatus(status, "destroy tensor_descriptor"); } protected: float *partial_sums_ = nullptr; int *partial_counts_ = nullptr; int *retired_ctas_ = nullptr; unsigned int *relu_bitmask_ = nullptr; void _setFwdParams(NhwcBatchNormFwdParams *params) const; void _setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const; void _setBwdParams(NhwcBatchNormBwdParams *params) const; // @todo: ability to configure these? // Kernel params static const int USE_ONLINE_APPROACH = 1; static const int THREADS_PER_CTA = 512; static const int THREADS_PER_PIXEL = 16; static const int C_ELEMENTS_PER_CTA = 64; static const int ELEMENTS_PER_LDG = C_ELEMENTS_PER_CTA / THREADS_PER_PIXEL; static const int MAX_SMEM_WITHOUT_OPT_IN = 48 * 1024; typedef uint16_t StorageType; // increasing this to 6 causes spills in fwd kernel! static const int PIXELS_PER_THREAD_IN_REGISTERS_FWD = 5; static const int PIXELS_PER_THREAD_IN_REGISTERS_BWD = 3; static const int PIXELS_PER_THREAD_IN_SMEM_FWD = 10; static const int PIXELS_PER_THREAD_IN_SMEM_BWD = 5; static const int PIXELS_PER_THREAD_FWD = PIXELS_PER_THREAD_IN_REGISTERS_FWD + \ PIXELS_PER_THREAD_IN_SMEM_FWD; static const int PIXELS_PER_THREAD_BWD = PIXELS_PER_THREAD_IN_REGISTERS_BWD + \ PIXELS_PER_THREAD_IN_SMEM_BWD; static const int PIXELS_PER_THREAD_FWD_INFERENCE = 4; // Derived params static const size_t SMEM_SIZE_FWD = PIXELS_PER_THREAD_IN_SMEM_FWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*sizeof(StorageType); static const size_t SMEM_SIZE_BWD = PIXELS_PER_THREAD_IN_SMEM_BWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*2*sizeof(StorageType); static const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; static const int PIXELS_PER_CTA_FWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD; static const int PIXELS_PER_CTA_BWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_BWD; static const int PIXELS_PER_CTA_FWD_INFERENCE = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD_INFERENCE; // max grid.y in case of group bn is limited by exchange buffer size static const int MAX_GBN_BLOCK_Y = 256; // Helper function to launch the forward kernel. // We calculate (based on smem usage) the achievable occupancy and make sure we run a kernel // version that was compiled with that occupancy in its launch bounds. This way, we avoid // needless register spills. void _fwdKernelLauncher(cudaStream_t stream, NhwcBatchNormFwdParams params, dim3 grid_dim, int outer_loops, const int occupancy, const bool coop) { #define LAUNCH_FWD_KERNEL(OUTER_LOOPS, USE_RELU, USE_ADD_RELU, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_FWD <= MAX_SMEM_WITHOUT_OPT_IN) << \ "Nhwc batchnormaddrelu kernel smem too big."; \ auto fwd_func = nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(fwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " fwd ser coop kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using FWD_FUNC = decltype(nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } else { \ cudaLaunchKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } \ checkCudaStatus(name_ + " fwd ser coop kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, false, true, 2, coop); else LAUNCH_FWD_KERNEL(1, false, true, 1, coop); } else { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, false, true, 2, coop); else LAUNCH_FWD_KERNEL(0, false, true, 1, coop); } #undef LAUNCH_FWD_KERNEL } // Helper function to launch the backward kernel. void _bwdKernelLauncher(cudaStream_t stream, NhwcBatchNormBwdParams params, dim3 grid_dim, int outer_loops, const int occupancy, const bool coop) { #define LAUNCH_BWD_ADD_RELU_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << \ "Nhwc batchnormaddrelu kernel smem too big."; \ auto bwd_add_relu_func = nhwc_batch_norm_bwd_add_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_add_relu_func, \ cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + \ " bwd-add-relu coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_ADD_RELU_FUNC = decltype(nhwc_batch_norm_bwd_add_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_add_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_add_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd-add-relu coop serial kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1) { if (occupancy >= 2) LAUNCH_BWD_ADD_RELU_KERNEL(1, 2, coop); else LAUNCH_BWD_ADD_RELU_KERNEL(1, 1, coop); } else { if (occupancy >= 2) LAUNCH_BWD_ADD_RELU_KERNEL(0, 2, coop); else LAUNCH_BWD_ADD_RELU_KERNEL(0, 1, coop); } #undef LAUNCH_BWD_KERNEL } public: // Calculate the expected fwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_fwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int fwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int fwd_smem_bytes = SMEM_SIZE_FWD + fwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / fwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } // Calculate the expected bwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_bwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int bwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int bwd_smem_bytes = SMEM_SIZE_BWD + bwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / bwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } }; const std::vector NhwcBatchNormAddRelu::numWorkspaceBytes() const { assert(c_ > 0); // choose the max memory required between fwd/bwd passes int grid_x_fwd = div_up(m_, PIXELS_PER_CTA_FWD); int grid_x_bwd = div_up(m_, PIXELS_PER_CTA_BWD); int grid_x = max(grid_x_fwd, grid_x_bwd); int grid_y = div_up(c_, C_ELEMENTS_PER_CTA); const size_t num_mean_bytes = c_ * sizeof(float); const size_t num_variance_bytes = num_mean_bytes; int elems_per_group = ((m_ + 31) & ~31) * 2; int group_count = div_up(c_, C_ELEMENTS_PER_CTA); const size_t bitmask_bytes = elems_per_group * group_count * sizeof(unsigned int); const size_t size_sums = grid_y*grid_x*THREADS_PER_PIXEL*\ ELEMENTS_PER_LDG*2*sizeof(float); const size_t size_counts = grid_y*grid_x*sizeof(int); return {num_mean_bytes, num_variance_bytes, bitmask_bytes, size_retired_ctas(grid_y), size_sums, size_counts}; } void NhwcBatchNormAddRelu::setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes) { assert(workspace.size() == 6); assert(num_workspace_bytes.size() == 6); minibatch_mean_ = static_cast(workspace[0]); minibatch_variance_ = static_cast(workspace[1]); relu_bitmask_ = static_cast(workspace[2]); retired_ctas_ = static_cast(workspace[3]); partial_sums_ = static_cast(workspace[4]); partial_counts_ = static_cast(workspace[5]); } void NhwcBatchNormAddRelu::_setFwdParams(NhwcBatchNormFwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = static_cast(addend_); params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_running_mean = population_mean_; params->gmem_running_var = population_variance_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->gmem_relu_bitmask = relu_bitmask_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->rvar_inv_count = rvar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_counts = partial_counts_; params->gmem_retired_ctas = retired_ctas_; params->var_eps = eps_; params->outer_loops = 0; params->exp_avg_factor = static_cast(exp_avg_factor_); params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNormAddRelu::_setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = static_cast(addend_); params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_mean = population_mean_; params->gmem_var = population_variance_; params->nhw = m_; params->c = c_; params->var_eps = eps_; } void NhwcBatchNormAddRelu::_setBwdParams(NhwcBatchNormBwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dy = static_cast(dY_); params->gmem_dst = static_cast(dX_); params->gmem_dst1 = static_cast(dAddend_); params->gmem_relu_bitmask = relu_bitmask_; params->gmem_dscale = dscale_; params->gmem_dbias = dbias_; params->gmem_scale = scale_; params->gmem_bias = bias_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_retired_ctas = retired_ctas_; params->outer_loops = 0; params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNormAddRelu::fwdInference(cudaStream_t stream) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr // && minibatch_mean_ != nullptr // && minibatch_variance_ != nullptr && population_mean_ != nullptr && population_variance_ != nullptr && X_ != nullptr // && dX_ != nullptr && Y_ != nullptr && addend_ != nullptr // && dY_ != nullptr // && dscale_ != nullptr // && dbias_ != nullptr && partial_sums_ != nullptr && partial_counts_ != nullptr; if (!ptrs_are_set) die(); dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD_INFERENCE); grid_dim.y = div_up(c_, C_ELEMENTS_PER_CTA); // @todo: maybe just move this inside initialize routine? NhwcBatchNormFwdInferenceParams params; _setFwdInferenceParams(¶ms); nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference-relu kernel"); } dim3 NhwcBatchNormAddRelu::calc_fwd_grid(int *loop, const int grid_dim_x) { dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD); int c_blks = div_up(c_, C_ELEMENTS_PER_CTA); unsigned int max_grid_x = grid_dim_x; if (grid_dim.x <= max_grid_x) { *loop = 1; if (max_grid_x / grid_dim.x > 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y> 1); dim3 grid_dim = calc_fwd_grid(¶ms.outer_loops, grid_dim_x); _fwdKernelLauncher(stream, params, grid_dim, params.outer_loops, occupancy, coop); } void NhwcBatchNormAddRelu::dgrad(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr && minibatch_mean_ != nullptr && minibatch_variance_ != nullptr && relu_bitmask_ != nullptr // && population_mean_ != nullptr // && population_variance_ != nullptr && X_ != nullptr && dX_ != nullptr // && Y_ != nullptr && dY_ != nullptr && dAddend_ != nullptr && dscale_ != nullptr && dbias_ != nullptr && retired_ctas_ != nullptr; if (!ptrs_are_set) die(); // reset of retired_cta_count no longer needed NhwcBatchNormBwdParams params; _setBwdParams(¶ms); params.my_data = my_data; params.pair_datas[0] = pair_data; params.pair_datas[1] = pair_data2; params.pair_datas[2] = pair_data3; params.magic = magic; params.sync_iters = (bn_group==8)?3:(bn_group >> 1); params.wgrad_coeff = 1.0 / bn_group; dim3 grid_dim = calc_bwd_grid(¶ms.outer_loops, grid_dim_x); _bwdKernelLauncher(stream, params, grid_dim, params.outer_loops, occupancy, coop); } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/cuda_utils.h ================================================ #include #ifndef CUDA_UTILS_H #define CUDA_UTILS_H namespace at { namespace cuda { namespace utils { static inline int MaxSharedMemoryPerMultiprocessor(int device_id) { return getDeviceProperties(device_id)->sharedMemPerMultiprocessor; } } } } #endif ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/interface.cpp ================================================ #include #include #include #include #include #include #include #include "ATen/Scalar.h" #ifndef VERSION_GE_1_1 #include "ATen/Type.h" #endif #include "ATen/Tensor.h" #include "ATen/Storage.h" #include "ATen/Generator.h" namespace py = pybind11; int64_t get_buffer_size( const int bn_sync_steps); void* get_data_ptr( const at::Tensor& data); void* get_remote_data_ptr( const at::Tensor& handle, const int64_t offset); void close_remote_data( const at::Tensor& handle); at::Tensor nhwc_bn_fwd_train( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_fwd_eval( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon, const bool fuse_relu); std::vector nhwc_bn_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_addrelu_fwd_train( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_addrelu_fwd_eval( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon); std::vector nhwc_bn_addrelu_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); int nhwc_bn_fwd_occupancy(); int nhwc_bn_bwd_occupancy(); int nhwc_bn_addrelu_fwd_occupancy(); int nhwc_bn_addrelu_bwd_occupancy(); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("get_buffer_size", &get_buffer_size, "get_buffer_size"); m.def("get_data_ptr", &get_data_ptr, "get_data_ptr"); m.def("get_remote_data_ptr", &get_remote_data_ptr, "get_remote_data_ptr"); m.def("close_remote_data", &close_remote_data, "close_remote_data"); m.def("bn_fwd_nhwc", &nhwc_bn_fwd_train, "bn_fwd_nhwc"); m.def("bn_fwd_eval_nhwc", &nhwc_bn_fwd_eval, "bn_fwd_eval_nhwc"); m.def("bn_bwd_nhwc", &nhwc_bn_bwd, "bn_bwd_nhwc"); m.def("bn_fwd_nhwc_occupancy", &nhwc_bn_fwd_occupancy, "bn_fwd_nhwc_occupancy"); m.def("bn_bwd_nhwc_occupancy", &nhwc_bn_bwd_occupancy, "bn_bwd_nhwc_occupancy"); m.def("bn_addrelu_fwd_nhwc", &nhwc_bn_addrelu_fwd_train, "bn_addrelu_fwd_nhwc"); m.def("bn_addrelu_fwd_eval_nhwc", &nhwc_bn_addrelu_fwd_eval, "bn_addrelu_fwd_eval_nhwc"); m.def("bn_addrelu_bwd_nhwc", &nhwc_bn_addrelu_bwd, "bn_addrelu_bwd_nhwc"); m.def("bn_addrelu_fwd_nhwc_occupancy", &nhwc_bn_addrelu_fwd_occupancy, "bn_addrelu_fwd_nhwc_occupancy"); m.def("bn_addrelu_bwd_nhwc_occupancy", &nhwc_bn_addrelu_bwd_occupancy, "bn_addrelu_bwd_nhwc_occupancy"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/ipc.cu ================================================ #include #include #include #include "THC/THC.h" #include #include "compat.h" #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) template<> struct std::hash { size_t operator() (const cudaIpcMemHandle_t& handle) const { size_t hash = 0; uint8_t* ptr = (uint8_t*)&handle; assert(sizeof(uint8_t) == 1); for (int i=0; i struct std::equal_to { bool operator() (const cudaIpcMemHandle_t &lhs, const cudaIpcMemHandle_t &rhs) const { return (std::memcmp((void*) &lhs, (void*) &rhs, sizeof(cudaIpcMemHandle_t)) == 0); } }; namespace { namespace gpuipc { //from: src/operator/nn/cudnn/nhwc_batch_norm_kernel.h // The number of threads per pixel. const int THREADS_PER_PIXEL = 16; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The number of reducing ops, each uses its own space : mean, var, dscale, dbias const int REDUCE_OPS = 4; // Maximum block.y supported - limited due to buffer allocation const int MAX_BLOCK_Y = 256; const int MAX_OFFSET = REDUCE_OPS*MAX_BLOCK_Y; const int BYTES_PER_ELEM = 4; // Buffer size per sync step const int SINGLE_SYNC_BUFFER_BYTES = MAX_OFFSET*THREADS_PER_PIXEL*2*ELEMENTS_PER_LDG*BYTES_PER_ELEM; }; class IpcMemHandleRegistry { public: void* getPtr(const cudaIpcMemHandle_t& handle, int64_t offset) { if (registry_.count(handle) == 0) { registry_.insert(std::make_pair(handle, RegistryEntry())); registry_[handle].dev_ptr = ipcOpenMem(handle); } registry_[handle].ref_count++; return (((uint8_t*)registry_[handle].dev_ptr) + offset); } void releasePtr(const cudaIpcMemHandle_t& handle) { if (registry_.count(handle) == 0) { } if (--registry_[handle].ref_count == 0) { ipcCloseMem(registry_[handle].dev_ptr); registry_.erase(handle); } } struct RegistryEntry { void* dev_ptr; int ref_count; RegistryEntry() : dev_ptr(NULL) , ref_count(0) {} }; protected: std::unordered_map registry_; void* ipcOpenMem(const cudaIpcMemHandle_t& handle) { void *data; cudaIpcOpenMemHandle(&data, handle, cudaIpcMemLazyEnablePeerAccess); cudaCheckErrors("ipc init"); return data; } void ipcCloseMem(void* dev_ptr) { cudaIpcCloseMemHandle(dev_ptr); cudaCheckErrors("ipc close"); } }; } static IpcMemHandleRegistry ipc_mem_registry; int64_t get_buffer_size(const int bn_sync_steps) { return bn_sync_steps * gpuipc::SINGLE_SYNC_BUFFER_BYTES; } void* get_remote_data_ptr(const at::Tensor& handle, const int64_t offset) { cudaIpcMemHandle_t my_handle; memcpy((unsigned char *)(&my_handle), handle.DATA_PTR(), sizeof(my_handle)); return ipc_mem_registry.getPtr(my_handle, offset); } void close_remote_data(const at::Tensor& handle) { cudaIpcMemHandle_t my_handle; memcpy((unsigned char *)(&my_handle), handle.DATA_PTR(), sizeof(my_handle)); ipc_mem_registry.releasePtr(my_handle); } void* get_data_ptr( const at::Tensor& data) { return data.DATA_PTR(); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/groupbn/nhwc_batch_norm_kernel.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm_kernel.h * \brief CUDA NHWC Batch Normalization code * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Maxim Milakov, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ #include #include #define DEVICE_FUNCTION static inline __device__ // CTA margin used by cooperative launch. Can be overridden by env var NHWC_BATCHNORM_LAUNCH_MARGIN. #define NHWC_BATCHNORM_LAUNCH_MARGIN_MIN 3 #define NHWC_BATCHNORM_LAUNCH_MARGIN_DEFAULT NHWC_BATCHNORM_LAUNCH_MARGIN_MIN //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename T, int ELEMENTS_PER_LDG > struct PackedStorage { enum { PACKED_ELEMENTS_PER_LDG = ELEMENTS_PER_LDG }; typedef T Type; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int ELEMENTS_PER_LDG > struct PackedStorage { enum { PACKED_ELEMENTS_PER_LDG = ELEMENTS_PER_LDG/2 }; typedef int Type; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void from_float(int (&dst)[N], const float (&src)[2*N]) { #pragma unroll for (int i = 0; i < N; ++i) { uint16_t lo, hi; asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(lo) : "f"(src[2*i+0])); asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(hi) : "f"(src[2*i+1])); asm volatile("mov.b32 %0, {%1, %2};" : "=r"(dst[i]) : "h"(lo), "h"(hi)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void from_float(float (&dst)[N], const float (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = src[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void to_float(float (&dst)[2*N], int (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { uint16_t lo, hi; asm volatile("mov.b32 {%0, %1}, %2;" : "=h"(lo), "=h"(hi) : "r"(src[i])); asm volatile("cvt.f32.f16 %0, %1;" : "=f"(dst[2*i+0]) : "h"(lo)); asm volatile("cvt.f32.f16 %0, %1;" : "=f"(dst[2*i+1]) : "h"(hi)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void to_float(float (&dst)[N], float (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = src[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg(int (&dst)[1], const uint16_t *gmem) { dst[0] = __ldg((const int*) gmem); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg_stream(int (&dst)[1], const uint16_t *gmem) { unsigned int tmp; asm volatile ("ld.global.cs.nc.s32 %0, [%1];" : "=r"(tmp) : "l" ((const uint *)gmem)); dst[0] = tmp; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg(int (&dst)[2], const uint16_t *gmem) { int2 tmp = __ldg((const int2*) gmem); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg_stream(int (&dst)[2], const uint16_t *gmem) { int2 tmp; asm volatile ("ld.global.cs.nc.v2.s32 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : "l"((const int2 *)gmem)); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void ldg(float (&dst)[N], const uint16_t *gmem) { int tmp[N/2]; ldg(tmp, gmem); to_float(dst, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void ldg_stream(float (&dst)[N], const uint16_t *gmem) { int tmp[N/2]; ldg_stream(tmp, gmem); to_float(dst, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg(uint16_t *gmem, int (&src)[1]) { reinterpret_cast(gmem)[0] = src[0]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg_stream(uint16_t *gmem, int (&src)[1]) { unsigned int tmp = src[0]; asm volatile ("st.global.cs.s32 [%0], %1;" :: "l"((uint *)gmem) , "r"(tmp)); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg(uint16_t *gmem, int (&src)[2]) { reinterpret_cast(gmem)[0] = make_int2(src[0], src[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg_stream(uint16_t *gmem, int (&src)[2]) { asm volatile ("st.global.cs.v2.s32 [%0], {%1,%2};" :: "l"((uint *)gmem) , "r"(src[0]), "r"( src[1])); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void stg(uint16_t *gmem, float (&src)[N]) { int tmp[N/2]; from_float(tmp, src); stg(gmem, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void stg_stream(uint16_t *gmem, float (&src)[N]) { int tmp[N/2]; from_float(tmp, src); stg_stream(gmem, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_gmem(float (&dst)[2], const float *gmem, int idx) { float2 tmp = __ldg(reinterpret_cast(&gmem[2*idx])); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_gmem(float (&dst)[4], const float *gmem, int idx) { float4 tmp = __ldg(reinterpret_cast(&gmem[4*idx])); dst[0] = tmp.x; dst[1] = tmp.y; dst[2] = tmp.z; dst[3] = tmp.w; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(float (&x)[2], const float *smem, int idx) { float2 tmp = *(const float2*) &smem[2*idx]; x[0] = tmp.x; x[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(int (&x)[1], const int *smem, int idx) { x[0] = smem[idx]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(float (&x)[4], const float *smem, int idx) { float4 tmp = *(const float4*) &smem[4*idx]; x[0] = tmp.x; x[1] = tmp.y; x[2] = tmp.z; x[3] = tmp.w; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(int (&x)[2], const int *smem, int idx) { int2 tmp = *(const int2*) &smem[2*idx]; x[0] = tmp.x; x[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_gmem(float *gmem, int idx, const float (&src)[2]) { reinterpret_cast(&gmem[2*idx])[0] = make_float2(src[0], src[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_gmem(float *gmem, int idx, const float (&src)[4]) { reinterpret_cast(&gmem[4*idx])[0] = make_float4(src[0], src[1], src[2], src[3]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void scaled_write_to_gmem(float *gmem, int idx, const float (&src)[4], const float coeff) { reinterpret_cast(&gmem[4*idx])[0] = make_float4(src[0]*coeff, src[1]*coeff, src[2]*coeff, src[3]*coeff); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(float *smem, int idx, const float (&x)[2]) { reinterpret_cast(&smem[2*idx])[0] = make_float2(x[0], x[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(int *smem, int idx, const int (&x)[1]) { smem[idx] = x[0]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(float *smem, int idx, const float (&x)[4]) { reinterpret_cast(&smem[4*idx])[0] = make_float4(x[0], x[1], x[2], x[3]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(int *smem, int idx, const int (&x)[2]) { reinterpret_cast(&smem[2*idx])[0] = make_int2(x[0], x[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void zero_array(int (&dst)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = 0; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void zero_array(float (&dst)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = 0.f; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void add(float (&x)[N], const float (&y)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] += y[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void multiply(float (&x)[N], const float (&y)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] *= y[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void scale_(float (&x)[N], float scalar) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] *= scalar; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void normalize(float (&x)[N], const float (&bias)[N], const float (&scale)[N], const float (&m1)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] = bias[i] + scale[i] * (x[i] - m1[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION Storage relu(Storage in) { Storage zero = (Storage)0.f; return (in < zero)? zero : in; } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_activation(float (&x)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] = relu(x[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA > DEVICE_FUNCTION void parallel_sums_16x2(float *smem, float (&x)[4], int nhw, void* params_my_data, void** params_pair_datas, int off, const int magic, const int sync_iters) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of threads per pixel. const int THREADS_PER_PIXEL = 16; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The number of reducing ops, each uses its own space : mean, var, dscale, dbias const int REDUCE_OPS = 4; // Maximum block.y supported - limited due to buffer allocation const int MAX_BLOCK_Y = 256; const int MAX_OFFSET = REDUCE_OPS*MAX_BLOCK_Y; // The warp decomposition. const int warp_id = threadIdx.x / THREADS_PER_WARP; const int lane_id = threadIdx.x % THREADS_PER_WARP; // total size of data per sync iter const int data_total = MAX_OFFSET*THREADS_PER_PIXEL*ELEMENTS_PER_LDG*2; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); } // The warp leaders, write to SMEM. if (lane_id < THREADS_PER_PIXEL) { write_to_smem(smem, warp_id*THREADS_PER_PIXEL + lane_id, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // The 1st warp does all the work. // We do the final reduction each half-warp sequentially reduces the final values. if (warp_id == 0) { read_from_smem(x, smem, threadIdx.x); #pragma unroll for (int offset = 1; offset < WARPS_PER_CTA/(THREADS_PER_WARP / THREADS_PER_PIXEL); ++offset) { float y[ELEMENTS_PER_LDG]; // Read the mean and variance from the other pixel. read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_WARP); // Compute the updated sum. add(x, y); } for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); } // Make sure the data was read from SMEM. __syncwarp(); // Store the final values. if (threadIdx.x < THREADS_PER_PIXEL) { // probably could do it earlier, before sync for (int sync_iter=0; sync_iter < sync_iters; ++sync_iter) { //float* params_pair_data = (reinterpret_cast(params_pair_datas))[sync_iter]; void* params_pair_data = params_pair_datas[sync_iter]; // skip the space consumed by previous sync iterations const int xbuf_offset = sync_iter*data_total; // data starts after flags, but have to skip previous const int data_offset = xbuf_offset + off*ELEMENTS_PER_LDG*THREADS_PER_PIXEL*2 + ELEMENTS_PER_LDG*threadIdx.x*2; // after sums for this GPU were computed, let CTA0 broadcast the sum to over GPU if (blockIdx.x == 0) { volatile float * write_data = &((reinterpret_cast(params_pair_data))[data_offset]); // write the data to memory region to be reflected to other GPU asm volatile ("st.global.wt.v4.b32 [%0], {%1,%2,%3,%4};" :: "l"(write_data) , "f"(x[0]), "r"(magic), "f"(x[2]), "r"(magic)); asm volatile ("st.global.wt.v4.b32 [%0], {%1,%2,%3,%4};" :: "l"(write_data+4) , "f"(x[1]), "r"(magic), "f"(x[3]), "r"(magic)); } // now each CTA (on each GPU) reads the data written by CTA 0 of the other GPU volatile float * read_data = &((reinterpret_cast(params_my_data))[data_offset]); float other[4]; uint32_t other_flag_a, other_flag_b; do { asm volatile ("ld.volatile.global.v4.b32 {%0, %1, %2, %3}, [%4];" : "=f"(other[0]), "=r"(other_flag_a), "=f"(other[2]), "=r"(other_flag_b) : "l"(read_data)); } while ((other_flag_a != magic) || (other_flag_b != magic)); do { asm volatile ("ld.volatile.global.v4.b32 {%0, %1, %2, %3}, [%4];" : "=f"(other[1]), "=r"(other_flag_a), "=f"(other[3]), "=r"(other_flag_b) : "l"(read_data+4)); } while ((other_flag_a != magic) || (other_flag_b != magic)); add(x, other); } // finally, after syncing up and accounting for partial sums from // other GPUs as required, write the result write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA > DEVICE_FUNCTION void parallel_sums_8x4(float *smem, float (&x)[4], int nhw) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of threads per pixel. const int THREADS_PER_PIXEL = 8; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The warp decomposition. const int warp_id = threadIdx.x / THREADS_PER_WARP; const int lane_id = threadIdx.x % THREADS_PER_WARP; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL*2+lane_id); } // The warp leaders, write to SMEM. if (lane_id < THREADS_PER_PIXEL) { write_to_smem(smem, warp_id*THREADS_PER_PIXEL + lane_id, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // The 1st warp does all the work. // We do the final reduction each half-warp sequentially reduces the final values. if (warp_id == 0) { read_from_smem(x, smem, threadIdx.x); #pragma unroll for (int offset = 1; offset < WARPS_PER_CTA/(THREADS_PER_WARP / THREADS_PER_PIXEL); ++offset) { float y[ELEMENTS_PER_LDG]; // Read the mean and variance from the other pixel. read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_WARP); // Compute the updated sum. add(x, y); } for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL*2+lane_id); } // Make sure the data was read from SMEM. __syncwarp(); // Store the final values. if (threadIdx.x < THREADS_PER_PIXEL) { write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA, int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG > DEVICE_FUNCTION void parallel_sums(float *smem, float (&x)[ELEMENTS_PER_LDG], int nhw) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of pixels computed by a single warp. const int PIXELS_PER_WARP = THREADS_PER_WARP / THREADS_PER_PIXEL; // The position in the warp. const int nhw_in_warp = nhw % PIXELS_PER_WARP; // The C in the warp. const int c_in_warp = threadIdx.x % THREADS_PER_PIXEL; // Store the values to shared memory. write_to_smem(smem, threadIdx.x, x); // Compute the parallel sums. for (int offset = PIXELS_PER_WARP/2; offset > 0; offset /= 2) { // NOP. __syncwarp(); // Read the running sum from the other thread. float y[ELEMENTS_PER_LDG]; if (nhw_in_warp < offset) { read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_PIXEL); } // Compute the updated sum. add(x, y); // NOP. __syncwarp(); // Update the sum in SMEM. if (offset > 1 && nhw_in_warp < offset) { write_to_smem(smem, threadIdx.x, x); } } // The warps are done. Do the final reduction at the CTA level. __syncthreads(); // The warp leaders, write to SMEM. const int idx = (threadIdx.x/THREADS_PER_WARP)*THREADS_PER_PIXEL + c_in_warp; if (nhw_in_warp == 0) { write_to_smem(smem, idx, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // Read the 1st element to prepare the work. if (nhw < WARPS_PER_CTA/2) { read_from_smem(x, smem, threadIdx.x); } // We have the running mean and running m2. Let's build the mean/var of the CTA. for (int offset = WARPS_PER_CTA/2; offset > 0; offset /= 2) { // NOP. __syncwarp(); // Read the mean and variance from the other pixel. float y[ELEMENTS_PER_LDG]; if (nhw < offset) { read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_PIXEL); } // Compute the updated sum. add(x, y); // NOP. __syncwarp(); // Store the mean/var for the different pixels. if (nhw < offset) { write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG > struct ParallelSums { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[ELEMENTS_PER_LDG], int nhw) { parallel_sums(smem, x, nhw); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct ParallelSums<16, 4> { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[4], int nhw) { parallel_sums_16x2(smem, x, nhw, 0, 0, 0, 0, 0); } template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatchX(float *smem, float (&x)[4], int nhw, void* params_my_data, void** params_pair_datas, int off, const int magic, const unsigned int& sync_iters) { parallel_sums_16x2(smem, x, nhw, params_my_data, params_pair_datas, off, magic, sync_iters); } }; template<> struct ParallelSums<8, 4> { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[4], int nhw) { parallel_sums_8x4(smem, x, nhw); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// static inline int div_up(int m, int n) { return (m + n - 1) / n; } //////////////////////////////////////////////////////////////////////////////////////////////////// // It is expected that all threads in the CTA enter this function! DEVICE_FUNCTION void inter_block_sync(int* gmem_retired_ctas, int expected_count, bool master) { // Register the CTA. if (threadIdx.x == 0) { // Issue the membar. __threadfence(); // Notify that the CTA is done. int val_to_add = 1; if (master) { val_to_add = -(expected_count - 1); } atomicAdd(gmem_retired_ctas, val_to_add); } // Are all CTAs done? if (threadIdx.x == 0) { int retired_ctas = -1; do { __threadfence(); asm volatile ("ld.global.cg.b32 %0, [%1];" : "=r"(retired_ctas) : "l"(gmem_retired_ctas)); } while (retired_ctas != 0); } __syncthreads(); } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormFwdInferenceParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dst, *gmem_src1; // the final mean and variance as calculated during the training process float *gmem_mean, *gmem_var; // The bias/scale. float *gmem_bias, *gmem_scale; // The dimensions. int nhw, c; // epsilon float var_eps; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // No DESIRED_OCCUPANCY launch bounds needed, as this is not launched cooperatively template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG, bool USE_RELU, bool USE_ADD_RELU > __global__ __launch_bounds__(THREADS_PER_CTA) void nhwc_batch_norm_fwd_inference(NhwcBatchNormFwdInferenceParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // The start position in the NHW dimension where the CTA starts. const int cta_nhw_stride = gridDim.x * PIXELS_PER_LDG; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // thread's starting point in NHW const int thread_nhw = thread_in_cta_nhw + blockIdx.x * PIXELS_PER_LDG; // The position in the C dimension where the CTA starts. const int cta_c = blockIdx.y * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; float mean[ELEMENTS_PER_LDG], var[ELEMENTS_PER_LDG]; float scale[ELEMENTS_PER_LDG], bias[ELEMENTS_PER_LDG]; zero_array(mean); zero_array(var); zero_array(scale); zero_array(bias); if (is_valid_c) { read_from_gmem(var, ¶ms.gmem_var[cta_c], thread_in_cta_c); read_from_gmem(scale, ¶ms.gmem_scale[cta_c], thread_in_cta_c); read_from_gmem(mean, ¶ms.gmem_mean[cta_c], thread_in_cta_c); read_from_gmem(bias, ¶ms.gmem_bias[cta_c], thread_in_cta_c); } // Update the scale with the stddev and eps. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { scale[i] *= rsqrtf(var[i] + params.var_eps); } // The base pointers for reading/writing uint16_t *const gmem_src = ¶ms.gmem_src[thread_c]; uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; const uint16_t *gmem_src1 = nullptr; if (USE_ADD_RELU) { gmem_src1 = ¶ms.gmem_src1[thread_c]; } // apply BN for (int nhw = thread_nhw; nhw < params.nhw; nhw += cta_nhw_stride) { float x_math[ELEMENTS_PER_LDG]; zero_array(x_math); if (is_valid_c) { ldg(x_math, &gmem_src[nhw*params.c]); } // Normalize and apply activation function normalize(x_math, bias, scale, mean); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg(x1_math, &gmem_src1[nhw*params.c]); add(x_math, x1_math); relu_activation(x_math); } else if (USE_RELU) { relu_activation(x_math); } if (is_valid_c) { stg(&gmem_dst[nhw*params.c], x_math); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormFwdParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dst, *gmem_src1; // The bias/scale. float *gmem_bias, *gmem_scale; // running mean/var (refer BN API from cudnn doc) float *gmem_running_mean, *gmem_running_var; // saved mean/var (refer BN API from cudnn doc) float *gmem_saved_mean, *gmem_saved_var; // ReLU bitmask unsigned int *gmem_relu_bitmask; // The dimensions. int nhw, c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. float svar_inv_count; // factor to scale sum of squared errors to get running variance. Should be 1/nhw or 1/(nhw-1). float rvar_inv_count; // The buffer to do the reduction for mean, stddev and count. float *gmem_sums; // The buffer to count items in the different CTAs. int *gmem_counts; // The counters of retired CTAs. int *gmem_retired_ctas; // The epsilon to apply to the computation of the variance. float var_eps; // outer loop count int outer_loops; // exponential average factor float exp_avg_factor; // number of CTAs along .x dimension int c_blks; void* my_data; void* pair_datas[4]; int magic; int sync_iters; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, bool USE_RELU, bool USE_ADD_RELU, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_fwd(NhwcBatchNormFwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Clamp thread_c so that we load from valid locations even if we don't use the value if (!is_valid_c) thread_c = params.c - 4; // Single pass numerically stable algorithm, see: // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm // // n = 0, mean = 0.0, M2 = 0.0 // // for x in data: // n += 1 // delta = x - mean // mean += delta/n // delta2 = x - mean // M2 += delta*delta2 // // if n < 2: // return float('nan') // else: // return M2 / (n - 1) // Register to store the number of elements read so far. float count = 0.f, mean[ELEMENTS_PER_LDG], m2[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean[i] = 0.f; m2[i] = 0.f; } // The number of elements loaded by this CTA. int cta_count = 0; // The base pointer to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute the mean/var across those elements. const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized, offset is evenly divisible by 32 int offset = (pixels_per_iteration * OUTER_LOOPS + PIXELS_PER_CTA_IN_SMEM * gridDim.x - params.nhw) & ~31; cta_nhw_regs -= offset; cta_nhw_smem -= offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(min(nhw_regs + PIXELS_PER_CTA_IN_REGISTERS, params.nhw) - max(nhw_regs, 0), 0); // Load the data and compute the local mean/sum and the variance. if (USE_ONLINE_APPROACH) { // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { float delta0 = x_math[j] - mean[j]; mean[j] += delta0 * inv_count; float delta1 = x_math[j] - mean[j]; m2[j] += delta0 * delta1 * is_valid[i]; } } } else { // Read the elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); } count += 1.f; } } // Sum the elements in registers. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { mean[j] += x_math[j]; } } // Compute the mean. float inv_count = 1.f / count; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { mean[j] *= inv_count; } // Compute the variance. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Is it a valid pixel? float is_valid = i < static_cast(count) ? 1.f : 0.f; // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { m2[j] += (x_math[j] - mean[j]) * (x_math[j] - mean[j]) * is_valid; } } } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(smem_nhw + PIXELS_PER_CTA_IN_SMEM, params.nhw) - max(smem_nhw, 0); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; float is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) ? 1.f : 0.f; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG]; ldg_stream(x_storage_local, &gmem_src[(is_pixel_valid ? idx : 0)*params.c]); // The offset to store in SMEM. const int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { float delta0 = x_math[j] - mean[j]; mean[j] += delta0 * inv_count; float delta1 = x_math[j] - mean[j]; m2[j] += delta0 * delta1 * is_pixel_valid; } } } // We scale the mean by the number of elements. It brings more stability. float m1[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = mean[i] * count; } // Run the parallel sum accross the CTA to get the local sum. ParallelSums::dispatch( smem, m1, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(m1, smem, thread_in_cta_c); __syncthreads(); // Adjust the variance. float inv_cta_count = 1.f / static_cast(cta_count); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { float mean_diff = m1[i]*inv_cta_count - mean[i]; m2[i] = m2[i] + mean_diff * mean_diff * count; } // Run the parallel sum accross the CTA to get the local adjusted variance. ParallelSums::dispatch( smem, m2, thread_in_cta_nhw); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, m1); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, m2); } // The memory location to store the number of pixels per CTA. int *gmem_counts = ¶ms.gmem_counts[c_blk_index*gridDim.x]; if (threadIdx.x == 0) { gmem_counts[blockIdx.x] = cta_count; } // Read the bias and scale. float bias[ELEMENTS_PER_LDG], scale[ELEMENTS_PER_LDG]; if (is_valid_c) { read_from_gmem(bias, ¶ms.gmem_bias[cta_c], thread_in_cta_c); read_from_gmem(scale, ¶ms.gmem_scale[cta_c], thread_in_cta_c); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the mean to compute the global mean. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = 0.f; } // Build the global mean. #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp[ELEMENTS_PER_LDG]; read_from_gmem(tmp, gmem_sums, idx); add(m1, tmp); } if (params.sync_iters>0) { ParallelSums::dispatchX( smem, m1, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+3, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, m1, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(m1, smem, thread_in_cta_c); __syncthreads(); // Normalize the mean. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = m1[i] * params.svar_inv_count; } // Reset the variance. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m2[i] = 0.f; } // for add+relu fusion const uint16_t *gmem_src1 = nullptr; if (USE_ADD_RELU) { gmem_src1 = ¶ms.gmem_src1[thread_c]; } // Build the global variance. #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { // Read the means computed by different CTAs (again). Reuse tmp if we have 1 iteration. float tmp_mean[ELEMENTS_PER_LDG], tmp_var[ELEMENTS_PER_LDG]; read_from_gmem(tmp_mean, &gmem_sums[ 0], idx); read_from_gmem(tmp_var, &gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx); // Read the number of pixels visited by a given CTA. cta_count = __ldg(&gmem_counts[idx / THREADS_PER_PIXEL]); // Compute the diff to update the variance. float mean_diff[ELEMENTS_PER_LDG], inv_cta_count = 1.f / static_cast(cta_count); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean_diff[i] = m1[i] - tmp_mean[i]*inv_cta_count; } // Update the variance. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m2[i] += tmp_var[i] + mean_diff[i]*mean_diff[i]*static_cast(cta_count); } } if (params.sync_iters>0) { ParallelSums::dispatchX( smem, m2, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+2, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, m2, thread_in_cta_nhw); } __syncthreads(); read_from_smem(m2, smem, thread_in_cta_c); // Finalize the stddev. // becasue saved var and running var may have different denominator, we don't do it here // scale_(m2, inv_count); // store the saved mean/var float svarinv[ELEMENTS_PER_LDG]; bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { svarinv[i] = rsqrtf(m2[i] * params.svar_inv_count + params.var_eps); } if (is_valid_for_saving) { write_to_gmem(params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG, m1); write_to_gmem(params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG, svarinv); } // store the running mean/var float rmean[ELEMENTS_PER_LDG], rvar[ELEMENTS_PER_LDG]; zero_array(rmean); zero_array(rvar); if (params.exp_avg_factor != 1.f && is_valid_for_saving) { read_from_gmem(rmean, params.gmem_running_mean, thread_c/ELEMENTS_PER_LDG); read_from_gmem(rvar, params.gmem_running_var, thread_c/ELEMENTS_PER_LDG); } #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { rmean[i] = (1.f - params.exp_avg_factor) * rmean[i] + \ params.exp_avg_factor * m1[i]; rvar[i] = (1.f - params.exp_avg_factor) * rvar[i] + \ params.exp_avg_factor * (m2[i] * params.rvar_inv_count); } if (is_valid_for_saving) { write_to_gmem(params.gmem_running_mean, thread_c/ELEMENTS_PER_LDG, rmean); write_to_gmem(params.gmem_running_var, thread_c/ELEMENTS_PER_LDG, rvar); } // Update the scale with the stddev and eps. multiply(scale, svarinv); // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; unsigned int *const gmem_relu_bitmask = params.gmem_relu_bitmask + ((params.nhw + 31) & ~31) * 2 * c_blk_index; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_valid = is_valid_nhw && is_valid_c; // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Normalize and apply activation function normalize(x_math, bias, scale, m1); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg_stream(x1_math, &gmem_src1[(is_valid ? idx : 0)*params.c]); add(x_math, x1_math); unsigned int relu_mask; int lane_id = threadIdx.x & 31; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { bool rectified = x_math[i] < 0.0F; unsigned int local_relu_mask = __ballot_sync(0xFFFFFFFFU, rectified); if (lane_id == i) { // Thread 0 remembers the relu_mask from the first time through this // loop, Thread 1 the next, Thread 2 the next, and Thread 3 the last. relu_mask = local_relu_mask; } if (rectified) { x_math[i] = 0.0F; } } if (is_valid_nhw && (lane_id < ELEMENTS_PER_LDG)) { gmem_relu_bitmask[idx * 2 + lane_id] = relu_mask; } } else if (USE_RELU) { relu_activation(x_math); } // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], x_math); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { #pragma unroll 2 for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_valid = is_valid_nhw && is_valid_c; // Read from SMEM. const int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); // Normalize and apply activation function normalize(x_math, bias, scale, m1); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg_stream(x1_math, &gmem_src1[(is_valid ? idx : 0)*params.c]); add(x_math, x1_math); unsigned int relu_mask; int lane_id = threadIdx.x & 31; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { bool rectified = x_math[i] < 0.0F; unsigned int local_relu_mask = __ballot_sync(0xFFFFFFFFU, rectified); if (lane_id == i) { relu_mask = local_relu_mask; } if (rectified) { x_math[i] = 0.0F; } } if (is_valid_nhw && (lane_id < ELEMENTS_PER_LDG)) { gmem_relu_bitmask[idx * 2 + lane_id] = relu_mask; } } else if (USE_RELU) { relu_activation(x_math); } // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], x_math); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormBwdParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dy, *gmem_dst, *gmem_dst1; // dscale/dbias float *gmem_dscale, *gmem_dbias; // The scale and bias. float *gmem_scale, *gmem_bias; // The mean/inv-var saved from fwd pass float *gmem_saved_mean, *gmem_saved_var; // ReLU bitmask unsigned int *gmem_relu_bitmask; // The dimensions. int nhw, c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. float svar_inv_count; // The buffer to do the reduction for dscale and dbias float *gmem_sums; // The counters of retired CTAs. int *gmem_retired_ctas; // outer loop count int outer_loops; // number of CTAs along .x dimension int c_blks; void* my_data; void* pair_datas[4]; int magic; int sync_iters; float wgrad_coeff; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const float (&x)[N], const float (&mean_var_scale_bias)[N], const float (&var_scale)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { float y = (x[j] * var_scale[j]) + mean_var_scale_bias[j]; if ((y <= 0.f) && valid_data) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const float (&y)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { if ((y[j] <= 0.f) && valid_data) { dy[j] = 0.f; } } } template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const bool (&rectified)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { if (rectified[j] && valid_data) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd_for_dx(float (&dy)[N], const float (&x)[N], const float (&mean_var_scale_bias)[N], const float (&var_scale)[N]) { #pragma unroll for (int j = 0; j < N; ++j) { float y = (x[j] * var_scale[j]) + mean_var_scale_bias[j]; if (y <= 0.f) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd_for_dx(float (&dy)[N], const float (&y)[N]) { #pragma unroll for (int j = 0; j < N; ++j) { if (y[j] <= 0.f) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void bwd_update(float (&dscale)[N], float (&dbias)[N], const float (&dy)[N], const float (&x)[N], const float (&mean)[N], float inv_count) { #pragma unroll for (int j = 0; j < N; ++j) { float delta0 = dy[j] - dbias[j]; dbias[j] += delta0 * inv_count; delta0 = (dy[j] * (x[j] - mean[j])) - dscale[j]; dscale[j] += delta0 * inv_count; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void bwd_dx(float (&dx)[N], const float (&dy)[N], const float (&var)[N], const float (&x)[N], const float (&mean)[N], const float (&dscale)[N], const float (&dbias)[N], float inv_count) { #pragma unroll for (int j = 0; j < N; ++j) { float tmp1 = dy[j] - (dbias[j]* inv_count); float tmp2 = dscale[j] * inv_count; float tmp3 = x[j] - mean[j]; dx[j] = var[j] * (tmp1 - (tmp2 * tmp3)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Registers to store the mean used for entire duration float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized int offset = params.nhw - pixels_per_iteration * OUTER_LOOPS - PIXELS_PER_CTA_IN_SMEM * gridDim.x; cta_nhw_regs += offset; cta_nhw_smem += offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; bool is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c); PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // inv-var float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } // Normalize the dscale. multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // scale float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } // Further normalize the dscale to be used in dx calculation multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd_relu(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Registers to store the mean/var/scale/bias used for the entire duration // Register usage optimizations: // 1. Can combine bias - (mean * var * scale) into a single register // 2. Can combine var * scale into a single register float varscale[ELEMENTS_PER_LDG]; zero_array(varscale); if (is_valid_c) { read_from_gmem(varscale, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } float tmp[ELEMENTS_PER_LDG]; zero_array(tmp); if (is_valid_c) { read_from_gmem(tmp, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(varscale, tmp); float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } zero_array(tmp); if (is_valid_c) { read_from_gmem(tmp, params.gmem_bias, thread_c/ELEMENTS_PER_LDG); } float mean_var_scale_bias[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean_var_scale_bias[i] = tmp[i] - (mean[i] * varscale[i]); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized int offset = params.nhw - pixels_per_iteration * OUTER_LOOPS - PIXELS_PER_CTA_IN_SMEM * gridDim.x; cta_nhw_regs += offset; cta_nhw_smem += offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; relu_bwd(dy_math, x_math, mean_var_scale_bias, varscale, is_valid[i]); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; bool is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c); PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd(dy_math, x_math, mean_var_scale_bias, varscale, is_pixel_valid); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // Normalize the dscale. float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // Further normalize the dscale to be used in dx calculation float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); relu_bwd_for_dx(dy_math, x_math, mean_var_scale_bias, var); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd_for_dx(dy_math, x_math, mean_var_scale_bias, var); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd_add_relu(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; uint16_t *gmem_dst1 = ¶ms.gmem_dst1[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized, offset is evenly divisible by 32 int offset = (pixels_per_iteration * OUTER_LOOPS + PIXELS_PER_CTA_IN_SMEM * gridDim.x - params.nhw) & ~31; cta_nhw_regs -= offset; cta_nhw_smem -= offset; } const unsigned int *const gmem_relu_bitmask = params.gmem_relu_bitmask + ((params.nhw + 31) & ~31) * 2 * c_blk_index; #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); int lane_id = threadIdx.x & 31; // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; unsigned int relu_mask[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); if (is_valid_nhw) { if (is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } if (lane_id < ELEMENTS_PER_LDG) { relu_mask[i] = gmem_relu_bitmask[idx * 2 + lane_id]; } } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; bool rectified[ELEMENTS_PER_LDG]; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { rectified[j] = ((__shfl_sync(0xFFFFFFFFU, relu_mask[i], j) & (1U << lane_id)) != 0); } to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; relu_bwd(dy_math, rectified, is_valid[i]); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); // Lastly we need 'dy' only for BN, so store the 'relu-dgrad'ed version from_float(dy_storage[i], dy_math); // dZ for elementwise add if (is_valid[i]) { if (loop_i == OUTER_LOOPS - 1) { stg_stream(&gmem_dst1[idx*params.c], dy_storage[i]); } else { stg(&gmem_dst1[idx*params.c], dy_storage[i]); } } } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_pixel_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_pixel_valid = is_pixel_valid_nhw && is_valid_c; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; unsigned int relu_mask; int lane_id = threadIdx.x & 31; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid_nhw) { if (is_valid_c) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } if (lane_id < ELEMENTS_PER_LDG) { relu_mask = gmem_relu_bitmask[idx * 2 + lane_id]; } } bool rectified[ELEMENTS_PER_LDG]; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { rectified[j] = ((__shfl_sync(0xFFFFFFFFU, relu_mask, j) & (1U << lane_id)) != 0); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd(dy_math, rectified, is_pixel_valid); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); from_float(dy_storage_local, dy_math); // dZ for elementwise add if (is_pixel_valid) { stg_stream(&gmem_dst1[idx*params.c], dy_storage_local); } // only store the 'relu-dgrad'ed version! write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // Normalize the dscale. float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // Further normalize the dscale to be used in dx calculation float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; float y[ELEMENTS_PER_LDG]; zero_array(y); if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dst1[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ ================================================ FILE: KoSentenceT5/apex/contrib/csrc/layer_norm/ln_api.cpp ================================================ #include #include "ATen/cuda/CUDAContext.h" void ln_fwd_cuda(at::Tensor &y, at::Tensor &mu, at::Tensor &rsigma, const at::Tensor &x, const at::Tensor &gamma, const at::Tensor &beta, const float epsilon, const int rows, const int cols, cudaStream_t stream); void ln_bwd_cuda(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, cudaStream_t stream); std::vector ln_fwd(const at::Tensor &x, // BxSxhidden_size const at::Tensor &gamma, // hidden_size const at::Tensor &beta, // hidden_size const float epsilon ) { TORCH_CHECK(x.is_cuda()) TORCH_CHECK(gamma.is_cuda()) TORCH_CHECK(beta.is_cuda()) TORCH_CHECK(x.is_contiguous()); auto sizes = x.sizes(); TORCH_CHECK(sizes.size() == 2); const int rows = sizes[0]; const int cols = sizes[1]; auto dtype = x.scalar_type(); TORCH_CHECK(gamma.dtype() == dtype); TORCH_CHECK(beta.dtype() == dtype); TORCH_CHECK(gamma.sizes() == beta.sizes()); TORCH_CHECK(gamma.numel() == cols); TORCH_CHECK(epsilon >= 0.f); auto stream = at::cuda::getCurrentCUDAStream().stream(); auto y = torch::empty_like(x); auto opts = x.options(); auto mu = torch::empty({rows}, opts.dtype(torch::kFloat32)); auto rsigma = torch::empty({rows}, opts.dtype(torch::kFloat32)); ln_fwd_cuda(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, stream); return {y, mu, rsigma}; } std::vector ln_bwd(const at::Tensor &dw, // BxSxhidden_size const at::Tensor &x, // BxSxhidden_size const at::Tensor &mu, // BxS, FP32! const at::Tensor &rsigma, // BxS, FP32! const at::Tensor &gamma // hidden_size ) { TORCH_CHECK(x.is_cuda()); TORCH_CHECK(dw.is_cuda()); TORCH_CHECK(mu.is_cuda()); TORCH_CHECK(rsigma.is_cuda()); TORCH_CHECK(gamma.is_cuda()); TORCH_CHECK(x.is_contiguous()); TORCH_CHECK(dw.is_contiguous()); auto sizes = x.sizes(); TORCH_CHECK(sizes.size() == 2); TORCH_CHECK(dw.sizes() == sizes); auto rows = sizes[0]; auto cols = sizes[1]; auto dtype = x.scalar_type(); TORCH_CHECK(dw.dtype() == dtype); TORCH_CHECK(gamma.dtype() == dtype); TORCH_CHECK(mu.dtype() == torch::kFloat32); TORCH_CHECK(rsigma.dtype() == torch::kFloat32); TORCH_CHECK(mu.sizes() == rsigma.sizes()); TORCH_CHECK(mu.numel() == rows); TORCH_CHECK(gamma.numel() == cols); auto stream = at::cuda::getCurrentCUDAStream().stream(); auto dx = torch::empty_like(x); auto dgamma = torch::empty_like(gamma); auto dbeta = torch::empty_like(gamma); ln_bwd_cuda(dx, dgamma, dbeta, dw, x, mu, rsigma, gamma, rows, cols, stream); return {dx, dgamma, dbeta}; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.doc() = "CUDA LayerNorm"; // optional module docstring m.def("ln_fwd", &ln_fwd, "Run LayerNorm forward kernel"); m.def("ln_bwd", &ln_bwd, "Run LayerNorm backward kernel"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/layer_norm/ln_bwd_semi_cuda_kernel.cu ================================================ #include "utils.cuh" #include "ln_kernel_traits.h" #include "ATen/cuda/CUDAContext.h" template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_bwd_kernel(void * __restrict__ dx_, void * __restrict__ dg_, void * __restrict__ db_, const void * __restrict__ dw_, const void * __restrict__ x_, const void * __restrict__ mu_, const void * __restrict__ rs_, const void * __restrict__ g_, const int rows ){ using Vec = typename Ktraits::Vec; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { WARPS_M = Ktraits::WARPS_M }; enum { WARPS_N = Ktraits::WARPS_N }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { COLS = Ktraits::COLS }; enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum { LDGS = BYTES_PER_ROW / Ktraits::BYTES_PER_ROW_PER_CTA }; static_assert(LDGS * Ktraits::BYTES_PER_ROW_PER_CTA == BYTES_PER_ROW, ""); enum { NUM_ELTS = Vec::NUM_ELTS }; using vec_t = typename Ktraits::vec_t; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_m = warp / Ktraits::WARPS_N; const int warp_n = warp % Ktraits::WARPS_N; const int tid_r = warp_n * THREADS_PER_WARP + lane; const int r = bidx * Ktraits::ROWS_PER_CTA + warp_m; const int c = warp_n * THREADS_PER_WARP + lane; const char *dw_ptr = static_cast(dw_); const char *x_ptr = static_cast(x_); const char *g_ptr = static_cast(g_); char *dx_ptr = static_cast(dx_); const compute_t *mu_ptr = static_cast(mu_); const compute_t *rs_ptr = static_cast(rs_); static_assert(COLS == THREADS_PER_ROW * LDGS * NUM_ELTS, ""); // smem for final reduction //__shared__ compute_t smem_[ROWS_PER_CTA * COLS]; extern __shared__ compute_t smem_[]; // static_assert(sizeof(smem_dw_sum) == 32*1024,""); // Using the grid stride loop we can assign multiple rows to each thread // by using a number of CTAs smaller than rows / ROWS_PER_CTA // We accumulate them here, one in smem, one in registers, because the smem // capacity is limited compute_t * dw_sum = &smem_dw_sum[warp_m * COLS + tid_r // * LDGS * NUM_ELTS]; compute_t dwy_sum[LDGS * NUM_ELTS]; compute_t dw_sum[LDGS * NUM_ELTS]; memset(dwy_sum, 0, sizeof(compute_t) * LDGS * NUM_ELTS); memset(dw_sum, 0, sizeof(compute_t) * LDGS * NUM_ELTS); // Debug 8 rows, 4B, 1024 cols __shared__ compute_t smem_mdy[ROWS_PER_CTA * WARPS_N]; __shared__ compute_t smem_mdyy[ROWS_PER_CTA * WARPS_N]; compute_t *mdy_shared = &smem_mdy[warp_m * WARPS_N]; compute_t *mdyy_shared = &smem_mdyy[warp_m * WARPS_N]; constexpr float rn = 1.f / float(COLS); Vec gamma[LDGS]; int col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { gamma[it].load_from(g_ptr + col * BYTES_PER_LDG); col += Ktraits::THREADS_PER_ROW; } // TODO if ROWS_PER_CTA does not divice rows, we might get divergence in the // last blocks with syncthreads! // grid stride over rows #pragma unroll 1 for (int row = r; row < rows; row += gridDim.x * ROWS_PER_CTA) { const compute_t mu_r = mu_ptr[row]; const compute_t rs_r = rs_ptr[row]; Vec dw[LDGS], x[LDGS], dx[LDGS]; int col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { dw[it].load_from(dw_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); x[it].load_from(x_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } // local reductions compute_t dy[LDGS * NUM_ELTS]; compute_t y[LDGS * NUM_ELTS]; compute_t mdy_local = 0.f; compute_t mdyy_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < Vec::NUM_ELTS; jt++) { compute_t x_tmp = x[it].data.elt[jt]; compute_t y_tmp = rs_r * (x_tmp - mu_r); compute_t dy_tmp = gamma[it].data.elt[jt] * dw[it].data.elt[jt]; compute_t dw_tmp = dw[it].data.elt[jt]; mdy_local += dy_tmp; mdyy_local += dy_tmp * y_tmp; dy[it * NUM_ELTS + jt] = dy_tmp; y[it * NUM_ELTS + jt] = y_tmp; dwy_sum[it * NUM_ELTS + jt] += dw_tmp * y_tmp; dw_sum[it * NUM_ELTS + jt] += dw_tmp; } } // reduction across row for mdy, mdyy if (WARPS_N == 1) { // no need to go through smem! #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { mdy_local += __shfl_xor_sync(uint32_t(-1), mdy_local, it); mdyy_local += __shfl_xor_sync(uint32_t(-1), mdyy_local, it); } mdy_local *= rn; mdyy_local *= rn; } else { #pragma unroll for (int it = 16; it > 0; it /= 2) { mdy_local += __shfl_down_sync(uint32_t(-1), mdy_local, it); mdyy_local += __shfl_down_sync(uint32_t(-1), mdyy_local, it); } // lane 0 holds the result! if (lane == 0) { mdy_shared[warp_n] = mdy_local; mdyy_shared[warp_n] = mdyy_local; } __syncthreads(); if (warp_n == 0 && lane == 0) { mdy_local = 0.f; mdyy_local = 0.f; for (int it = 0; it < WARPS_N; it++) { mdy_local += mdy_shared[it]; mdyy_local += mdyy_shared[it]; } mdy_shared[0] = mdy_local; mdyy_shared[0] = mdyy_local; } __syncthreads(); mdy_local = mdy_shared[0] * rn; mdyy_local = mdyy_shared[0] * rn; } #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { compute_t dy_tmp = dy[it * NUM_ELTS + jt]; compute_t y_tmp = y[it * NUM_ELTS + jt]; compute_t dx_tmp = compute_t(rs_r) * (dy_tmp - mdyy_local * y_tmp - mdy_local); dx[it].data.elt[jt] = dx_tmp; } } col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { dx[it].store_to(dx_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += Ktraits::THREADS_PER_ROW; } } // end: grid stride loop // Finalize reduction of part dgamma and dbeta for this CTA // by reducing over the rows held across the WARPS_M warps enum { NUM_RES = COLS / Ktraits::THREADS_PER_CTA }; static_assert(NUM_RES * Ktraits::THREADS_PER_CTA == COLS, ""); compute_t *smem_write; smem_write = &smem_[warp_m * COLS + tid_r * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { smem_write[jt] = dw_sum[it * NUM_ELTS + jt]; } smem_write += THREADS_PER_ROW * NUM_ELTS; } __syncthreads(); compute_t cta_dw_sum[NUM_RES]; memset(cta_dw_sum, 0, sizeof(compute_t) * NUM_RES); for (int it = 0; it < ROWS_PER_CTA; it++) { for (int jt = 0; jt < NUM_RES; jt++) { cta_dw_sum[jt] += smem_[it * COLS + tidx + jt * Ktraits::THREADS_PER_CTA]; } } __syncthreads(); smem_write = &smem_[warp_m * COLS + tid_r * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { smem_write[jt] = dwy_sum[it * NUM_ELTS + jt]; } smem_write += THREADS_PER_ROW * NUM_ELTS; } __syncthreads(); compute_t cta_dwy_sum[NUM_RES]; memset(cta_dwy_sum, 0, sizeof(compute_t) * NUM_RES); for (int it = 0; it < ROWS_PER_CTA; it++) { for (int jt = 0; jt < NUM_RES; jt++) { cta_dwy_sum[jt] += smem_[it * COLS + tidx + jt * Ktraits::THREADS_PER_CTA]; } } compute_t *dgamma_part = static_cast(dg_) + bidx * COLS + tidx; for (int jt = 0; jt < NUM_RES; jt++) { *dgamma_part = cta_dwy_sum[jt]; dgamma_part += Ktraits::THREADS_PER_CTA; } compute_t *dbeta_part = static_cast(db_) + bidx * COLS + tidx; for (int jt = 0; jt < NUM_RES; jt++) { *dbeta_part = cta_dw_sum[jt]; dbeta_part += Ktraits::THREADS_PER_CTA; } } template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_bwd_finalize_kernel(void * __restrict__ dg_, void * __restrict__ db_, const void * __restrict__ dg_part_, const void * __restrict__ db_part_, const int rows ){ using Vec = typename Ktraits::Vec; enum { NUM_ELTS = Vec::NUM_ELTS }; using vec_t = typename Ktraits::vec_t; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { WARPS_M = Ktraits::WARPS_M }; enum { WARPS_N = Ktraits::WARPS_N }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { COLS = Ktraits::COLS }; enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum {VEC_COLS = BYTES_PER_ROW / BYTES_PER_LDG}; //dbg static_assert(VEC_COLS == COLS / NUM_ELTS, ""); //static_assert(VEC_COLS == 1024,""); const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_m = warp / Ktraits::WARPS_N; const int warp_n = warp % Ktraits::WARPS_N; const int tid_c = warp_n * THREADS_PER_WARP + lane; const int c =bidx * THREADS_PER_ROW + tid_c; const int r = warp_m; __shared__ compute_t smem_[(WARPS_M - 1) * THREADS_PER_ROW * NUM_ELTS]; //Will probably run this with WARPS_N = 1 and grid = 1024 / (32*4) = 8, or NUM_ELTS=1 and grid = 32 // and WARPS_M = 4 (or 1??) for(int col = c; col < VEC_COLS; col += gridDim.x * THREADS_PER_ROW){ const char* dg_part_ptr = static_cast(dg_part_) + r * BYTES_PER_ROW + col * BYTES_PER_LDG; const char* db_part_ptr = static_cast(db_part_) + r * BYTES_PER_ROW + col * BYTES_PER_LDG; compute_t dg_sum[NUM_ELTS]; compute_t db_sum[NUM_ELTS]; memset(dg_sum, 0, sizeof(compute_t) * NUM_ELTS); memset(db_sum, 0, sizeof(compute_t) * NUM_ELTS); #pragma unroll for(int row = r; row < rows;row += ROWS_PER_CTA){ Vec dg; Vec db; dg.load_from(dg_part_ptr); db.load_from(db_part_ptr); dg_part_ptr += ROWS_PER_CTA * BYTES_PER_ROW; db_part_ptr += ROWS_PER_CTA * BYTES_PER_ROW; #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_sum[jt] += dg.data.elt[jt]; db_sum[jt] += db.data.elt[jt]; } } // Finalize the reduction across rows of the CTA compute_t * smem_write; smem_write = smem_ + (warp_m -1) *THREADS_PER_ROW * NUM_ELTS + tid_c; if (warp_m > 0) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { *smem_write = dg_sum[jt]; smem_write+=THREADS_PER_ROW; } } __syncthreads(); compute_t *smem_read ; smem_read = smem_ + tid_c ; if (warp_m == 0) { #pragma unroll for (int it = 0; it < WARPS_M - 1; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_sum[jt] += *smem_read; smem_read += THREADS_PER_ROW; } } } __syncthreads(); smem_write = smem_ + (warp_m -1) *THREADS_PER_ROW * NUM_ELTS + tid_c; if (warp_m > 0) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { *smem_write = db_sum[jt]; smem_write+=THREADS_PER_ROW; } } __syncthreads(); smem_read = smem_ + tid_c; if (warp_m == 0) { #pragma unroll for (int it = 0; it < WARPS_M - 1; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { db_sum[jt] += *smem_read; smem_read += THREADS_PER_ROW; } } using vout_t = typename Vec_type::Type; union { vout_t raw; out_t elt[NUM_ELTS]; } dg_out, db_out; // out_t dg_out[NUM_ELTS], db_out[NUM_ELTS]; #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_out.elt[jt] = dg_sum[jt]; db_out.elt[jt] = db_sum[jt]; } vout_t *dg_ptr = reinterpret_cast(dg_) + col ; vout_t *db_ptr = reinterpret_cast(db_) + col ; *dg_ptr = dg_out.raw; *db_ptr = db_out.raw; } } } template void launch(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, at::Tensor &dgamma_part, at::Tensor &dbeta_part, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, const int gridx, cudaStream_t stream){ if (cols == 1024) { using Ktraits = Kernel_traits; if (Ktraits::SMEM_BYTES >= 48 * 1024) { AT_CUDA_CHECK(cudaFuncSetAttribute( ln_bwd_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, Ktraits::SMEM_BYTES)); } ln_bwd_kernel <<>>( dx.data_ptr(), dgamma_part.data_ptr(), dbeta_part.data_ptr(), dw.data_ptr(), x.data_ptr(), mu.data_ptr(), rsigma.data_ptr(), gamma.data_ptr(), rows); using Ktraits2 = Kernel_traits; constexpr int grid2 = DIVUP(1024, Ktraits2::THREADS_PER_ROW * Ktraits2::Vec::NUM_ELTS); ln_bwd_finalize_kernel <<>>( dgamma.data_ptr(), dbeta.data_ptr(), dgamma_part.data_ptr(), dbeta_part.data_ptr(), gridx); } else { assert(false && "Not implemented"); } AT_CUDA_CHECK(cudaPeekAtLastError()); } void ln_bwd_cuda(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, cudaStream_t stream) { const auto dtype = x.scalar_type(); const auto props = at::cuda::getCurrentDeviceProperties(); const int smCount = props->multiProcessorCount; // Launch 2 CTAs per SM const int grid = 2 * smCount; //request workspace for two-step reduction. We always reduce in FP32. auto opts = x.options(); auto dbeta_part = torch::empty({grid, cols}, opts.dtype(torch::kFloat32)); auto dgamma_part = torch::empty({grid, cols}, opts.dtype(torch::kFloat32)); if (dtype == torch::kFloat16) { launch(dx, dgamma, dbeta, dgamma_part, dbeta_part, dw, x, mu, rsigma, gamma, rows, cols, grid, stream); } else if (dtype == torch::kFloat32) { launch(dx, dgamma, dbeta, dgamma_part, dbeta_part, dw, x, mu, rsigma, gamma, rows, cols, grid, stream); } else { assert(false && "Not implemented"); } } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/layer_norm/ln_fwd_cuda_kernel.cu ================================================ #include "utils.cuh" #include "ln_kernel_traits.h" #include "ATen/cuda/CUDAContext.h" template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_fwd_kernel( void *__restrict__ y_, void *__restrict__ mu_, void *__restrict__ rsigma_, const void *__restrict__ x_, const void *__restrict__ gamma_, const void *__restrict__ beta_, const float epsilon, int rows) { using Vec = typename Ktraits::Vec; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; enum { NUM_ELTS = Vec::NUM_ELTS }; enum { WARPS_N = Ktraits::WARPS_N }; enum { WARPS_M = Ktraits::WARPS_M }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; static_assert(BYTES_PER_LDG == 16, ""); enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum { LDGS = BYTES_PER_ROW / Ktraits::BYTES_PER_ROW_PER_CTA }; static_assert(LDGS * Ktraits::BYTES_PER_ROW_PER_CTA == BYTES_PER_ROW, ""); const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_n = warp % WARPS_N; const int warp_m = warp / WARPS_N; const int c = warp_n * THREADS_PER_WARP + lane; const int r = bidx * ROWS_PER_CTA + warp_m; const char *x_ptr = static_cast(x_); const char *g_ptr = static_cast(gamma_); const char *b_ptr = static_cast(beta_); char *y_ptr = static_cast(y_); compute_t *mu_ptr = static_cast(mu_); compute_t *rs_ptr = static_cast(rsigma_); Vec gamma[LDGS]; Vec beta[LDGS]; #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { gamma[it].load_from(g_ptr + col * BYTES_PER_LDG); beta[it].load_from(b_ptr + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } constexpr compute_t rn = 1.f / compute_t(Ktraits::COLS); for (int row = r; row < rows; row += gridDim.x * ROWS_PER_CTA) { Vec x[LDGS]; #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { x[it].load_from(x_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } compute_t xf[LDGS * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { xf[it * NUM_ELTS + jt] = compute_t(x[it].data.elt[jt]); } } compute_t mu_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { mu_local += xf[it * NUM_ELTS + jt]; } } #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { mu_local += __shfl_xor_sync(uint32_t(-1), mu_local, it); } mu_local *= rn; if(lane == 0){ mu_ptr[row] = mu_local; } compute_t var_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { compute_t diff = xf[it * NUM_ELTS + jt] - mu_local; var_local += diff * diff; } } #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { var_local += __shfl_xor_sync(uint32_t(-1), var_local, it); } compute_t rsigma = rsqrtf(var_local * rn + epsilon); if(lane == 0){ rs_ptr[row] = rsigma; } #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { base_t tmp = (rsigma * (xf[it * NUM_ELTS + jt] - mu_local)); x[it].data.elt[jt] = gamma[it].data.elt[jt] * tmp + beta[it].data.elt[jt]; } } #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { x[it].store_to(y_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } } } template void launch( at::Tensor & y, // BxSxhidden_size at::Tensor & mu, at::Tensor & rsigma, const at::Tensor & x, // BxSxhidden_size const at::Tensor & gamma, const at::Tensor & beta, const float epsilon, const int rows, const int cols, const int max_gridx, cudaStream_t stream ){ if (cols == 1024) { using Ktraits = Kernel_traits; const int grid = std::min(DIVUP(rows, Ktraits::ROWS_PER_CTA), max_gridx); ln_fwd_kernel<<>>( y.data_ptr(), mu.data_ptr(), rsigma.data_ptr(), x.data_ptr(), gamma.data_ptr(), beta.data_ptr(), epsilon, rows); } else { assert(false && "Not implemented"); } AT_CUDA_CHECK(cudaPeekAtLastError()); } void ln_fwd_cuda( at::Tensor & y, // BxSxhidden_size at::Tensor & mu, at::Tensor & rsigma, const at::Tensor & x, // BxSxhidden_size const at::Tensor & gamma, const at::Tensor & beta, const float epsilon, const int rows, const int cols, cudaStream_t stream ){ const auto dtype = x.scalar_type(); const auto props = at::cuda::getCurrentDeviceProperties(); const int max_gridx = props->maxGridSize[0]; //TODO // - Using dispatch macro costs 1% perf wtf?!?! // - Tune FP32 warps // - Add more sizes if (dtype == torch::kFloat16) { launch(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, max_gridx, stream); } else if (dtype == torch::kFloat32) { launch(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, max_gridx, stream); } else { assert(false && "Not implemented"); } } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/layer_norm/ln_kernel_traits.h ================================================ #pragma once constexpr uint32_t THREADS_PER_WARP = 32; template struct Kernel_traits { enum { WARPS_M = WARPS_M_ }; enum { WARPS_N = WARPS_N_ }; enum { COLS = COLS_ }; enum { BYTES_PER_LDG = BYTES_PER_LDG_ }; using Vec = Vec; using vec_t = typename Vec::vec_t; using base_t = typename Vec::base_t; using packed_t = typename Vec::packed_t; using compute_t = typename Vec::compute_t; using packed_compute_t = typename Vec::packed_compute_t; enum { THREADS_PER_ROW = WARPS_N * THREADS_PER_WARP }; enum { THREADS_PER_CTA = WARPS_M * THREADS_PER_ROW }; enum { ROWS_PER_CTA = WARPS_M }; enum { BYTES_PER_ROW = COLS * sizeof(base_t) }; enum { BYTES_PER_ROW_PER_CTA = THREADS_PER_ROW * BYTES_PER_LDG }; enum {SMEM_BYTES = ROWS_PER_CTA * COLS * sizeof(compute_t)}; }; ================================================ FILE: KoSentenceT5/apex/contrib/csrc/layer_norm/utils.cuh ================================================ #pragma once #include "torch/extension.h" #include // for CUDNN_CHECK #define DIVUP(x, y) (((x) + ((y)-1)) / (y)) #define DISPATCH_FLOAT_AND_HALF(TYPE, NAME, ...) \ [&] { \ const auto &the_type = TYPE; \ /* don't use TYPE again in case it is an expensive or side-effect op */ \ at::ScalarType _st = ::detail::scalar_type(the_type); \ switch (_st) { \ AT_PRIVATE_CASE_TYPE(at::ScalarType::Float, float, __VA_ARGS__) \ AT_PRIVATE_CASE_TYPE(at::ScalarType::Half, at::Half, __VA_ARGS__) \ default: \ AT_ERROR(#NAME, " not implemented for '", toString(_st), "'"); \ } \ }() template struct Vec_type {}; template <> struct Vec_type<16> { using Type = uint4; static __device__ inline Type zero() { return make_uint4(0, 0, 0, 0); } }; template <> struct Vec_type<8> { using Type = uint2; static __device__ inline Type zero() { return make_uint2(0, 0); } }; template <> struct Vec_type<4> { using Type = uint32_t; static __device__ inline Type zero() { return 0; } }; template <> struct Vec_type<2> { using Type = uint16_t; static __device__ inline Type zero() { return 0; } }; template struct TypeInfo { using base_t = T; using packed_t = T; using compute_t = float; using packed_compute_t = float; }; template <> struct TypeInfo { using base_t = half; using packed_t = half2; using compute_t = float; using packed_compute_t = float2; }; template struct Vec { using base_t = typename TypeInfo::base_t; using packed_t = typename TypeInfo::packed_t; using compute_t = typename TypeInfo::compute_t; using packed_compute_t = typename TypeInfo::packed_compute_t; static_assert(Bytes % sizeof(base_t) == 0, ""); static_assert(Bytes % sizeof(packed_t) == 0, ""); enum { BYTES_PER_THREAD = Bytes }; enum { NUM_ELTS = Bytes / sizeof(base_t) }; enum { NUM_PACKED = Bytes / sizeof(packed_t) }; using vec_t = typename Vec_type::Type; using store_t = union { vec_t raw; base_t elt[NUM_ELTS]; packed_t packed[NUM_PACKED]; }; store_t data; __device__ Vec() { data.raw = Vec_type::zero(); } __device__ inline void load_from(const char *ptr) { data.raw = *reinterpret_cast(ptr); } __device__ inline void load_or_zero(const char *ptr, const bool is_valid) { data.raw = is_valid ? *reinterpret_cast(ptr) : Vec_type::zero(); } __device__ inline void store_to(char *ptr) const { *reinterpret_cast(ptr) = data.raw; } __device__ inline void store_valid(char *ptr, const bool is_valid) const { if (is_valid) *reinterpret_cast(ptr) = data.raw; } }; ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/additive_masked_softmax_dropout.cpp ================================================ #include #include #include namespace multihead_attn { namespace fused_softmax { namespace additive_mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const half* pad_mask, float dropout_prob ); torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool is_training, int heads, torch::Tensor const& input, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(input.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Half, "Only BYTE is supported"); } return fwd_cuda( is_training, heads, input, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } torch::Tensor bwd( bool use_mask, int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); // AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, softmax_results, dropout_mask, dropout_prob ); } } // end namespace mask_softmax_dropout } // end namespace fused_softmax } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::fused_softmax::additive_mask_softmax_dropout::fwd, "Self Multihead Attention masked softmax dropout -- Forward."); m.def("backward", &multihead_attn::fused_softmax::additive_mask_softmax_dropout::bwd, "Self Multihead Attention masked softmax dropout -- Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/additive_masked_softmax_dropout_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "softmax.h" #include "dropout.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace fused_softmax { namespace additive_mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const half* pad_mask, float dropout_prob ) { const int attn_batches = input.size(0); const int sequences = attn_batches / heads; const int q_seq_len = input.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = input.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* input_ptr = static_cast(input.data_ptr()); void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { softmax_success = dispatch_additive_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 return { dropout_results, dropout_mask, softmax_results }; } torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ) { const int attn_batches = output_grads.size(0); const int q_seq_len = output_grads.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations // torch::Tensor input_grads = torch::empty_like(output_grads); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); //backward pass is completely in-place return output_grads; } } } } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/dropout.h ================================================ #include #ifdef OLD_GENERATOR #include #else #include #endif #include #include #include const int UNROLL = 4; template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_fused_dropout_kernel(scalar_t const *inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p, std::pair seeds ) { accscalar_t pinv = accscalar_t(1)/p; IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; curandStatePhilox4_32_10_t state; curand_init( seeds.first, idx, seeds.second, &state); IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { float4 rand = curand_uniform4(&state); scalar_t src[UNROLL]; rand.x = rand.x <= p; rand.y = rand.y <= p; rand.z = rand.z <= p; rand.w = rand.w <= p; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = src[ii]*(&rand.x)[ii]*pinv; mask[li] = (uint8_t)(&rand.x)[ii]; } } __syncthreads(); } } template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_dropout_add_kernel(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p, std::pair seeds ) { accscalar_t pinv = accscalar_t(1)/p; IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; curandStatePhilox4_32_10_t state; curand_init( seeds.first, idx, seeds.second, &state); IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { float4 rand = curand_uniform4(&state); scalar_t src[UNROLL]; scalar_t add_src[UNROLL]; rand.x = rand.x <= p; rand.y = rand.y <= p; rand.z = rand.z <= p; rand.w = rand.w <= p; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; add_src[ii] = add_inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { accscalar_t int1 = src[ii] * (&rand.x)[ii] * pinv; outputs[li] = static_cast(static_cast(add_src[ii]) + int1); mask[li] = (uint8_t)(&rand.x)[ii]; } } __syncthreads(); } } template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_add_kernel( scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, IndexType totalElements ) { IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { scalar_t src[UNROLL]; scalar_t add_src[UNROLL]; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; add_src[ii] = add_inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = src[ii] + add_src[ii]; } } __syncthreads(); } } template __global__ void apex_masked_scale_kernel(scalar_t const *inputs, scalar_t *outputs, uint8_t const *mask, IndexType totalElements, accscalar_t scale ) { IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { scalar_t src[UNROLL]; scalar_t msk[UNROLL]; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = static_cast(inputs[li]); msk[ii] = static_cast(mask[li]); } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = static_cast(src[ii]) * scale * static_cast(msk[ii]); } } } } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_fused_dropout_cuda(scalar_t const *inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p) { auto gen = at::cuda::detail::getDefaultCUDAGenerator(); int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); //number of times random will be generated per thread, to offset philox counter in thc random state int64_t counter_offset = ((totalElements - 1)/(block_size*grid.x*UNROLL)+1)*UNROLL; std::pair rng_engine_inputs; { // See Note [Acquire lock when using random generators] #ifdef OLD_GENERATOR std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_engine_inputs(counter_offset); #else std::lock_guard lock(gen.mutex()); rng_engine_inputs = at::check_generator(gen)->philox_engine_inputs(counter_offset); #endif } apex_fused_dropout_kernel<<>>(inputs, outputs, mask, totalElements, p, rng_engine_inputs); THCudaCheck(cudaGetLastError()); } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_dropout_add_cuda(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p) { auto gen = at::cuda::detail::getDefaultCUDAGenerator(); int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); //number of times random will be generated per thread, to offset philox counter in thc random state int64_t counter_offset = ((totalElements - 1)/(block_size*grid.x*UNROLL)+1)*UNROLL; std::pair rng_engine_inputs; { // See Note [Acquire lock when using random generators] #ifdef OLD_GENERATOR std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_engine_inputs(counter_offset); #else std::lock_guard lock(gen.mutex()); rng_engine_inputs = at::check_generator(gen)->philox_engine_inputs(counter_offset); #endif } apex_dropout_add_kernel<<>>(inputs, add_inputs, outputs, mask, totalElements, p, rng_engine_inputs); THCudaCheck(cudaGetLastError()); } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_add_cuda(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, IndexType totalElements ) { int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); apex_add_kernel<<>>(inputs, add_inputs, outputs, totalElements); THCudaCheck(cudaGetLastError()); } template void apex_masked_scale_cuda(scalar_t const *inputs, scalar_t *outputs, uint8_t const *mask, IndexType totalElements, accscalar_t scale ) { int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); apex_masked_scale_kernel<<>>(inputs, outputs, mask, totalElements, scale); THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/encdec_multihead_attn.cpp ================================================ #include #include namespace multihead_attn { namespace encdec { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_q_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_kv_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_q_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_kv_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_q_results, input_lin_kv_results, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace encdec } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::encdec::cublas_gemmex::fwd, "Encdec Multihead Attention Forward."); m.def("backward", &multihead_attn::encdec::cublas_gemmex::bwd, "Encdec Multihead Attention Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_cuda.cu ================================================ #include #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace encdec { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs_q.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_q_results = torch::empty({q_seq_len, sequences, output_lin_q_dim}, act_options); torch::Tensor input_lin_kv_results = torch::empty({k_seq_len, sequences, output_lin_kv_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs_q, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); void* k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); void* v_lin_results_ptr = static_cast(static_cast(input_lin_kv_results.data_ptr()) + head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Q Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_q_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_q_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_kv_dim, batches_kv, embed_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), k_lin_results_ptr, CUDA_R_16F, output_lin_kv_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(q_lin_results_ptr), lead_dim_q, batch_stride_q, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_q_results, input_lin_kv_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_q_grads = torch::empty_like(inputs_q); torch::Tensor input_kv_grads = torch::empty_like(inputs_kv); torch::Tensor input_weight_q_grads = torch::empty_like(input_weights_q); torch::Tensor input_weight_kv_grads = torch::empty_like(input_weights_kv); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_q_output_grads = torch::empty_like(input_lin_q_results); at::Tensor input_lin_kv_output_grads = torch::empty_like(input_lin_kv_results); auto q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); auto v_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()) + head_dim; auto q_lin_grads_ptr = static_cast(input_lin_q_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()); auto v_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()) + head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches_q, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim_kv, batch_stride_kv, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim_q, batch_stride_q, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim_q, batch_stride_q, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Input Linear Q Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, output_lin_q_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Q Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_q_dim, batches_q, static_cast(&alpha), static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_weight_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_kv, output_lin_kv_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_kv_dim, batches_kv, static_cast(&alpha), static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_weight_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_q_grads, input_kv_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace encdec } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add.cpp ================================================ #include #include namespace multihead_attn { namespace encdec_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_q_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_kv_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_mean.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_invvar.dim() == 1, "expected 1D tensor"); AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_add_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_q_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_kv_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_mean.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(lyr_nrm_invvar.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); AT_ASSERTM(dropout_add_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_q_results, input_lin_kv_results, lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, dropout_mask, dropout_add_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace encdec_norm_add } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::encdec_norm_add::cublas_gemmex::fwd, "Encdec Multihead Attention Plus Layer Norm and Residual Add Forward."); m.def("backward", &multihead_attn::encdec_norm_add::cublas_gemmex::bwd, "Encdec Multihead Attention Plus Layer Norm and Residual Add Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace encdec_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int total_tokens_q = batches_q * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs_q.options().requires_grad(false); auto lyr_nrm_options = act_options.dtype(torch::kFloat32); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor lyr_nrm_mean = torch::empty({batches_q}, lyr_nrm_options); torch::Tensor lyr_nrm_invvar = torch::empty({batches_q}, lyr_nrm_options); torch::Tensor lyr_nrm_results = torch::empty_like(inputs_q, act_options); torch::Tensor input_lin_q_results = torch::empty({q_seq_len, sequences, output_lin_q_dim}, act_options); torch::Tensor input_lin_kv_results = torch::empty({k_seq_len, sequences, output_lin_kv_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor output_lin_results = torch::empty_like(inputs_q, act_options); torch::Tensor dropout_add_mask = torch::empty_like(inputs_q, mask_options); torch::Tensor outputs = torch::empty_like(inputs_q, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); void* k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); void* v_lin_results_ptr = static_cast(static_cast(input_lin_kv_results.data_ptr()) + head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Layer Norm HostApplyLayerNorm( static_cast(lyr_nrm_results.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(batches_q), // n1 static_cast(embed_dim), // n2 1.0e-5, static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr())); // Input Linear Q Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_q_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, //static_cast(inputs_q.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_q_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_kv_dim, batches_kv, embed_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), k_lin_results_ptr, CUDA_R_16F, output_lin_kv_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(q_lin_results_ptr), lead_dim_q, batch_stride_q, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()), //static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_results.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // End-of-block Dropout-Add if (is_training) { apex_dropout_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(outputs.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens_q, (1.0f - dropout_prob)); } else { apex_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(outputs.data_ptr()), total_tokens_q); } THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, input_lin_q_results, input_lin_kv_results, softmax_results, dropout_results, dropout_mask, matmul2_results, dropout_add_mask, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int total_tokens_q = batches_q * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_q_grads = torch::empty_like(inputs_q); torch::Tensor input_kv_grads = torch::empty_like(inputs_kv); torch::Tensor lyr_nrm_gamma_grads = torch::empty_like(lyr_nrm_gamma_weights); torch::Tensor lyr_nrm_beta_grads = torch::empty_like(lyr_nrm_beta_weights); torch::Tensor input_weight_q_grads = torch::empty_like(input_weights_q); torch::Tensor input_weight_kv_grads = torch::empty_like(input_weights_kv); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor dropout_add_grads = torch::empty_like(output_grads); at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_q_output_grads = torch::empty_like(input_lin_q_results); at::Tensor input_lin_kv_output_grads = torch::empty_like(input_lin_kv_results); at::Tensor input_lin_q_grads = torch::empty_like(inputs_q); auto q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); auto v_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()) + head_dim; auto q_lin_grads_ptr = static_cast(input_lin_q_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()); auto v_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()) + head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Dropout Add Backward apex_masked_scale_cuda( static_cast(output_grads.data_ptr()), static_cast(dropout_add_grads.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens_q, (1.0 / (1.0 - dropout_prob))); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches_q, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim_kv, batch_stride_kv, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim_q, batch_stride_q, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim_q, batch_stride_q, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Input Linear Q Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, output_lin_q_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), //static_cast(input_q_grads.data_ptr()), static_cast(input_lin_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Q Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_q_dim, batches_q, static_cast(&alpha), static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_weight_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_kv, output_lin_kv_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_kv_dim, batches_kv, static_cast(&alpha), static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_weight_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Fused Layer Norm Bwd with Residual Add HostLayerNormGradient( static_cast(input_lin_q_grads.data_ptr()), static_cast(output_grads.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), inputs_q, static_cast(batches_q), // n1 static_cast(embed_dim), // n2 static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr()), 1.0e-5, static_cast(input_q_grads.data_ptr()), static_cast(lyr_nrm_gamma_grads.data_ptr()), static_cast(lyr_nrm_beta_grads.data_ptr()) ); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_q_grads, input_kv_grads, lyr_nrm_gamma_grads, lyr_nrm_beta_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace encdec_norm_add } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/layer_norm.h ================================================ #include "ATen/ATen.h" #include #include #include template __device__ void cuWelfordOnlineSum( const U curr, U& mu, U& sigma2, U& count) { count = count + U(1); U delta = curr - mu; U lmean = mu + delta / count; mu = lmean; U delta2 = curr - lmean; sigma2 = sigma2 + delta * delta2; } template __device__ void cuChanOnlineSum( const U muB, const U sigma2B, const U countB, U& mu, U& sigma2, U& count) { U delta = muB - mu; U nA = count; U nB = countB; count = count + countB; U nX = count; if (nX > U(0)) { nA = nA / nX; nB = nB / nX; mu = nA*mu + nB*muB; sigma2 = sigma2 + sigma2B + delta * delta * nA * nB * nX; } else { mu = U(0); sigma2 = U(0); } } template __device__ void cuWelfordMuSigma2( const T* __restrict__ vals, const int n1, const int n2, const int i1, U& mu, U& sigma2, U* buf) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensor is contiguous // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. // // compute variance and mean over n2 U count = U(0); mu= U(0); sigma2 = U(0); if (i1 < n1) { // one warp normalizes one n1 index, // synchronization is implicit // initialize with standard Welford algorithm const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; const T* lvals = vals + i1*n2; int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { U curr = static_cast(lvals[l+k]); cuWelfordOnlineSum(curr,mu,sigma2,count); } } for (; l < n2; ++l) { U curr = static_cast(lvals[l]); cuWelfordOnlineSum(curr,mu,sigma2,count); } // intra-warp reductions for (int l = 0; l <= 4; ++l) { int srcLaneB = (threadIdx.x+(1<(muB,sigma2B,countB,mu,sigma2,count); } // threadIdx.x == 0 has correct values for each warp // inter-warp reductions if (blockDim.y > 1) { U* ubuf = (U*)buf; U* ibuf = (U*)(ubuf + blockDim.y); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_y = threadIdx.y - offset; ubuf[2*wrt_y] = mu; ubuf[2*wrt_y+1] = sigma2; ibuf[wrt_y] = count; } __syncthreads(); // lower half merges if (threadIdx.x == 0 && threadIdx.y < offset) { U muB = ubuf[2*threadIdx.y]; U sigma2B = ubuf[2*threadIdx.y+1]; U countB = ibuf[threadIdx.y]; cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); } __syncthreads(); } // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values if (threadIdx.x == 0 && threadIdx.y == 0) { ubuf[0] = mu; ubuf[1] = sigma2; } __syncthreads(); mu = ubuf[0]; sigma2 = ubuf[1]/U(n2); // don't care about final value of count, we know count == n2 } else { mu = WARP_SHFL(mu, 0); sigma2 = WARP_SHFL(sigma2/U(n2), 0); } } } template<> __device__ void cuWelfordMuSigma2( const at::Half* __restrict__ vals, const int n1, const int n2, const int i1, float& mu, float& sigma2, float* buf) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensor is contiguous // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. // // compute variance and mean over n2 float count = 0.0f; mu= float(0); sigma2 = float(0); if (i1 < n1) { // one warp normalizes one n1 index, // synchronization is implicit // initialize with standard Welford algorithm const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; const at::Half* lvals = vals + i1*n2; int l = 8*thrx; if ((((size_t)lvals)&3) != 0) { // 16 bit alignment // first thread consumes first point if (thrx == 0) { float curr = static_cast(lvals[0]); cuWelfordOnlineSum(curr,mu,sigma2,count); } ++l; } // at this point, lvals[l] are 32 bit aligned for all threads. for (; l+7 < n2; l+=8*numx) { for (int k = 0; k < 8; k+=2) { float2 curr = __half22float2(*((__half2*)(lvals+l+k))); cuWelfordOnlineSum(curr.x,mu,sigma2,count); cuWelfordOnlineSum(curr.y,mu,sigma2,count); } } for (; l < n2; ++l) { float curr = static_cast(lvals[l]); cuWelfordOnlineSum(curr,mu,sigma2,count); } // intra-warp reductions for (int l = 0; l <= 4; ++l) { int srcLaneB = (threadIdx.x+(1< 1) { float* ubuf = (float*)buf; float* ibuf = (float*)(ubuf + blockDim.y); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_y = threadIdx.y - offset; ubuf[2*wrt_y] = mu; ubuf[2*wrt_y+1] = sigma2; ibuf[wrt_y] = count; } __syncthreads(); // lower half merges if (threadIdx.x == 0 && threadIdx.y < offset) { float muB = ubuf[2*threadIdx.y]; float sigma2B = ubuf[2*threadIdx.y+1]; float countB = ibuf[threadIdx.y]; cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); } __syncthreads(); } // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values if (threadIdx.x == 0 && threadIdx.y == 0) { ubuf[0] = mu; ubuf[1] = sigma2; } __syncthreads(); mu = ubuf[0]; sigma2 = ubuf[1]/float(n2); // don't care about final value of count, we know count == n2 } else { mu = WARP_SHFL(mu, 0); sigma2 = WARP_SHFL(sigma2/float(n2), 0); } } } template U rsqrt(U v) { return U(1) / sqrt(v); } template<> float rsqrt(float v) { return rsqrtf(v); } template<> double rsqrt(double v) { return rsqrt(v); } namespace { // This is the un-specialized struct. Note that we prevent instantiation of this // struct by putting an undefined symbol in the function body so it won't compile. // template // struct SharedMemory // { // // Ensure that we won't compile any un-specialized types // __device__ T *getPointer() // { // extern __device__ void error(void); // error(); // return NULL; // } // }; // https://github.com/NVIDIA/apex/issues/246 template struct SharedMemory; template <> struct SharedMemory { __device__ float *getPointer() { extern __shared__ float s_float[]; return s_float; } }; template <> struct SharedMemory { __device__ double *getPointer() { extern __shared__ double s_double[]; return s_double; } }; } template __global__ void cuApplyLayerNorm( T* __restrict__ output_vals, U* __restrict__ mean, U* __restrict__ invvar, const T* __restrict__ vals, const int n1, const int n2, const U epsilon, const T* __restrict__ gamma, const T* __restrict__ beta ) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensors are contiguous // for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { SharedMemory shared; U* buf = shared.getPointer(); U mu,sigma2; cuWelfordMuSigma2(vals,n1,n2,i1,mu,sigma2,buf); const T* lvals = vals + i1*n2; T* ovals = output_vals + i1*n2; U c_invvar = rsqrt(sigma2 + epsilon); const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; if (gamma != NULL && beta != NULL) { for (int i = thrx; i < n2; i+=numx) { U curr = static_cast(lvals[i]); ovals[i] = gamma[i] * static_cast(c_invvar * (curr - mu)) + beta[i]; } } else { for (int i = thrx; i < n2; i+=numx) { U curr = static_cast(lvals[i]); ovals[i] = static_cast(c_invvar * (curr - mu)); } } if (threadIdx.x == 0 && threadIdx.y == 0) { mean[i1] = mu; invvar[i1] = c_invvar; } } } template __device__ void cuLoadWriteStridedInputs( const int i1_block, const int thr_load_row_off, const int thr_load_col_off, const int i2_off, const int row_stride, U* warp_buf1, U* warp_buf2, const T* input, const T* dout, const int i1_end, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar ) { int i1 = i1_block+thr_load_row_off; if (i1 < i1_end) { U curr_mean = mean[i1]; U curr_invvar = invvar[i1]; for (int k = 0; k < blockDim.y; ++k) { int i2 = i2_off + k; int load_idx = i1*n2+i2; int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; if (i2(input[load_idx]); U curr_dout = static_cast(dout[load_idx]); warp_buf1[write_idx] = curr_dout; warp_buf2[write_idx] = curr_dout * (curr_input - curr_mean) * curr_invvar; } else { warp_buf1[write_idx] = U(0); warp_buf2[write_idx] = U(0); } } } else { for (int k = 0; k < blockDim.y; ++k) { int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; warp_buf1[write_idx] = U(0); warp_buf2[write_idx] = U(0); } } } template __device__ void cuLoadAddStridedInputs( const int i1_block, const int thr_load_row_off, const int thr_load_col_off, const int i2_off, const int row_stride, U* warp_buf1, U* warp_buf2, const T* input, const T* dout, const int i1_end, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar ) { int i1 = i1_block+thr_load_row_off; if (i1 < i1_end) { U curr_mean = mean[i1]; U curr_invvar = invvar[i1]; for (int k = 0; k < blockDim.y; ++k) { int i2 = i2_off + k; int load_idx = i1*n2+i2; int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; if (i2(input[load_idx]); U curr_dout = static_cast(dout[load_idx]); warp_buf1[write_idx] += curr_dout; warp_buf2[write_idx] += curr_dout * (curr_input - curr_mean) * curr_invvar; } } } } template __global__ void cuComputePartGradGammaBeta( const T* __restrict__ dout, const T* __restrict__ input, const int n1, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar, U epsilon, U* part_grad_gamma, U* part_grad_beta) { const int numsegs_n1 = (n1+blockDim.y*blockDim.y-1) / (blockDim.y*blockDim.y); const int segs_per_block = (numsegs_n1 + gridDim.y - 1) / gridDim.y; const int i1_beg = blockIdx.y * segs_per_block * blockDim.y*blockDim.y; const int i1_beg_plus_one = (blockIdx.y+1) * segs_per_block * blockDim.y*blockDim.y; const int i1_end = i1_beg_plus_one < n1 ? i1_beg_plus_one : n1; const int row_stride = blockDim.x+1; const int thr_load_col_off = (threadIdx.x*blockDim.y)&(blockDim.x-1); const int thr_load_row_off = (threadIdx.x*blockDim.y)/blockDim.x + threadIdx.y*blockDim.y; const int i2_off = blockIdx.x * blockDim.x + thr_load_col_off; SharedMemory shared; U* buf = shared.getPointer(); // buf has at least blockDim.x * blockDim.y * blockDim.y + (blockDim.y - 1)*(blockDim.x/blockDim.y) elements U* warp_buf1 = (U*)buf; U* warp_buf2 = warp_buf1 + blockDim.y * blockDim.y * row_stride; // compute partial sums from strided inputs // do this to increase number of loads in flight cuLoadWriteStridedInputs(i1_beg,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); for (int i1_block = i1_beg+blockDim.y*blockDim.y; i1_block < i1_end; i1_block+=blockDim.y*blockDim.y) { cuLoadAddStridedInputs(i1_block,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); } __syncthreads(); // inter-warp reductions // sum within each warp U acc1 = U(0); U acc2 = U(0); for (int k = 0; k < blockDim.y; ++k) { int row1 = threadIdx.y + k*blockDim.y; int idx1 = row1*row_stride + threadIdx.x; acc1 += warp_buf1[idx1]; acc2 += warp_buf2[idx1]; } warp_buf1[threadIdx.y*row_stride+threadIdx.x] = acc1; warp_buf2[threadIdx.y*row_stride+threadIdx.x] = acc2; __syncthreads(); // sum all warps for (int offset = blockDim.y/2; offset > 1; offset /= 2) { if (threadIdx.y < offset) { int row1 = threadIdx.y; int row2 = threadIdx.y + offset; int idx1 = row1*row_stride + threadIdx.x; int idx2 = row2*row_stride + threadIdx.x; warp_buf1[idx1] += warp_buf1[idx2]; warp_buf2[idx1] += warp_buf2[idx2]; } __syncthreads(); } int i2 = blockIdx.x * blockDim.x + threadIdx.x; if (threadIdx.y == 0 && i2 < n2) { int row1 = threadIdx.y; int row2 = threadIdx.y + 1; int idx1 = row1*row_stride + threadIdx.x; int idx2 = row2*row_stride + threadIdx.x; part_grad_beta[blockIdx.y*n2+i2] = warp_buf1[idx1] + warp_buf1[idx2]; part_grad_gamma[blockIdx.y*n2+i2] = warp_buf2[idx1] + warp_buf2[idx2]; } } template __global__ void cuComputeGradGammaBeta( const U* part_grad_gamma, const U* part_grad_beta, const int part_size, const int n1, const int n2, T* grad_gamma, T* grad_beta) { // sum partial gradients for gamma and beta SharedMemory shared; U* buf = shared.getPointer(); int i2 = blockIdx.x * blockDim.x + threadIdx.x; if (i2 < n2) { // each warp does sequential reductions until reduced part_size is num_warps int num_warp_reductions = part_size / blockDim.y; U sum_gamma = U(0); U sum_beta = U(0); const U* part_grad_gamma_ptr = part_grad_gamma + threadIdx.y * num_warp_reductions * n2 + i2; const U* part_grad_beta_ptr = part_grad_beta + threadIdx.y * num_warp_reductions * n2 + i2; for (int warp_offset = 0; warp_offset < num_warp_reductions; ++warp_offset) { sum_gamma += part_grad_gamma_ptr[warp_offset*n2]; sum_beta += part_grad_beta_ptr[warp_offset*n2]; } // inter-warp reductions const int nbsize3 = blockDim.x * blockDim.y / 2; for (int offset = blockDim.y/2; offset >= 1; offset /= 2) { // top half write to shared memory if (threadIdx.y >= offset && threadIdx.y < 2*offset) { const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x; buf[write_idx] = sum_gamma; buf[write_idx+nbsize3] = sum_beta; } __syncthreads(); // bottom half sums if (threadIdx.y < offset) { const int read_idx = threadIdx.y * blockDim.x + threadIdx.x; sum_gamma += buf[read_idx]; sum_beta += buf[read_idx+nbsize3]; } __syncthreads(); } // write out fully summed gradients if (threadIdx.y == 0) { grad_gamma[i2] = sum_gamma; grad_beta[i2] = sum_beta; } } } template __global__ void cuComputeGradInput( const T* __restrict__ dout, const T* __restrict__ dout_resid, const T* __restrict__ input, const int n1, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar, U epsilon, const T* gamma, T* grad_input) { for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { U sum_loss1 = U(0); U sum_loss2 = U(0); const U c_mean = mean[i1]; const U c_invvar = invvar[i1]; const T* k_input = input + i1*n2; const T* k_dout = dout + i1*n2; const T* k_dout_resid = dout_resid + i1*n2; const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; if (gamma != NULL) { int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { const U c_h = static_cast(k_input[l+k]); const U c_loss = static_cast(k_dout[l+k]); sum_loss1 += c_loss * static_cast(gamma[l+k]); sum_loss2 += c_loss * static_cast(gamma[l+k]) * (c_h - c_mean) * c_invvar; } } for (; l < n2; ++l) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); sum_loss1 += c_loss * static_cast(gamma[l]); sum_loss2 += c_loss * static_cast(gamma[l]) * (c_h - c_mean) * c_invvar; } } else { int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { const U c_h = static_cast(k_input[l+k]); const U c_loss = static_cast(k_dout[l+k]); sum_loss1 += c_loss; sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; } } for (; l < n2; ++l) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); sum_loss1 += c_loss; sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; } } // intra-warp reductions for (int mask = blockDim.x/2; mask > 0; mask /= 2) { sum_loss1 += WARP_SHFL_XOR(sum_loss1, mask); sum_loss2 += WARP_SHFL_XOR(sum_loss2, mask); } // inter-warp reductions if (blockDim.y > 1) { SharedMemory shared; U* buf = shared.getPointer(); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_i = (threadIdx.y - offset) * blockDim.x + threadIdx.x; buf[2*wrt_i] = sum_loss1; buf[2*wrt_i+1] = sum_loss2; } __syncthreads(); // lower half merges if (threadIdx.y < offset) { const int read_i = threadIdx.y * blockDim.x + threadIdx.x; sum_loss1 += buf[2*read_i]; sum_loss2 += buf[2*read_i+1]; } __syncthreads(); } if (threadIdx.y == 0) { buf[2*threadIdx.x] = sum_loss1; buf[2*threadIdx.x+1] = sum_loss2; } __syncthreads(); if (threadIdx.y !=0) { sum_loss1 = buf[2*threadIdx.x]; sum_loss2 = buf[2*threadIdx.x+1]; } } // all threads now have the two sums over l U fH = (U)n2; U term1 = (U(1) / fH) * c_invvar; T* k_grad_input = grad_input + i1*n2; if (gamma != NULL) { for (int l = thrx; l < n2; l+=numx) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); const T c_resid= static_cast(k_dout_resid[l]); U f_grad_input = fH * c_loss * static_cast(gamma[l]); f_grad_input -= sum_loss1; f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; f_grad_input *= term1; k_grad_input[l] = static_cast(f_grad_input)+c_resid; } } else { for (int l = thrx; l < n2; l+=numx) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); const T c_resid= static_cast(k_dout_resid[l]); U f_grad_input = fH * c_loss; f_grad_input -= sum_loss1; f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; f_grad_input *= term1; k_grad_input[l] = static_cast(f_grad_input)+c_resid; } } } } template void HostApplyLayerNorm( T* output, U* mean, U* invvar, const T* input, int n1, int n2, double epsilon, const T* gamma, const T* beta ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); const dim3 threads(32,4,1); const uint64_t maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; const dim3 blocks(1, std::min((uint64_t)n1, maxGridY), 1); int nshared = threads.y > 1 ? threads.y*sizeof(U)+(threads.y/2)*sizeof(U) : 0; cuApplyLayerNorm<<>>( output, mean, invvar, input, n1,n2, U(epsilon), gamma,beta); } template void HostLayerNormGradient( const T* dout, const T* dout_resid, const U* mean, const U* invvar, const at::Tensor& input, int n1, int n2, const T* gamma, const T* beta, double epsilon, T* grad_input, T* grad_gamma, T* grad_beta ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); if (gamma != NULL && beta != NULL) { // compute grad_gamma(j) and grad_beta(j) const int part_size = 16; const dim3 threads2(32,4,1); const dim3 blocks2((n2+threads2.x-1)/threads2.x,part_size,1); const int nshared2_a = 2 * sizeof(U) * threads2.y * threads2.y * (threads2.x + 1); const int nshared2_b = threads2.x * threads2.y * sizeof(U); const int nshared2 = nshared2_a > nshared2_b ? nshared2_a : nshared2_b; at::Tensor part_grad_gamma = at::empty({part_size,n2}, input.options().dtype(input.scalar_type()==at::ScalarType::Half ? at::ScalarType::Float : input.scalar_type())); at::Tensor part_grad_beta = at::empty_like(part_grad_gamma); cuComputePartGradGammaBeta<<>>( dout, static_cast(input.data_ptr()), n1,n2, mean, invvar, U(epsilon), static_cast(part_grad_gamma.data_ptr()), static_cast(part_grad_beta.data_ptr())); const dim3 threads3(32,8,1); const dim3 blocks3((n2+threads2.x-1)/threads2.x,1,1); const int nshared3 = threads3.x * threads3.y * sizeof(U); cuComputeGradGammaBeta<<>>( static_cast(part_grad_gamma.data_ptr()), static_cast(part_grad_beta.data_ptr()), part_size, n1,n2, grad_gamma, grad_beta); } // compute grad_input const uint64_t maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; const dim3 blocks1(1, std::min((uint64_t)n1, maxGridY), 1); const dim3 threads1(32,4,1); int nshared = threads1.y > 1 ? threads1.y*threads1.x*sizeof(U) : 0; cuComputeGradInput<<>>( dout, dout_resid, static_cast(input.data_ptr()), n1,n2, mean, invvar, U(epsilon), gamma, grad_input); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/masked_softmax_dropout.cpp ================================================ #include #include namespace multihead_attn { namespace fused_softmax { namespace mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const uint8_t* pad_mask, float dropout_prob ); torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, const uint8_t *padding_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool is_training, int heads, torch::Tensor const& input, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(input.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( is_training, heads, input, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } torch::Tensor bwd( bool use_mask, int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, torch::Tensor const& padding_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); // AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, softmax_results, dropout_mask, use_mask ? static_cast(padding_mask.data_ptr()) : nullptr, dropout_prob ); } } // end namespace mask_softmax_dropout } // end namespace fused_softmax } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::fused_softmax::mask_softmax_dropout::fwd, "Self Multihead Attention masked softmax dropout -- Forward."); m.def("backward", &multihead_attn::fused_softmax::mask_softmax_dropout::bwd, "Self Multihead Attention masked softmax dropout -- Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/masked_softmax_dropout_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "softmax.h" #include "dropout.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace fused_softmax { namespace mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const uint8_t* pad_mask, float dropout_prob ) { const int attn_batches = input.size(0); const int sequences = attn_batches / heads; const int q_seq_len = input.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = input.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* input_ptr = static_cast(input.data_ptr()); void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 return { dropout_results, dropout_mask, softmax_results }; } torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, const uint8_t *padding_mask, float dropout_prob ) { const int attn_batches = output_grads.size(0); const int q_seq_len = output_grads.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations // torch::Tensor input_grads = torch::empty_like(output_grads); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad if (padding_mask == nullptr) { dispatch_masked_scale_softmax_backward_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); } else{ dispatch_masked_scale_softmax_backward_masked_out_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), static_cast(padding_mask), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, heads, stream); } //backward pass is completely in-place return output_grads; } } } } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/philox.h ================================================ #pragma once //Philox CUDA. class Philox { public: __device__ inline Philox(unsigned long long seed, unsigned long long subsequence, unsigned long long offset) { key.x = (unsigned int)seed; key.y = (unsigned int)(seed >> 32); counter = make_uint4(0, 0, 0, 0); counter.z = (unsigned int)(subsequence); counter.w = (unsigned int)(subsequence >> 32); STATE = 0; incr_n(offset / 4); } __device__ inline uint4 operator()() { if(STATE == 0) { uint4 counter_ = counter; uint2 key_ = key; //7-round philox for(int i = 0; i < 6; i++) { counter_ = single_round(counter_, key_); key_.x += (kPhilox10A); key_.y += (kPhilox10B); } output = single_round(counter_, key_); incr(); } //return a float4 directly //unsigned long ret; //switch(STATE) { // case 0: ret = output.x; break; // case 1: ret = output.y; break; // case 2: ret = output.z; break; // case 3: ret = output.w; break; //} //STATE = (STATE + 1) % 4; return output; } private: uint4 counter; uint4 output; uint2 key; unsigned int STATE; __device__ inline void incr_n(unsigned long long n) { unsigned int nlo = (unsigned int)(n); unsigned int nhi = (unsigned int)(n >> 32); counter.x += nlo; if (counter.x < nlo) nhi++; counter.y += nhi; if (nhi <= counter.y) return; if (++counter.z) return; ++counter.w; } __device__ inline void incr() { if (++counter.x) return; if (++counter.y) return; if (++counter.z) return; ++counter.w; } __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, unsigned int *result_high) { *result_high = __umulhi(a, b); return a*b; } __device__ inline uint4 single_round(uint4 ctr, uint2 key) { unsigned int hi0; unsigned int hi1; unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; return ret; } static const unsigned long kPhilox10A = 0x9E3779B9; static const unsigned long kPhilox10B = 0xBB67AE85; static const unsigned long kPhiloxSA = 0xD2511F53; static const unsigned long kPhiloxSB = 0xCD9E8D57; }; // Inverse of 2^32. #define M_RAN_INVM32 2.3283064e-10f __device__ __inline__ float4 uniform4(uint4 x) { return make_float4(x.x * M_RAN_INVM32, x.y * M_RAN_INVM32, x.z * M_RAN_INVM32,x.w * M_RAN_INVM32); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn.cpp ================================================ #include #include namespace multihead_attn { namespace self { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self::cublas_gemmex::fwd, "Self Multihead Attention Forward."); m.def("backward", &multihead_attn::self::cublas_gemmex::bwd, "Self Multihead Attention Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias.cpp ================================================ #include #include namespace multihead_attn { namespace self_bias { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, //torch::Tensor const& input_biases, //torch::Tensor const& output_biases, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_bias::cublas_gemmex::fwd, "Self Multihead Attention with Bias -- Forward."); m.def("backward", &multihead_attn::self_bias::cublas_gemmex::bwd, "Self Multihead Attention with Bias -- Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_additive_mask.cpp ================================================ #include #include #include namespace multihead_attn { namespace self_bias_additive_mask { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const half* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, // torch::Tensor const& softmax_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, //torch::Tensor const& input_biases, //torch::Tensor const& output_biases, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(use_mask , "no mask is not supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Half, "Only Half is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, bmm1_results, pad_mask, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_bias_additive_mask::cublas_gemmex::fwd, "Self Multihead Attention with Bias -- Forward."); m.def("backward", &multihead_attn::self_bias_additive_mask::cublas_gemmex::bwd, "Self Multihead Attention with Bias -- Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_additive_mask_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_bias_additive_mask { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const half* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta_zero = 0.0; const float beta_one = 1.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor bmm1_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* bmm1_results_ptr = static_cast(bmm1_results.data_ptr()); void* dropout_results_ptr = static_cast(dropout_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd input_lin_results.copy_(input_biases); THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta_zero, static_cast(bmm1_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (is_training) { softmax_success = dispatch_additive_masked_softmax_dropout( reinterpret_cast(dropout_results_ptr), (is_training) ? reinterpret_cast(dropout_mask.data_ptr()) : nullptr, reinterpret_cast(bmm1_results_ptr), pad_mask, attn_batches*q_seq_len*q_seq_len, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences, 1.0f-dropout_prob, stream); } else { softmax_success = dispatch_additive_masked_softmax( reinterpret_cast(dropout_results_ptr),//this is actually softmax results, but making it consistent for the next function reinterpret_cast(bmm1_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta_zero, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); outputs.copy_(output_biases); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, bmm1_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto output_bias_grads = output_grads.view({-1, embed_dim}) .sum(0, false); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_recompute( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(bmm1_results.data_ptr()), reinterpret_cast(pad_mask.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len/sequences, attn_batches*q_seq_len, stream); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(input_lin_output_grads.data_ptr()), //static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto input_bias_grads = input_lin_output_grads.view({-1, output_lin_dim}).sum(0, false); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads, input_bias_grads, output_bias_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_bias { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta_zero = 0.0; const float beta_one = 1.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd input_lin_results.copy_(input_biases); THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta_zero, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta_zero, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); outputs.copy_(output_biases); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto output_bias_grads = output_grads.view({-1, embed_dim}) .sum(0, false); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_stream( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(input_lin_output_grads.data_ptr()), //static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto input_bias_grads = input_lin_output_grads.view({-1, output_lin_dim}).sum(0, false); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads, input_bias_grads, output_bias_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add.cpp ================================================ #include #include namespace multihead_attn { namespace self_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_mean.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_invvar.dim() == 1, "expected 1D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_add_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_mean.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(lyr_nrm_invvar.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); AT_ASSERTM(dropout_add_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda(heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, dropout_mask, dropout_add_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self_norm_add } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_norm_add::cublas_gemmex::fwd, "Self Multihead Attention Plus Layer Norm and Residual Add Forward."); m.def("backward", &multihead_attn::self_norm_add::cublas_gemmex::bwd, "Self Multihead Attention Plus Layer Norm and Residual Add Backward."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int total_tokens = batches * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto lyr_nrm_options = act_options.dtype(torch::kFloat32); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor lyr_nrm_mean = torch::empty({batches}, lyr_nrm_options); torch::Tensor lyr_nrm_invvar = torch::empty({batches}, lyr_nrm_options); torch::Tensor lyr_nrm_results = torch::empty_like(inputs, act_options); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor output_lin_results= torch::empty_like(inputs, act_options); torch::Tensor dropout_add_mask = torch::empty_like(inputs, mask_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Layer Norm HostApplyLayerNorm( static_cast(lyr_nrm_results.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), static_cast(inputs.data_ptr()), static_cast(batches), // n1 static_cast(embed_dim), // n2 1.0e-5, static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr())); // Input Linear Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, //static_cast(inputs.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , //static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_results.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // End-of-block Dropout-Add if (is_training) { apex_dropout_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs.data_ptr()), static_cast(outputs.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens, (1.0f - dropout_prob)); } else { apex_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs.data_ptr()), static_cast(outputs.data_ptr()), total_tokens); } THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, dropout_add_mask, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int total_tokens = batches * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor lyr_nrm_gamma_grads = torch::empty_like(lyr_nrm_gamma_weights); torch::Tensor lyr_nrm_beta_grads = torch::empty_like(lyr_nrm_beta_weights); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations torch::Tensor dropout_add_grads = torch::empty_like(output_grads); torch::Tensor output_lin_grads = torch::empty_like(matmul2_results); torch::Tensor matmul2_grads = torch::empty_like(dropout_results); torch::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); torch::Tensor input_lin_grads = torch::empty_like(inputs); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Dropout Add Backward apex_masked_scale_cuda( static_cast(output_grads.data_ptr()), static_cast(dropout_add_grads.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens, (1.0 / (1.0 - dropout_prob))); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), //static_cast(input_grads.data_ptr()), static_cast(input_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), //static_cast(inputs.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Fused Layer Norm Bwd with Residual Add HostLayerNormGradient( static_cast(input_lin_grads.data_ptr()), static_cast(output_grads.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), inputs, static_cast(batches), // n1 static_cast(embed_dim), // n2 static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr()), 1.0e-5, static_cast(input_grads.data_ptr()), static_cast(lyr_nrm_gamma_grads.data_ptr()), static_cast(lyr_nrm_beta_grads.data_ptr()) ); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, lyr_nrm_gamma_grads, lyr_nrm_beta_grads, input_weight_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace self_norm_add } // end namespace multihead_attn ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/softmax.h ================================================ #pragma once #include #include #include #include "philox.h" #include #include #include #include #include #include namespace { template __device__ __inline__ void copy_vector(Datatype *dst, const Datatype *src); template <> __device__ __inline__ void copy_vector<__half, 1>(__half *dst, const __half *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector(float *dst, const float *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector<__half, 4>(__half *dst, const __half *src) { *((float2*) dst) = *((float2*) src); } template <> __device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) {*((half2*) dst) = *((half2*) src); } template __device__ __inline__ void apply_mask(Datatype *dst, Datatype value, const uint8_t *src); template <> __device__ __inline__ void apply_mask<__half, 1>(__half *dst, __half value, const uint8_t *src) { if (*src == 1) { *dst = value; } } template __device__ __inline__ void apply_additive_mask(Datatype *dst, const Datatype *additive_mask); template <> __device__ __inline__ void apply_additive_mask<__half, 1>(__half *dst, const __half *additive_mask) { *dst += *additive_mask; } template <> __device__ __inline__ void apply_additive_mask<__half, 4>(__half *dst, const __half *additive_mask) { *dst += *additive_mask; *(dst+1) += *(additive_mask+1); *(dst+2) += *(additive_mask+2); *(dst+3) += *(additive_mask+3);} } // namespace anonymous //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp Softmax forward //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void softmax_warp_forward(input_t *dst, const output_t *src, int batch_size, int stride, int element_count) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; src += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; dst += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { copy_vector(&elements_input[i][it], src + i * element_count + it * WARP_SIZE); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using softmax_forward_func = void(*)(input_t *dst, const output_t *src, int batch_size, int stride, int element_count); template bool warp_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &softmax_warp_forward; break; case 1: // 2 kernel = &softmax_warp_forward; break; case 2: // 4 kernel = &softmax_warp_forward; break; case 3: // 8 kernel = &softmax_warp_forward; break; case 4: // 16 kernel = &softmax_warp_forward; break; case 5: // 32 kernel = &softmax_warp_forward; break; case 6: // 64 kernel = &softmax_warp_forward; break; case 7: // 128 kernel = &softmax_warp_forward; break; case 8: // 256 kernel = &softmax_warp_forward; break; case 9: // 512 kernel = &softmax_warp_forward; break; case 10: // 1024 kernel = &softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_softmax(output_t *dst, const input_t *src, int softmax_elements, int softmax_elements_stride, int batch_count) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template __global__ void additive_masked_softmax_dropout_warp_forward_vec4(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p) { assert(ELEMENTS_PER_LDG_STG==4); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; int tid = blockIdx.x * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; acc_t pinv = acc_t(1)/p; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; //vectorize if element_count is multiple of 4, else don't vectorize input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; dropout_mask += thread_offset; // load data from global memory for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const half* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); //(__half)-std::numeric_limits::infinity() } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } auto seeds = at::cuda::philox::unpack(philox_args); Philox ph(std::get<0>(seeds), tid, std::get<1>(seeds)); uint8_t rands[WARP_BATCH][WARP_ITERATIONS]; float4 rand_num; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it+=ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { rand_num = uniform4(ph()); rands[i][it] = (rand_num.x <= p) > 0.5; rands[i][it+1] = (rand_num.y <= p) > 0.5; rands[i][it+2] = (rand_num.z <= p) > 0.5; rands[i][it+3] = (rand_num.w <= p) > 0.5; copy_vector(dropout_mask + i * element_count + it * WARP_SIZE, &rands[i][it]); } } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { output_t out[ELEMENTS_PER_LDG_STG]; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = rands[i][it+element] * (pinv * (elements[i][it + element] / sum[i])); } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } template __global__ void additive_masked_softmax_dropout_warp_forward(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; int tid = blockIdx.x * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; acc_t pinv = acc_t(1)/p; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; //vectorize if element_count is multiple of 4, else don't vectorize input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; int thread_offset = first_batch * stride + local_idx; src += thread_offset; dst += thread_offset; dropout_mask += thread_offset; // load data from global memory for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + local_idx; const half* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += 1) { int element_index = local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < 1;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } curandStatePhilox4_32_10_t state; auto seeds = at::cuda::philox::unpack(philox_args); curand_init( std::get<0>(seeds), tid, std::get<1>(seeds), &state); // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += 1) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { output_t out[1]; acc_t softmax_out[1]; uint8_t dropout_mask_temp[1]; //generate a vector of random numbers here float rand = curand_uniform(&state); float *rand_ptr = (float*)(&rand); #pragma unroll for (int element = 0;element < 1;++element) { softmax_out[element] = (elements[i][it + element] / sum[i]); rand_ptr[element] = rand_ptr[element] <= p; out[element] = rand_ptr[element] * pinv * softmax_out[element]; dropout_mask_temp[element] = rand_ptr[element] > 0.5; // just to distinguish 0.0f and 1.0f } copy_vector(dst + i * element_count + it * WARP_SIZE, out); copy_vector(dropout_mask + i * element_count + it * WARP_SIZE, dropout_mask_temp); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using additive_masked_softmax_dropout_forward_func = void(*)(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p); template bool warp_additive_masked_softmax_dropout_kernel(int element_count, int log2_elements, int &warp_size, int &batches_per_warp, additive_masked_softmax_dropout_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; bool flag_vec4 = (element_count % 4 == 0); switch (log2_elements) { case 0: // 1 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 1: // 2 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 2: // 4 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 3: // 8 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 4: // 16 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 5: // 32 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 6: // 64 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 7: // 128 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 8: // 256 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 9: // 512 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 10: // 1024 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 11: // 2048 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; default: return false; } return true; } template bool dispatch_additive_masked_softmax_dropout(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int totalElements, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride, float p, cudaStream_t streamid)// p is the probability to keep, not drop { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 2048) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_dropout_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_dropout_kernel(softmax_elements, log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; c10::optional gen_; auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); int64_t counter_offset = (totalElements/(blocks*threads_per_block)+1); at::PhiloxCudaState rng_engine_inputs; { std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_cuda_state(counter_offset); } // compute launch size dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, dropout_mask, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride, rng_engine_inputs, p); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void additive_masked_softmax_warp_forward(input_t *dst, const output_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const half* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); //apply_mask(&elements_input[i][it], // (__half)-std::numeric_limits::infinity(), // curr_mask + itr_jmp); elements_input[i][it] += *(curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using additive_masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const half *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_additive_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, additive_masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &additive_masked_softmax_warp_forward; break; case 1: // 2 kernel = &additive_masked_softmax_warp_forward; break; case 2: // 4 kernel = &additive_masked_softmax_warp_forward; break; case 3: // 8 kernel = &additive_masked_softmax_warp_forward; break; case 4: // 16 kernel = &additive_masked_softmax_warp_forward; break; case 5: // 32 kernel = &additive_masked_softmax_warp_forward; break; case 6: // 64 kernel = &additive_masked_softmax_warp_forward; break; case 7: // 128 kernel = &additive_masked_softmax_warp_forward; break; case 8: // 256 kernel = &additive_masked_softmax_warp_forward; break; case 9: // 512 kernel = &additive_masked_softmax_warp_forward; break; case 10: // 1024 kernel = &additive_masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_additive_masked_softmax(output_t *dst, const input_t *src, const input_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } template bool dispatch_additive_masked_softmax_stream(output_t *dst, const input_t *src, const input_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void masked_softmax_warp_forward(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_mask(&elements_input[i][it], (__half)-std::numeric_limits::infinity(), curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &masked_softmax_warp_forward; break; case 1: // 2 kernel = &masked_softmax_warp_forward; break; case 2: // 4 kernel = &masked_softmax_warp_forward; break; case 3: // 8 kernel = &masked_softmax_warp_forward; break; case 4: // 16 kernel = &masked_softmax_warp_forward; break; case 5: // 32 kernel = &masked_softmax_warp_forward; break; case 6: // 64 kernel = &masked_softmax_warp_forward; break; case 7: // 128 kernel = &masked_softmax_warp_forward; break; case 8: // 256 kernel = &masked_softmax_warp_forward; break; case 9: // 512 kernel = &masked_softmax_warp_forward; break; case 10: // 1024 kernel = &masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_masked_softmax(output_t *dst, const input_t *src, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void time_masked_softmax_warp_forward(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int mod_seq_len) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) % mod_seq_len) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_mask(&elements_input[i][it], (__half)-std::numeric_limits::infinity(), curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using time_masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int mod_seq_len); template bool warp_time_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, time_masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &time_masked_softmax_warp_forward; break; case 1: // 2 kernel = &time_masked_softmax_warp_forward; break; case 2: // 4 kernel = &time_masked_softmax_warp_forward; break; case 3: // 8 kernel = &time_masked_softmax_warp_forward; break; case 4: // 16 kernel = &time_masked_softmax_warp_forward; break; case 5: // 32 kernel = &time_masked_softmax_warp_forward; break; case 6: // 64 kernel = &time_masked_softmax_warp_forward; break; case 7: // 128 kernel = &time_masked_softmax_warp_forward; break; case 8: // 256 kernel = &time_masked_softmax_warp_forward; break; case 9: // 512 kernel = &time_masked_softmax_warp_forward; break; case 10: // 1024 kernel = &time_masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_time_masked_softmax(output_t *dst, const input_t *src, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int mod_seq_len) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; time_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_time_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, mod_seq_len); return true; } return false; } int log2_ceil_native(int value) { int log2_value = 0; while ((1 << log2_value) < value) ++log2_value; return log2_value; } template __device__ __forceinline__ T WARP_SHFL_XOR_NATIVE(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) { #if CUDA_VERSION >= 9000 return __shfl_xor_sync(mask, value, laneMask, width); #else return __shfl_xor(value, laneMask, width); #endif } template __device__ __forceinline__ void warp_reduce_sum(acc_t* sum) { #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { acc_t b = WARP_SHFL_XOR_NATIVE(sum[i], offset, WARP_SIZE); sum[i] = sum[i] + b; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp softmax backward functions as fused variants of at::softmax_backward_data function //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //softmax backward data function is taken from native pytorch, elementwise mul is fused in the epolog, as well as masking and scaling for fusing dropout template __global__ void masked_scale_softmax_warp_backward_masked_dgrad(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int batch_size, int stride, int element_count, int heads) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = (input_t)((acc_t)mask[i*element_count+it*WARP_SIZE] * (acc_t)grad[i*element_count+it*WARP_SIZE] * (acc_t)scale )*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients int total_ind = thread_offset + i*element_count + it*WARP_SIZE; int pad_mask_ind = element_count*(total_ind/(heads * element_count * element_count)) + total_ind%element_count; uint8_t pad_mask_element = 1 - pad_mask[pad_mask_ind]; if (pad_mask_element == 0) gradInput[i*element_count+it*WARP_SIZE] = 0; else { if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } } template void dispatch_masked_scale_softmax_backward_masked_out(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, int heads) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 1: // 2 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 2: // 4 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 3: // 8 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 4: // 16 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 5: // 32 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 6: // 64 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 7: // 128 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 8: // 256 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 9: // 512 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 10: // 1024 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; default: break; } } } template void dispatch_masked_scale_softmax_backward_masked_out_stream(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, int heads, cudaStream_t streamid) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 1: // 2 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 2: // 4 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 3: // 8 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 4: // 16 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 5: // 32 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 6: // 64 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 7: // 128 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 8: // 256 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 9: // 512 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 10: // 1024 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; default: break; } } } template __global__ void masked_scale_softmax_warp_backward(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *mask, acc_t scale, int batch_size, int stride, int element_count) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = (input_t)((acc_t)mask[i*element_count+it*WARP_SIZE] * (acc_t)grad[i*element_count+it*WARP_SIZE] * (acc_t)scale )*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } template __global__ void masked_scale_softmax_warp_backward_recompute(output_t *gradInput, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int batch_size, int stride, int pad_batch_stride, int element_count) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; //vectorize if a row length is multiple of 4 int flag_vec4 = element_count & 3 == 0; acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; input_t elements_input[WARP_BATCH][WARP_ITERATIONS] ; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; softmax_input += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const input_t* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; grad_reg[i][it+element] = acc_t(0); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], softmax_input + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); //(__half)-std::numeric_limits::infinity() uint8_t mask_temp[ELEMENTS_PER_LDG_STG]; input_t grad_temp[ELEMENTS_PER_LDG_STG]; copy_vector(&mask_temp[0], mask + itr_idx); copy_vector(&grad_temp[0], grad + itr_idx); #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { grad_reg[i][it+element] = ((acc_t)mask_temp[element] * (acc_t)grad_temp[element] * (acc_t)scale ); } } } } // load data from global memory // convert input_t to acc_t // TODO : remove this, input is already acc_t type in register acc_t elements[WARP_BATCH][WARP_ITERATIONS] ; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it ++) { elements[i][it] = elements[i][it] / sum[i]; grad_reg[i][it] = grad_reg[i][it] * elements[i][it]; } } acc_t grad_sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { grad_sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { grad_sum[i] += grad_reg[i][it]; } } warp_reduce_sum(grad_sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t grad_input_reg[ELEMENTS_PER_LDG_STG]; #pragma unroll for (int element=0; element(gradInput + i * element_count + it * WARP_SIZE, grad_input_reg); } } } } template using masked_scale_softmax_warp_backward_recompute_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int batch_size, int stride, int pad_batch_stride, int element_count); template bool masked_scale_softmax_warp_backward_recompute_kernel(int element_count, int log2_elements, int &warp_size, int &batches_per_warp, masked_scale_softmax_warp_backward_recompute_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; bool flag_vec4 = (element_count % 4 == 0); switch (log2_elements) { case 0: // 1 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 1: // 2 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 2: // 4 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 3: // 8 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 4: // 16 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 5: // 32 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 6: // 64 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 7: // 128 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 8: // 256 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 9: // 512 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 10: // 1024 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 11: // 2048 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; default: return false; } return true; } template bool dispatch_masked_scale_softmax_backward_recompute(output_t *grad_input, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int pad_batch_stride, int batch_count, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 2048) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_scale_softmax_warp_backward_recompute_func kernel; int warp_size, batches_per_warp; if (!masked_scale_softmax_warp_backward_recompute_kernel(softmax_elements, log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; // compute launch size dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, softmax_input, pad_mask, mask, scale, batch_count, softmax_elements_stride, pad_batch_stride, softmax_elements); return true; } return false; } template void dispatch_masked_scale_softmax_backward_stream(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, cudaStream_t streamid) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 1: // 2 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 2: // 4 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 3: // 8 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 4: // 16 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 5: // 32 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 6: // 64 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 7: // 128 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 8: // 256 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 9: // 512 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 10: // 1024 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; default: break; } } } // elementwise multiplication called in at::softmax_backward_data is fused inside softmax dgrad kernel // as a result of fusion, intermediate multiplication result is stored in fp32 in registers, instead of fp16 template __global__ void softmax_warp_backward_fused_native(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = grad[i*element_count+it*WARP_SIZE]*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; //* output_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it];// * output_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } template void dispatch_softmax_backward_fused_native(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 1: // 2 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 2: // 4 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 3: // 8 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 4: // 16 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 5: // 32 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 6: // 64 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 7: // 128 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 8: // 256 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 9: // 512 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 10: // 1024 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; default: break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp softmax backward //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template __global__ void softmax_warp_backward(__half *gradInput, const __half *grad, const __half *output, int batch_size, int stride, int element_count) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // load data from global memory input_t grad_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; input_t output_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { copy_vector(&grad_reg_input[i][it], grad + i * element_count + it * WARP_SIZE); copy_vector(&output_reg_input[i][it], output + i * element_count + it * WARP_SIZE); } } } // convert half to floating point acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS]; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { grad_reg[i][it] = grad_reg_input[i][it]; output_reg[i][it] = output_reg_input[i][it]; } } // compute thread local sum acc_t sum[WARP_BATCH] = {0}; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { sum[i] += grad_reg[i][it] * output_reg[i][it]; } } // reduction sum constexpr uint32_t FULL_MASK = 0xffffffff; #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = (output_reg[i][it+element] * (grad_reg[i][it+element] - sum[i])); } // store them in global memory copy_vector(gradInput + i * element_count + it * WARP_SIZE, out); } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using softmax_backward_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count); template bool warp_softmax_backward_kernel(int log2_elements, int &warp_size, int &batches_per_warp, softmax_backward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &softmax_warp_backward; break; case 1: // 2 kernel = &softmax_warp_backward; break; case 2: // 4 kernel = &softmax_warp_backward; break; case 3: // 8 kernel = &softmax_warp_backward; break; case 4: // 16 kernel = &softmax_warp_backward; break; case 5: // 32 kernel = &softmax_warp_backward; break; case 6: // 64 kernel = &softmax_warp_backward; break; case 7: // 128 kernel = &softmax_warp_backward; break; case 8: // 256 kernel = &softmax_warp_backward; break; case 9: // 512 kernel = &softmax_warp_backward; break; case 10: // 1024 kernel = &softmax_warp_backward; break; default: return false; } return true; } template bool dispatch_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template bool dispatch_softmax_backward_stream(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template __global__ void masked_softmax_warp_backward(__half *gradInput, const __half *grad, const __half *output, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // load data from global memory input_t grad_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; input_t output_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { copy_vector(&grad_reg_input[i][it], grad + i * element_count + it * WARP_SIZE); copy_vector(&output_reg_input[i][it], output + i * element_count + it * WARP_SIZE); } } } // convert half to floating point acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS]; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { grad_reg[i][it] = grad_reg_input[i][it]; output_reg[i][it] = output_reg_input[i][it]; } } // compute thread local sum acc_t sum[WARP_BATCH] = {0}; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { sum[i] += grad_reg[i][it] * output_reg[i][it]; } } // reduction sum constexpr uint32_t FULL_MASK = 0xffffffff; #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = (output_reg[i][it+element] * (grad_reg[i][it+element] - sum[i])); } // store them in global memory int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; // It is kind of unfortunate this has to be here to zero something out that is close to // zero in the first place apply_mask(&out[0], 0.0, curr_mask + itr_jmp); copy_vector(gradInput + itr_idx, out); } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using masked_softmax_backward_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_masked_softmax_backward_kernel(int log2_elements, int &warp_size, int &batches_per_warp, masked_softmax_backward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &masked_softmax_warp_backward; break; case 1: // 2 kernel = &masked_softmax_warp_backward; break; case 2: // 4 kernel = &masked_softmax_warp_backward; break; case 3: // 8 kernel = &masked_softmax_warp_backward; break; case 4: // 16 kernel = &masked_softmax_warp_backward; break; case 5: // 32 kernel = &masked_softmax_warp_backward; break; case 6: // 64 kernel = &masked_softmax_warp_backward; break; case 7: // 128 kernel = &masked_softmax_warp_backward; break; case 8: // 256 kernel = &masked_softmax_warp_backward; break; case 9: // 512 kernel = &masked_softmax_warp_backward; break; case 10: // 1024 kernel = &masked_softmax_warp_backward; break; default: return false; } return true; } template bool dispatch_masked_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_masked_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/multihead_attn/strided_batched_gemm.h ================================================ #include #include //#include #include #include #include #include #include #include "THC/THC.h" #include #include "cutlass/cutlass.h" #include "cutlass/gemm/gemm.h" #include "cutlass/gemm/wmma_gemm_traits.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; cublasOperation_t convertTransToCublasOperation(char trans) { if (trans == 't') return CUBLAS_OP_T; else if (trans == 'n') return CUBLAS_OP_N; else if (trans == 'c') return CUBLAS_OP_C; else { THError("trans must be one of: t, n, c"); return CUBLAS_OP_T; } } void CublasStridedBatchedGemm(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount, cublasGemmAlgo_t algo=CUBLAS_GEMM_DEFAULT_TENSOR_OP) { cublasOperation_t opa = convertTransToCublasOperation(transa); cublasOperation_t opb = convertTransToCublasOperation(transb); cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); float fAlpha = alpha; float fBeta = beta; //THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); THCublasCheck(cublasGemmStridedBatchedEx(handle, opa, opb, (int)m, (int)n, (int)k, (void*)&fAlpha, a, CUDA_R_16F, (int)lda, strideA, b, CUDA_R_16F, (int)ldb, strideB, (void*)&fBeta, c, CUDA_R_16F, (int)ldc, strideC, (int)batchCount, CUDA_R_32F, algo)); //THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); } template void CutlassGemm_FP32Accum(cudaStream_t stream, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { //printf("CUTLASS-> %c%c M: %ld N: %ld K: %ld %d%d%d LDA: %ld LDB: %ld LDC: %ld strideA: %ld strideB: %ld strideC: %ld Alpha: %f Beta: %f\n", ((int)A_LAYOUT == 0 ? 'T' : 'N'), ((int)B_LAYOUT ==0 ? 'T' : 'N'), m, n, k, SRC_A,SRC_B,DST_C, lda, ldb, ldc, strideA, strideB, strideC, alpha, beta); typedef cutlass::gemm::WmmaGemmTraits< A_LAYOUT, B_LAYOUT, cutlass::Shape<32, 16, 16>, half, half, half, cutlass::gemm::LinearScaling, float, typename cutlass::gemm::WmmaGemmAccumulatorsPerWarp >::Shape, typename cutlass::Shape<16, 16, 16>, SRC_A, //kScalarsPerLdgA_ SRC_B, //kScalarsPerLdgB_ SRC_A, //KScalarsPerLdsA_ SRC_B, //KScalarsPerLdsB_ DST_C, //kScalarsPerLdgCAndStgD_ DST_C/2, //kScalarsPerStsD_ DST_C/2 //kScalarsPerLdsD_ > WmmaGemmTraits; typedef cutlass::gemm::Gemm Gemm; typename Gemm::Params params; int result = params.initialize( m, // M dimension for each batch n, // N dimension for each batch k, // K dimension for each batch alpha, // scalar alpha a, lda, strideA, // distance in memory between the first element of neighboring batch b, ldb, strideB, // distance in memory between the first element of neighboring batch beta, // scalar beta c, // source matrix C ldc, strideC, // distance in memory between the first element of neighboring batch c, // destination matrix C (may be different memory than source C matrix) ldc, strideC, // distance in memory between the first element of neighboring batch batchCount ); AT_ASSERTM(result == 0, "Failed to initialize CUTLASS Gemm::Params object."); // batchCount in cutlass batched GEMM kernels maps to gridDim.z, which is limited to 16 bits. // To implement batched GEMM with larger batch size, we fragment it into // smaller batched GEMMs of gridDim.z <= 64k long batchesLeft = batchCount; long iterBatchCount = std::min(batchesLeft, static_cast((1 << 16) - 1)); do { //printf("CUTLASS-> %c%c M: %ld N: %ld K: %ld %d%d%d LDA: %ld LDB: %ld LDC: %ld strideA: %ld strideB: %ld strideC: %ld Alpha: %f Beta: %f TotalBatches: %ld iterBatchCount %ld\n", ((int)A_LAYOUT == 0 ? 'T' : 'N'), ((int)B_LAYOUT ==0 ? 'T' : 'N'), m, n, k, SRC_A,SRC_B,DST_C, lda, ldb, ldc, strideA, strideB, strideC, alpha, beta, batchesLeft, iterBatchCount); int result = params.initialize( m, // M dimension for each batch n, // N dimension for each batch k, // K dimension for each batch alpha, // scalar alpha a, lda, strideA, // distance in memory between the first element of neighboring batch b, ldb, strideB, // distance in memory between the first element of neighboring batch beta, // scalar beta c, // source matrix C ldc, strideC, // distance in memory between the first element of neighboring batch c, // destination matrix C (may be different memory than source C matrix) ldc, strideC, // distance in memory between the first element of neighboring batch iterBatchCount ); AT_ASSERTM(result == 0, "Failed to initialize CUTLASS Gemm::Params object."); // Launch the CUTLASS GEMM kernel. THCudaCheck(Gemm::launch(params, stream)); // Update batched GEMM params based on completed work batchesLeft = batchesLeft - iterBatchCount; a += iterBatchCount * strideA; b += iterBatchCount * strideB; c += iterBatchCount * strideC;; iterBatchCount = std::min(batchesLeft, static_cast((1 << 16) - 1)); } while(batchesLeft > 0); } void gemm_switch_fp32accum(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { auto stream = c10::cuda::getCurrentCUDAStream(); //printf("GEMM -> %c%c M: %i N: %i K: %i Alpha: %f Beta: %f\n", (transa == 't' ? 'T' : 'N'), (transb =='t' ? 'T' : 'N'), m, n, k, alpha, beta); if ( (transa == 't') && (transb == 'n') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else if ( (transa == 'n') && (transb == 'n') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else if ( (transa == 'n') && (transb == 't') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else { AT_ASSERTM(false, "TransA and TransB are invalid"); } } void adjustLdLevel3(char transa, char transb, int64_t m, int64_t n, int64_t k, int64_t *lda, int64_t *ldb, int64_t *ldc) { int transa_ = ((transa == 't') || (transa == 'T')); int transb_ = ((transb == 't') || (transb == 'T')); // Note: leading dimensions generally are checked that they are > 0 and at least as big the result // requires (even if the value won't be used). if(n <= 1) *ldc = std::max(m, 1); if(transa_) { if(m <= 1) *lda = std::max(k, 1); } else { if(k <= 1) *lda = std::max(m, 1); } if(transb_) { if(k <= 1) *ldb = std::max(n, 1); } else { if(n <= 1) *ldb = std::max(k, 1); } } void HgemmStridedBatched(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { if( (m >= INT_MAX) || (n >= INT_MAX) || (k >= INT_MAX) || (lda >= INT_MAX) || (ldb >= INT_MAX) || (ldc >= INT_MAX) || (batchCount >= INT_MAX) ) { THError("Cublas_SgemmStridedBatched only supports m, n, k, lda, ldb, ldc, batchCount" "with the bound [val] <= %d", INT_MAX); } adjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); //gemm_switch(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); gemm_switch_fp32accum(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } /****** at::Tensor strided_batched_gemm_cuda( float beta, at::Tensor in_result, float alpha, at::Tensor batch1, at::Tensor batch2) { bool transpose_result; char transpose_batch1, transpose_batch2; int64_t lda, ldb, ldc; at::Tensor result, input1, input2; if (in_result.stride(1) == 1) { transpose_result = false; result = in_result; ldc = result.stride(2); } else if (in_result.stride(2) == 1) { transpose_result = true; at::Tensor swap = batch2; batch2 = batch1; batch1 = swap; result = in_result; ldc = result.stride(1); } else { AT_ASSERTM(false, "result should be contiguous"); } if (batch1.stride(transpose_result ? 2 : 1) == 1 && batch1.stride(transpose_result ? 1 : 2) != 0) { transpose_batch1 = 'n'; input1 = batch1; lda = input1.stride(transpose_result ? 1 : 2); } else if (batch1.stride(transpose_result ? 1 : 2) == 1 && batch1.stride(transpose_result ? 2 : 1) != 0) { transpose_batch1 = 't'; input1 = batch1; lda = input1.stride(transpose_result ? 2 : 1); } else { AT_ASSERTM(false, "input1 should be contiguous"); } if (batch2.stride(transpose_result ? 2 : 1) == 1 && batch2.stride(transpose_result ? 1 : 2) != 0) { transpose_batch2 = 'n'; input2 = batch2; ldb = input2.stride(transpose_result ? 1 : 2); } else if (batch2.stride(transpose_result ? 1 : 2) == 1 && batch2.stride(transpose_result ? 2 : 1) != 0) { transpose_batch2 = 't'; input2 = batch2; ldb = input2.stride(transpose_result ? 2 : 1); } else { AT_ASSERTM(false, "input2 should be contiguous"); } int64_t num_batches = result.size(0); HgemmStridedBatched( state, transpose_batch1, transpose_batch2, result.size(transpose_result ? 2 : 1), result.size(transpose_result ? 1 : 2), input1.size(transpose_result ? 1 : 2), alpha, static_cast(input1.data_ptr()), lda, input1.stride(0), static_cast(input2.data_ptr()), ldb, input2.stride(0), beta, static_cast(result.data_ptr()), ldc, result.stride(0), num_batches); return in_result; } ***/ ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/fused_adam_cuda.cpp ================================================ #include // CUDA forward declaration void fused_strided_check_finite(at::Tensor & overflow_flag, at::Tensor & p_copy, int stride, int clear_overflow_first); void fused_adam_cuda(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_reversible_adam_cuda(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_maybe_adam_undo_cuda(at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_adam_cuda_mt(int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void maybe_cast_cuda(at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out); void maybe_cast_cuda_mt(int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists); #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) // C++ interface void strided_check_finite( at::Tensor& overflow_flag, at::Tensor& p_copy, int stride, int clear_overflow_first ) { CHECK_INPUT(p_copy); fused_strided_check_finite(overflow_flag, p_copy, stride, clear_overflow_first); } void adam(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); if (p_copy.numel() > 0) CHECK_INPUT(p_copy); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); AT_ASSERTM(p_copy.numel() == num_elem || p_copy.numel() == 0, "number of elements in p_copy and p tensors should be equal, or p_copy should be empty"); fused_adam_cuda(p, p_copy, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void reversible_adam(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); if (p_copy.numel() > 0) CHECK_INPUT(p_copy); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); AT_ASSERTM(p_copy.numel() == num_elem || p_copy.numel() == 0, "number of elements in p_copy and p tensors should be equal, or p_copy should be empty"); fused_reversible_adam_cuda(p, p_copy, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void maybe_adam_undo(at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); fused_maybe_adam_undo_cuda(overflow_flag, p, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void maybe_cast(at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out) { CHECK_INPUT(p_in); CHECK_INPUT(p_out); int64_t num_elem = p_in.numel(); AT_ASSERTM(p_out.numel() == num_elem, "number of elements in p_in and p_out should be equal"); maybe_cast_cuda(overflow_flag, p_in, p_out); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("strided_check_finite", &strided_check_finite, "Strided finite check."); m.def("adam", &adam, "Adam optimized CUDA implementation."); m.def("reversible_adam", &reversible_adam, "Reversible Adam optimized CUDA implementation."); m.def("adam_mt", &fused_adam_cuda_mt, "Multi tensor Adam optimized CUDA implementation."); m.def("maybe_adam_undo", &maybe_adam_undo, "Undo function for Adam optimized CUDA implementation."); m.def("maybe_cast", &maybe_cast, "Unpack byte tensor containing e5m2 floats."); m.def("maybe_cast_mt", &maybe_cast_cuda_mt, "Unpack byte tensor containing e5m2 floats."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/fused_adam_cuda_kernel.cu ================================================ #include "ATen/ATen.h" #include "ATen/cuda/CUDAContext.h" #include "ATen/cuda/detail/IndexUtils.cuh" #include #include #include #include #include "ATen/TensorUtils.h" // #include "ATen/Type.h" #include "ATen/AccumulateType.h" #include #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } #include "type_shim.h" typedef enum{ ADAM_MODE_0 =0, // eps under square root ADAM_MODE_1 =1 // eps outside square root } adamMode_t; template __global__ void adam_cuda_kernel( T* __restrict__ p, GRAD_T* __restrict__ p_copy, // For mixed precision training, pass NULL if not needed T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; for (int j = i; j < tsize; j+=totThreads) { T scaled_grad = g[j]/grad_scale; m[j] = b1*m[j] + (1-b1)*scaled_grad; v[j] = b2*v[j] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(v[j] + eps); else // Mode 1 denom = sqrtf(v[j]) + eps; float update = (m[j]/denom) + (decay*p[j]); p[j] = p[j] - (step_size*update); if (p_copy != NULL) p_copy[j] = (GRAD_T) p[j]; } } template struct AdamFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata& tl, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, adamMode_t mode, const float decay) { int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; T* p = (T *)tl.addresses[0][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T *)tl.addresses[1][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T *)tl.addresses[2][tensor_loc]; v += chunk_idx*chunk_size; GRAD_T* g = (GRAD_T *)tl.addresses[3][tensor_loc]; g += chunk_idx*chunk_size; GRAD_T* p_copy = NULL; if (DEPTH == 5) { p_copy = (GRAD_T *)tl.addresses[4][tensor_loc]; p_copy += chunk_idx*chunk_size; } n -= chunk_idx*chunk_size; T incoming_p[ILP]; T incoming_m[ILP]; T incoming_v[ILP]; T incoming_g[ILP]; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(m) && is_aligned(v) && is_aligned(g) && is_aligned(p_copy)) { for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load GRAD_T tmp_g[ILP]; load_store(incoming_p, p, 0, i_start); load_store(incoming_m, m, 0, i_start); load_store(incoming_v, v, 0, i_start); load_store(tmp_g, g, 0, i_start); #pragma unroll for(int ii = 0; ii < ILP; ii++) { incoming_g[ii] = static_cast(tmp_g[ii]); T scaled_grad = incoming_g[ii]/grad_scale; incoming_m[ii] = b1*incoming_m[ii] + (1-b1)*scaled_grad; incoming_v[ii] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(incoming_v[ii] + eps); else // Mode 1 denom = sqrtf(incoming_v[ii]) + eps; float update = (incoming_m[ii]/denom) + (decay*incoming_p[ii]); incoming_p[ii] = incoming_p[ii] - (step_size*update); if (DEPTH == 5) tmp_g[ii] = static_cast(incoming_p[ii]); } load_store(p, incoming_p, i_start, 0); load_store(m, incoming_m, i_start, 0); load_store(v, incoming_v, i_start, 0); if (DEPTH == 5) load_store(p_copy, tmp_g, i_start, 0); } } else { for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { incoming_p[ii] = 0; incoming_m[ii] = 0; incoming_v[ii] = 0; incoming_g[ii] = 0; int i = i_start + threadIdx.x + ii*blockDim.x; if (i < n && i < chunk_size) { incoming_p[ii] = p[i]; incoming_m[ii] = m[i]; incoming_v[ii] = v[i]; incoming_g[ii] = static_cast(g[i]); } } // note for clarification to future michael: // From a pure memory dependency perspective, there's likely no point unrolling // the write loop, since writes just fire off once their LDGs arrive. // Put another way, the STGs are dependent on the LDGs, but not on each other. // There is still compute ILP benefit from unrolling the loop though. #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = i_start + threadIdx.x + ii*blockDim.x; if(j < n && j < chunk_size) { T scaled_grad = incoming_g[ii]/grad_scale; m[j] = b1*incoming_m[ii] + (1-b1)*scaled_grad; v[j] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(v[j] + eps); else // Mode 1 denom = sqrtf(v[j]) + eps; float update = (m[j]/denom) + (decay*incoming_p[ii]); p[j] = incoming_p[ii] - (step_size*update); if (DEPTH == 5) p_copy[j] = (GRAD_T) p[j]; } } } } } }; void fused_adam_cuda( at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { // using namespace at; //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.numel() ? p_copy.DATA_PTR() : NULL, m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", adam_cuda_kernel<<>>( p.DATA_PTR(), NULL, //don't output p_copy for fp32, it's wasted write m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } void fused_adam_cuda_mt( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, // p, m, v, g, p_copy float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 4 || tl_sz == 5, "expected tensor lists of size 4 or 5"); if (tensor_lists[3][0].scalar_type() == at::ScalarType::Half) { //alher values should be fp32 for half gradients AT_ASSERTM(tensor_lists[0][0].scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dich is done on the gradient type if (tl_sz == 5) { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", using accscalar_t = at::acc_type; multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<5, accscalar_t, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } else { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", using accscalar_t = at::acc_type; multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<4, accscalar_t, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } } else { if (tl_sz == 5) { DISPATCH_DOUBLE_AND_FLOAT(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<5, scalar_t_0, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } else { DISPATCH_DOUBLE_AND_FLOAT(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<4, scalar_t_0, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } } THCudaCheck(cudaGetLastError()); } template __device__ void convert(const FROM_T vi, TO_T& vo) { vo = static_cast(vi); } template <> __device__ void convert(const float vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = vi; s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, float& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = static_cast(t.as_half); } template <> __device__ void convert(const at::Half vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = static_cast(vi); s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, at::Half& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = t.as_half; } template __global__ void strided_check_finite_cuda_kernel( volatile int* noop_gmem, GRAD_T* __restrict__ p_copy, const size_t tsize, int stride, int clear_overflow_first) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock) * stride; const int totThreads = gridDim.x*gridDim.y*threadsPerBlock*stride; if (clear_overflow_first) { if (i == 0) { *noop_gmem = 0; } __syncthreads(); } for (int j = i; j < tsize; j+=totThreads) { GRAD_T pi = p_copy[j]; if (!isfinite(pi)) { *noop_gmem = 1; } } } template <> __global__ void strided_check_finite_cuda_kernel( volatile int* noop_gmem, uint8_t* __restrict__ p_copy, const size_t tsize, int stride, int clear_overflow_first) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock) * stride; const int totThreads = gridDim.x*gridDim.y*threadsPerBlock*stride; if (clear_overflow_first) { if (i == 0) { *noop_gmem = 0; } __syncthreads(); } for (int j = i; j < tsize; j+=totThreads) { at::Half pi; convert(p_copy[j], pi); if (!isfinite(pi)) { *noop_gmem = 1; } } } template __global__ void maybe_cast_kernel( volatile int* overflow_flag, const FROM_T* p_in, TO_T* p_out, const size_t tsize) { if (overflow_flag && *overflow_flag != 0) return; //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; FROM_T pi[ILP]; TO_T po[ILP]; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { pi[ii] = 0; int j = j_start + i + totThreads*ii; if (j < tsize) { pi[ii] = p_in[j]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { convert(pi[ii], po[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i + totThreads*ii; if (j < tsize) { p_out[j] = po[ii]; } } } } template __global__ void reversible_adam_cuda_kernel( T* __restrict__ p, REDU_T* __restrict__ p_copy, // For mixed precision training, pass NULL if not needed T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; T mi[ILP]; T vi[ILP]; T pi[ILP]; T gi[ILP]; bool overflow = false; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { mi[ii] = T(0); vi[ii] = T(0); pi[ii] = T(0); gi[ii] = GRAD_T(0); int j = j_start + i + totThreads*ii; if (j < tsize) { pi[ii] = p[j]; mi[ii] = m[j]; vi[ii] = v[j]; gi[ii] = static_cast(g[j]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { T scaled_grad = gi[ii]/grad_scale; if (isfinite(scaled_grad)) { mi[ii] = b1*mi[ii] + (1-b1)*scaled_grad; vi[ii] = b2*vi[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(vi[ii] + eps); else // Mode 1 denom = sqrtf(vi[ii]) + eps; float update = (mi[ii]/denom) + (decay*pi[ii]); pi[ii] = pi[ii] - (step_size*update); } else { overflow = true; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i + totThreads*ii; if (j < tsize) { m[j] = mi[ii]; v[j] = vi[ii]; p[j] = pi[ii]; if (p_copy != NULL) { convert(pi[ii], p_copy[j]); } } } } if (p_copy != NULL) { __syncthreads(); if (overflow) { convert(float(INFINITY), p_copy[0]); } } } template __global__ void maybe_adam_undo_cuda_kernel( volatile int* overflow_flag, T* __restrict__ p, T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { // NB! Skip undo kernel when overflow flag is NOT set if (overflow_flag && *overflow_flag == 0) return; //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; T mi[ILP]; T vi[ILP]; T pi[ILP]; T gi[ILP]; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { mi[ii] = T(0); vi[ii] = T(0); pi[ii] = T(0); gi[ii] = GRAD_T(0); int j = j_start + i*ILP; if (j < tsize) { pi[ii] = p[j]; mi[ii] = m[j]; vi[ii] = v[j]; gi[ii] = static_cast(g[j]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { T scaled_grad = gi[ii]/grad_scale; if (isfinite(scaled_grad)) { float denom; if (mode == ADAM_MODE_0) denom = sqrtf(vi[ii] + eps); else // Mode 1 denom = sqrtf(vi[ii]) + eps; pi[ii] = (pi[ii] + step_size*(mi[ii]/denom)) / (1.0f - step_size*decay); mi[ii] = (mi[ii] - (1-b1)*scaled_grad) / b1; vi[ii] = (vi[ii] - (1-b2)*scaled_grad*scaled_grad) / b2; // Make sure round off errors don't create (small) negative value. // This can happen if we have to revert the very first step. vi[ii] = vi[ii] >= 0.0f ? vi[ii] : 0.0f; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i*ILP; if (j < tsize) { m[j] = mi[ii]; v[j] = vi[ii]; p[j] = pi[ii]; } } } } template struct MaybeCastFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* overflow_flag, TensorListMetadata& tl) { if (overflow_flag && *overflow_flag != 0) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; FROM_T* p_in = (FROM_T *)tl.addresses[0][tensor_loc]; p_in += chunk_idx*chunk_size; TO_T* p_out = (TO_T *)tl.addresses[1][tensor_loc]; p_out += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; int dim = chunk_size < n ? chunk_size : n; FROM_T pi[ILP]; TO_T po[ILP]; for(int j_start = 0; j_start < dim; j_start+=blockDim.x*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { pi[ii] = FROM_T(0); int j = j_start + threadIdx.x + ii*blockDim.x; if (j < dim) { pi[ii] = p_in[j]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { convert(pi[ii], po[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + threadIdx.x + ii*blockDim.x; if (j < dim) { p_out[j] = po[ii]; } } } } }; void fused_strided_check_finite( at::Tensor & overflow_flag, at::Tensor & p_copy, int stride, int clear_overflow_first) { //Get tensor size int tsize = p_copy.numel(); int niter = (tsize + stride - 1) / stride; //Determine #threads and #blocks const int threadsPerBlock = 512; //In order to avoid race condition, blocks must be 1 when clear_overflow_first flag is set. const dim3 blocks(clear_overflow_first ? 1 : (niter+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p_copy), "parameter tensor is too large to be indexed with int32"); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_HALF_AND_BYTE(p_copy.scalar_type(), 0, "check_finite_cuda_kernel", strided_check_finite_cuda_kernel<<>>( overflow_flag.DATA_PTR(), p_copy.DATA_PTR(), tsize, stride, clear_overflow_first); ); THCudaCheck(cudaGetLastError()); } void fused_reversible_adam_cuda( at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { // using namespace at; //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors if (p_copy.numel() == 0 || p_copy.scalar_type() == g.scalar_type()) { DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.numel() ? p_copy.DATA_PTR() : NULL, m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { AT_ASSERTM(p_copy.scalar_type() == at::ScalarType::Byte, "expected parameter to be of byte type"); DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_e5m2_kernel", using accscalar_t = at::acc_type; reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), NULL, //don't output p_copy for fp32, it's wasted write m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } void maybe_cast_cuda( at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out) { //Get tensor size int tsize = p_in.numel(); AT_ASSERTM(tsize == p_out.numel(), "p_in.numel() must equal p_out.numel()"); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p_in), "parameter tensor is too large to be indexed with int32"); //Constants cudaStream_t stream = at::cuda::getCurrentCUDAStream(); DISPATCH_FLOAT_HALF_AND_BYTE(p_in.scalar_type(), 0, "maybe_cast_cuda" DISPATCH_FLOAT_HALF_AND_BYTE(p_out.scalar_type(), 1, "maybe_cast_cuda", maybe_cast_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p_in.DATA_PTR(), p_out.DATA_PTR(), tsize); )) THCudaCheck(cudaGetLastError()); } void maybe_cast_cuda_mt( int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists) // p_in, p_out { //Constants cudaStream_t stream = at::cuda::getCurrentCUDAStream(); size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 2, "expected tensor lists of size 2"); DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[0][0].scalar_type(), 0, "maybe_cast_cuda_mt_kernel", DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[1][0].scalar_type(), 1, "maybe_cast_cuda_mt_kernel", multi_tensor_apply<2>( BLOCK_SIZE, chunk_size, overflow_flag, tensor_lists, MaybeCastFunctor<2, scalar_t_0, scalar_t_1>()); )) THCudaCheck(cudaGetLastError()); } void fused_maybe_adam_undo_cuda( at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; maybe_adam_undo_cuda_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", maybe_adam_undo_cuda_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/fused_lamb_cuda.cpp ================================================ #include void multi_tensor_lamb_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int bias_correction, const float weight_decay, const int grad_averaging, const int mode, const float global_grad_norm, const float max_grad_norm); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("lamb", &multi_tensor_lamb_cuda, "Computes and apply update for LAMB optimizer"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/fused_lamb_cuda_kernel.cu ================================================ #include #include #include #include // Another possibility: // #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 typedef enum{ MOMENT_MODE_0 =0, // L2 regularization mode MOMENT_MODE_1 =1 // Decoupled weight decay mode } adamMode_t; std::tuple multi_tensor_l2norm_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::optional per_tensor_python); using MATH_T = float; template struct LAMBStage1Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<4>& tl, const float beta1, const float beta2, const float beta3, const float beta1_correction, const float beta2_correction, const float epsilon, adamMode_t mode, const float decay, const float global_grad_norm, const float max_global_grad_norm) { // I'd like this kernel to propagate infs/nans. // if(*noop_gmem == 1) // return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float clipped_global_grad_norm = global_grad_norm > max_global_grad_norm ? global_grad_norm / max_global_grad_norm : 1.0f; T* g = (T*)tl.addresses[0][tensor_loc]; g += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T*)tl.addresses[2][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T*)tl.addresses[3][tensor_loc]; v += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; // see note in multi_tensor_scale_kernel.cu for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_g[ii] = g[i]; // special ?optimization? for lamb stage 1 if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = p[i]; } r_m[ii] = m[i]; r_v[ii] = v[i]; } else { r_g[ii] = MATH_T(0); r_p[ii] = MATH_T(0); r_m[ii] = MATH_T(0); r_v[ii] = MATH_T(0); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / clipped_global_grad_norm; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / clipped_global_grad_norm; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { g[i] = r_p[ii]; m[i] = r_m[ii]; v[i] = r_v[ii]; } } } } }; // Step 2 reads in 'update' value and per-tensor param_norm and update_norm. // It computes new parameter value. template struct LAMBStage2Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<2>& tl, const float* per_tensor_param_norm, const float* per_tensor_update_norm, const float learning_rate, const float decay) { // I'd like this kernel to propagate infs/nans. // if(*noop_gmem == 1) // return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; MATH_T ratio = learning_rate; // apply adaptive learning rate to parameters with non-zero weight decay if (decay != 0.0) { float param_norm = per_tensor_param_norm[tensor_num]; float update_norm = per_tensor_update_norm[tensor_num]; ratio = (update_norm != 0.0f && param_norm != 0.0f) ? learning_rate * (param_norm / update_norm) : learning_rate; } T* update = (T*)tl.addresses[0][tensor_loc]; update += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_p[ILP]; MATH_T r_update[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_p[ii] = p[i]; r_update[ii] = update[i]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = r_p[ii] - (ratio * r_update[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { p[i] = r_p[ii]; } } } } }; void multi_tensor_lamb_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int bias_correction, const float weight_decay, const int grad_averaging, const int mode, const float global_grad_norm, const float max_grad_norm) { using namespace at; // Master weight and 32bit momentum(potentially changing) is not handled by this // So we assume every tensor are all in the same type // Handle bias correction mode float bias_correction1 = 1.0f, bias_correction2 = 1.0f; if (bias_correction == 1) { bias_correction1 = 1 - std::pow(beta1, step); bias_correction2 = 1 - std::pow(beta2, step); } // Handle grad averaging mode float beta3 = 1.0f; if (grad_averaging == 1) beta3 = 1 - beta1; std::vector> grad_list(tensor_lists.begin(), tensor_lists.begin()+1); std::vector> param_list(tensor_lists.begin()+1, tensor_lists.begin()+2); // Compute per tensor param norm auto param_norm_tuple = multi_tensor_l2norm_cuda(chunk_size, noop_flag, param_list, true); // We now in-place modify grad to store update before compute its norm // Generally this is not a issue since people modify grad in step() method all the time // We can also grab list of empty tensor to avoid this, but I'd like to save space/cpu code DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 0, "lamb_stage_1", multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, LAMBStage1Functor(), beta1, beta2, beta3, // 1-beta1 or 1 depends on averaging mode bias_correction1, bias_correction2, epsilon, (adamMode_t) mode, weight_decay, global_grad_norm, max_grad_norm); ) // Compute update norms auto update_norm_tuple = multi_tensor_l2norm_cuda(chunk_size, noop_flag, grad_list, true); std::vector> grad_param_list(tensor_lists.begin(), tensor_lists.begin()+2); DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 0, "lamb_stage_2", multi_tensor_apply<2>( BLOCK_SIZE, chunk_size, noop_flag, grad_param_list, LAMBStage2Functor(), std::get<1>(param_norm_tuple).DATA_PTR(), std::get<1>(update_norm_tuple).DATA_PTR(), lr, weight_decay); ) AT_CUDA_CHECK(cudaGetLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/multi_tensor_distopt_adam.cpp ================================================ #include void multi_tensor_fused_adam_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_bias_correction, at::Tensor per_tensor_eps, at::Tensor per_tensor_weight_decay, float lr, float grad_scale, int step, int mode); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("multi_tensor_fused_adam", &multi_tensor_fused_adam_cuda, "Multi tensor Adam optimized CUDA implementation."); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/multi_tensor_distopt_adam_kernel.cu ================================================ #include #include #include #include #include // Another possibility: // #include #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } typedef enum{ ADAM_MODE_0 =0, // eps under square root ADAM_MODE_1 =1 // eps outside square root } adamMode_t; template struct DistAdamFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata& tl, const float* per_tensor_beta1, const float* per_tensor_beta2, const int* per_tensor_bias_correction, const float* per_tensor_eps, const float* per_tensor_weight_decay, const float lr, const float grad_scale, const int step, adamMode_t mode) { int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float b1 = per_tensor_beta1[tensor_num]; float b2 = per_tensor_beta2[tensor_num]; float eps = per_tensor_eps[tensor_num]; float decay = per_tensor_weight_decay[tensor_num]; float beta1_correction = 1.0f, beta2_correction = 1.0f; if (per_tensor_bias_correction[tensor_num] == 1) { beta1_correction = 1 - std::pow(b1, step); beta2_correction = 1 - std::pow(b2, step); } T* p = (T *)tl.addresses[0][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T *)tl.addresses[1][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T *)tl.addresses[2][tensor_loc]; v += chunk_idx*chunk_size; GRAD_T* g = (GRAD_T *)tl.addresses[3][tensor_loc]; g += chunk_idx*chunk_size; GRAD_T* p_copy = NULL; if (DEPTH == 5) { p_copy = (GRAD_T *)tl.addresses[4][tensor_loc]; p_copy += chunk_idx*chunk_size; } n -= chunk_idx*chunk_size; T incoming_p[ILP]; T incoming_m[ILP]; T incoming_v[ILP]; T incoming_g[ILP]; // to make things simple, we put aligned case in a different code path if (n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(m) && is_aligned(v) && is_aligned(g) && is_aligned(p_copy)) { for (int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load GRAD_T tmp_g[ILP]; load_store(incoming_p, p, 0, i_start); load_store(incoming_m, m, 0, i_start); load_store(incoming_v, v, 0, i_start); load_store(tmp_g, g, 0, i_start); #pragma unroll for (int ii = 0; ii < ILP; ii++) { incoming_g[ii] = static_cast(tmp_g[ii]); T scaled_grad = incoming_g[ii]/grad_scale; incoming_m[ii] = b1*incoming_m[ii] + (1-b1)*scaled_grad; incoming_v[ii] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; T next_m_unbiased = incoming_m[ii] / beta1_correction; T next_v_unbiased = incoming_v[ii] / beta2_correction; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(next_v_unbiased + eps); else // Mode 1 denom = sqrtf(next_v_unbiased) + eps; float update = (next_m_unbiased / denom) + (decay * incoming_p[ii]); incoming_p[ii] = incoming_p[ii] - (lr * update); if (DEPTH == 5) tmp_g[ii] = static_cast(incoming_p[ii]); } load_store(p, incoming_p, i_start, 0); load_store(m, incoming_m, i_start, 0); load_store(v, incoming_v, i_start, 0); if (DEPTH == 5) load_store(p_copy, tmp_g, i_start, 0); } } else { for (int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { #pragma unroll for (int ii = 0; ii < ILP; ii++) { incoming_p[ii] = 0; incoming_m[ii] = 0; incoming_v[ii] = 0; incoming_g[ii] = 0; int i = i_start + threadIdx.x + ii*blockDim.x; if (i < n && i < chunk_size) { incoming_p[ii] = p[i]; incoming_m[ii] = m[i]; incoming_v[ii] = v[i]; incoming_g[ii] = static_cast(g[i]); } } #pragma unroll for (int ii = 0; ii < ILP; ii++) { int j = i_start + threadIdx.x + ii*blockDim.x; if (j < n && j < chunk_size) { T scaled_grad = incoming_g[ii]/grad_scale; m[j] = b1*incoming_m[ii] + (1-b1)*scaled_grad; v[j] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; T next_m_unbiased = m[j] / beta1_correction; T next_v_unbiased = v[j] / beta2_correction; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(next_v_unbiased + eps); else // Mode 1 denom = sqrtf(next_v_unbiased) + eps; float update = (next_m_unbiased / denom) + (decay * incoming_p[ii]); p[j] = incoming_p[ii] - (lr * update); if (DEPTH == 5) p_copy[j] = (GRAD_T) p[j]; } } } } } }; void multi_tensor_fused_adam_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, // p, m, v, g, p_copy at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_bias_correction, at::Tensor per_tensor_eps, at::Tensor per_tensor_weight_decay, float lr, float grad_scale, int step, int mode) { using namespace at; size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 4 || tl_sz == 5, "expected tensor lists of size 4 or 5"); if (tl_sz == 5) { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "dist_adam_cuda_kernel", // g using accscalar_t = at::acc_type; multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistAdamFunctor<5, accscalar_t, scalar_t_0>(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), per_tensor_eps.DATA_PTR(), per_tensor_weight_decay.DATA_PTR(), lr, grad_scale, step, (adamMode_t) mode); ); } else { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "dist_adam_cuda_kernel", // g using accscalar_t = at::acc_type; multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistAdamFunctor<4, accscalar_t, scalar_t_0>(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), per_tensor_eps.DATA_PTR(), per_tensor_weight_decay.DATA_PTR(), lr, grad_scale, step, (adamMode_t) mode); ); } THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/multi_tensor_distopt_lamb.cpp ================================================ #include void multi_tensor_lamb_compute_update_term_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_beta3, at::Tensor per_tensor_bias_correction, at::Tensor step, at::Tensor per_tensor_epsilon, const int mode, at::Tensor per_tensor_decay, at::Tensor global_scale, at::Tensor global_grad_norm, const float max_grad_norm); void multi_tensor_lamb_update_weights_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_param_norm, at::Tensor per_tensor_update_norm, at::Tensor update_norm_offset, at::Tensor learning_rate, at::Tensor per_tensor_decay, at::Tensor global_grad_norm, bool use_nvlamb); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("multi_tensor_lamb_compute_update_term", &multi_tensor_lamb_compute_update_term_cuda, "Computes update term for LAMB optimizer"); m.def("multi_tensor_lamb_update_weights", &multi_tensor_lamb_update_weights_cuda, "Applies update term for LAMB optimizer"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/optimizers/multi_tensor_distopt_lamb_kernel.cu ================================================ #include #include #include #include // Another possibility: // #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } template __device__ void convert(const FROM_T vi, TO_T& vo) { vo = static_cast(vi); } template <> __device__ void convert(const float vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = vi; s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, float& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = static_cast(t.as_half); } template <> __device__ void convert(const at::Half vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = static_cast(vi); s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, at::Half& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = t.as_half; } typedef enum{ MOMENT_MODE_0 =0, // L2 regularization mode MOMENT_MODE_1 =1 // Decoupled weight decay mode } adamMode_t; template struct DistOptLAMBStage1Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<5>& tl, const MATH_T* per_tensor_beta1, const MATH_T* per_tensor_beta2, const MATH_T* per_tensor_beta3, const int* per_tensor_bias_correction, const int* step, const MATH_T* per_tensor_epsilon, adamMode_t mode, const MATH_T* per_tensor_decay, const MATH_T* global_scale, const MATH_T* global_grad_norm, const float max_grad_norm) { // I'd like this kernel to propagate infs/nans. if (*noop_gmem == 1) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float combined_scale = *global_scale; if (max_grad_norm > 0) { combined_scale = max_grad_norm / (*global_grad_norm / *global_scale + 1e-6); combined_scale = *global_scale / std::min((float) 1.0, combined_scale); } MATH_T beta1 = per_tensor_beta1[tensor_num]; MATH_T beta2 = per_tensor_beta2[tensor_num]; MATH_T beta3 = 1 - beta1; MATH_T beta1_correction, beta2_correction; if (per_tensor_bias_correction[tensor_num] == 1) { beta1_correction = 1 - pow(beta1, *step); beta2_correction = 1 - pow(beta2, *step); } else { beta1_correction = (MATH_T) 1.0; beta2_correction = (MATH_T) 1.0; } MATH_T epsilon = per_tensor_epsilon[tensor_num]; MATH_T decay = per_tensor_decay[tensor_num]; GRAD_T* g = (GRAD_T*)tl.addresses[0][tensor_loc]; g += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T*)tl.addresses[2][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T*)tl.addresses[3][tensor_loc]; v += chunk_idx*chunk_size; MATH_T* u = (MATH_T*)tl.addresses[4][tensor_loc]; u += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(g) && is_aligned(p) && is_aligned(m) && is_aligned(v)) { GRAD_T l_g[ILP]; T l_p[ILP]; T l_m[ILP]; T l_v[ILP]; for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load load_store(l_g, g, 0, i_start); if (decay != 0) load_store(l_p, p, 0, i_start); load_store(l_m, m, 0, i_start); load_store(l_v, v, 0, i_start); // unpack #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_g[ii] = l_g[ii]; if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = l_p[ii]; } r_m[ii] = l_m[ii]; r_v[ii] = l_v[ii]; } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / combined_scale; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / combined_scale; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { l_m[ii] = r_m[ii]; l_v[ii] = r_v[ii]; } // store load_store(u, r_p, i_start, 0); load_store(m, l_m, i_start, 0); load_store(v, l_v, i_start, 0); } } else { // see note in multi_tensor_scale_kernel.cu for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_g[ii] = g[i]; // special ?optimization? for lamb stage 1 if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = p[i]; } r_m[ii] = m[i]; r_v[ii] = v[i]; } else { r_g[ii] = MATH_T(0); r_p[ii] = MATH_T(0); r_m[ii] = MATH_T(0); r_v[ii] = MATH_T(0); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / combined_scale; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / combined_scale; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { u[i] = r_p[ii]; m[i] = r_m[ii]; v[i] = r_v[ii]; } } } } } }; // Step 2 reads in 'update' value and per-tensor param_norm and update_norm. // It computes new parameter value. template struct DistOptLAMBStage2Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<3>& tl, const MATH_T* per_tensor_param_norm, const MATH_T* per_tensor_update_norm, const long* update_norm_offset, const MATH_T* learning_rate, const MATH_T* per_tensor_decay, const MATH_T* global_grad_norm, bool use_nvlamb) { // I'd like this kernel to propagate infs/nans. if (*noop_gmem == 1) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; MATH_T decay = per_tensor_decay[tensor_num]; MATH_T ratio = *learning_rate; // nvlamb: apply adaptive learning rate to all parameters // otherwise, only apply to those with non-zero weight decay if (use_nvlamb || (decay != (MATH_T) 0.0)) { MATH_T param_norm = per_tensor_param_norm[tensor_num]; MATH_T update_norm = per_tensor_update_norm[update_norm_offset[tensor_num]]; ratio = (update_norm != 0.0 && param_norm != 0.0) ? (*learning_rate) * (param_norm / update_norm) : (*learning_rate); } MATH_T* update = (MATH_T*)tl.addresses[0][tensor_loc]; update += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; GRAD_T* p_copy = (GRAD_T*)tl.addresses[2][tensor_loc]; p_copy += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(update)) { T r_p[ILP]; MATH_T r_update[ILP]; GRAD_T r_p_copy[ILP]; for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load load_store(r_p, p, 0, i_start); load_store(r_update, update, 0, i_start); #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = static_cast(r_p[ii]) - (ratio * r_update[ii]); convert(r_p[ii], r_p_copy[ii]); } load_store(p, r_p, i_start, 0); load_store(p_copy, r_p_copy, i_start, 0); } } else { for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_p[ILP]; MATH_T r_update[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_p[ii] = p[i]; r_update[ii] = update[i]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = r_p[ii] - (ratio * r_update[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { p[i] = r_p[ii]; convert(r_p[ii], p_copy[i]); } } } } } }; void multi_tensor_lamb_compute_update_term_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_beta3, at::Tensor per_tensor_bias_correction, at::Tensor step, at::Tensor per_tensor_epsilon, const int mode, at::Tensor per_tensor_decay, at::Tensor global_scale, at::Tensor global_grad_norm, const float max_grad_norm) { using namespace at; DISPATCH_FLOAT_AND_HALF(tensor_lists[1][0].scalar_type(), 0, "lamb_stage_1", DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 1, "lamb_stage_1", DISPATCH_FLOAT_AND_HALF(tensor_lists[4][0].scalar_type(), 2, "lamb_stage_1", multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistOptLAMBStage1Functor(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_beta3.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), step.DATA_PTR(), per_tensor_epsilon.DATA_PTR(), (adamMode_t) mode, per_tensor_decay.DATA_PTR(), global_scale.DATA_PTR(), global_grad_norm.DATA_PTR(), max_grad_norm); ))) AT_CUDA_CHECK(cudaGetLastError()); } void multi_tensor_lamb_update_weights_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_param_norm, at::Tensor per_tensor_update_norm, at::Tensor update_norm_offset, at::Tensor learning_rate, at::Tensor per_tensor_decay, at::Tensor global_grad_norm, bool use_nvlamb) { using namespace at; DISPATCH_FLOAT_AND_HALF(tensor_lists[1][0].scalar_type(), 0, "lamb_stage_2", DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[2][0].scalar_type(), 1, "lamb_stage_2", DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 2, "lamb_stage_2", multi_tensor_apply<3>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistOptLAMBStage2Functor(), per_tensor_param_norm.DATA_PTR(), per_tensor_update_norm.DATA_PTR(), update_norm_offset.DATA_PTR(), learning_rate.DATA_PTR(), per_tensor_decay.DATA_PTR(), global_grad_norm.DATA_PTR(), use_nvlamb); ))) AT_CUDA_CHECK(cudaGetLastError()); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/transducer/transducer_joint.cpp ================================================ #include #include #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector transducer_joint_cuda_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize); std::vector transducer_joint_cuda_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale); std::vector transducer_joint_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize) { CHECK_INPUT(f); CHECK_INPUT(g); CHECK_INPUT(fLen); CHECK_INPUT(gLen); if (packOutput) CHECK_INPUT(batchOffset); return transducer_joint_cuda_forward( f, g, fLen, gLen, batchOffset, packedBatch, opt, packOutput, relu, dropout, dropoutProb, tileSize); } std::vector transducer_joint_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale) { for (auto t : in){ CHECK_INPUT(t); } CHECK_INPUT(fLen); CHECK_INPUT(gLen); if (packOutput) CHECK_INPUT(batchOffset); return transducer_joint_cuda_backward( in, fLen, gLen, batchOffset, maxFLen, maxGLen, packOutput, scale); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &transducer_joint_forward, "transducer joint forward (CUDA)"); m.def("backward", &transducer_joint_backward, "transducer joint backward (CUDA)"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/transducer/transducer_joint_kernel.cu ================================================ #include #include #include #include #include #include #include #include #include #include #include "philox.h" // Warp reduce kernels to reduce N groups of data into N numbers, where N = warpSize / width. // width should be a power of 2 and should be less than warpSize. template __device__ __forceinline__ scalar_t warpReduce(scalar_t x, int width=C10_WARP_SIZE){ for (unsigned offset = width/2; offset > 0; offset /= 2){ x += __shfl_down_sync(0xffffffff, x, offset, width); } return x; } inline int largestPowerOfTwo(int x){ int y = 1; while (y <= x) y <<= 1; return y >> 1; } /* Figure out vectorization type for masks. Similar to how PyTorch figures out acc_t here: aten/src/ATen/AccumulateType.h */ template struct MaskVecType { }; template <> struct MaskVecType<1> { using type = uint8_t; }; template <> struct MaskVecType<2> { using type = uint16_t; }; template <> struct MaskVecType<4> { using type = uint32_t; }; template using mvec_type = typename MaskVecType::type; // Helper class to calculate pointer offset that can be shared by different flavors of kernels. // For fwd, batch offset and stride are different for packing and non-packing mode. struct OffsetCalFwd{ __device__ __forceinline__ OffsetCalFwd( int64_t batch, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t gLen, int64_t hiddenSize, bool packOutput) : batch(batch), batchOffset(batchOffset), maxFLen(maxFLen), maxGLen(maxGLen), gLen(gLen), hiddenSize(hiddenSize), packOutput(packOutput) {} int64_t batch; const int64_t *batchOffset; int64_t maxFLen; int64_t maxGLen; int64_t gLen; int64_t hiddenSize; bool packOutput; __device__ __forceinline__ int64_t getBatchOffset(){ return packOutput ? ((batch==0) ? 0 : batchOffset[batch-1])*hiddenSize : batch*maxFLen*maxGLen*hiddenSize; } __device__ __forceinline__ int64_t getStrideF(){ return packOutput ? gLen*hiddenSize : maxGLen*hiddenSize; } }; // Helper class to calculate pointer offset that can be shared by different flavors of kernels // For bwd, batch offset and stride are different for packing and non-packing mode. // The reducion is done for two input tensors. Therefore, generating two sets of offsets // according to bwdFasterDim can lead to a unified implementation in the actual kernel. struct OffsetCalBwd{ __device__ __forceinline__ OffsetCalBwd( int64_t batch, const int64_t *batchOffset, const int *fLen, const int *gLen, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim) : batch(batch), batchOffset(batchOffset), maxFLen(maxFLen), maxGLen(maxGLen), fLen(fLen), gLen(gLen), hiddenSize(hiddenSize), packOutput(packOutput), bwdFasterDim(bwdFasterDim) {} int64_t batch; const int64_t *batchOffset; const int *fLen; const int *gLen; int64_t maxFLen; int64_t maxGLen; int64_t hiddenSize; bool packOutput; bool bwdFasterDim; // whether doing bwd on the faster moving dimension __device__ __forceinline__ int64_t getBatchOffset(){ return packOutput ? ((batch==0) ? 0 : batchOffset[batch-1])*hiddenSize : batch*maxFLen*maxGLen*hiddenSize; } __device__ __forceinline__ int64_t getMaxXLen(){ return bwdFasterDim ? maxGLen : maxFLen; } __device__ __forceinline__ auto getMyXLen() -> decltype(gLen[batch]){ return bwdFasterDim ? gLen[batch] : fLen[batch]; } __device__ __forceinline__ auto getMyYLen() -> decltype(gLen[batch]){ return bwdFasterDim ? fLen[batch] : gLen[batch]; } __device__ __forceinline__ int64_t getStrideX(){ return bwdFasterDim ? hiddenSize : ((packOutput ? gLen[batch] : maxGLen) * hiddenSize); } __device__ __forceinline__ int64_t getStrideY(){ return bwdFasterDim ? ((packOutput ? gLen[batch] : maxGLen) * hiddenSize) : hiddenSize; } }; // Vanila transducer joint forward kernel // Detail of this joint function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // f is a tensor of shape [batch, T, H] // g is a tensor of shape [batch, U, H] // the transducer joint does // sum = f.unsqueeze(dim=2) + g.unsqueeze(dim=1) // The resultant tensor is of shape [batch, T, U, H] // Each thread block is working on one "batch" of data in the output tensor, [batch, t, u, :] // This joint function can optionally pack the output where the output tensor with a shape of // [B, T, U, H] is packed into [B_packed, H]. // Don't-care region (t > fLen) or (u > gLen) is removed. // To enable packing, the starting offset for each batch need to be specified with batchOffset. template __global__ void transducer_joint_forward( const scalar_t *f, const scalar_t *g, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, scalar_t *sum) { const int batch = blockIdx.z; const int t = blockIdx.y; const int u = blockIdx.x; const auto myFLen = fLen[batch]; const auto myGLen = gLen[batch]; OffsetCal offsetCal(batch, batchOffset, maxFLen, maxGLen, myGLen, hiddenSize, packOutput); const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideF = offsetCal.getStrideF(); scalar_t const *myF = f + batch*maxFLen*hiddenSize + t*hiddenSize; scalar_t const *myG = g + batch*maxGLen*hiddenSize + u*hiddenSize; scalar_t *mySum = sum + myBatchOffset + t*strideF + u * hiddenSize; if (t < myFLen and u < myGLen){ #pragma unroll for (int h = threadIdx.x; h < hiddenSize; h += blockDim.x){ if (h < hiddenSize){ mySum[h] = myF[h] + myG[h]; } } } else if (packOutput == false and t < maxFLen and u < maxGLen){ // Need to write finite data to don't-care region because we instantiate the result tensor // with torch::empty for performance reasons. Even though it is don't-care region, the // contents need to be finite, otherwise could lead to NaN in WGRAD. // In packing mode, this write is no longer necessary as we remove the don't-care region // from the output. // Picking -1 (over 0) here for ease of testing. #pragma unroll for (int h = threadIdx.x; h < hiddenSize; h += blockDim.x){ if (h < hiddenSize){ mySum[h] = -1; } } } } /* Tiled version of the joint forward kernel Detail of this joint function can be found in: [1] Sequence Transduction with Recurrent Neural Networks. f is a tensor of shape [batch, T, H] g is a tensor of shape [batch, U, H] the transducer joint does sum = f.unsqueeze(dim=2) + g.unsqueeze(dim=1) The resultant tensor is of shape [batch, T, U, H] Each thread is working on a tile of the shape of tileF x tileG in the result tensor. The input for the tile is first loaded in the register and is reused tileG and tileF times. This joint function can optionally pack the output where the output tensor with a shape of [B, T, U, H] is packed into [B_packed, H]. Don't-care region (t > fLen) or (u > gLen) is removed. To enable packing, the starting offset for each batch need to be specified with batchOffset. Optionally this joint function performs ReLU and/or dropout on the joint output, which is controlled by arguments relu and dropout, respectively. philoxArgs is argument used for generating pseudorandom number. When at least one of operations in ReLU and dropout is activated, the joint function is a masked operation, which is controlled by the template argument masked. In this case, masks are saved to backward. */ template __global__ void transducer_joint_tiled_forward( const scalar_t *f, const scalar_t *g, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, int64_t hiddenPerBlock, bool packOutput, bool relu, bool dropout, float p, at::PhiloxCudaState philoxArgs, scalar_t *sum, uint8_t *mask) { static_assert(U == 4, "U has to be 4, as random numbers are generated in batch of 4"); const int batch = blockIdx.z; const int t = blockIdx.y * tileF; const int hiddenBlock = (hiddenSize + hiddenPerBlock - 1) / hiddenPerBlock; const int u = blockIdx.x / hiddenBlock * tileG; const int hOffset = (blockIdx.x % hiddenBlock) * hiddenPerBlock; const int h = threadIdx.x; const auto myFLen = fLen[batch]; const auto myGLen = gLen[batch]; OffsetCal offsetCal(batch, batchOffset, maxFLen, maxGLen, myGLen, hiddenSize, packOutput); const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideF = offsetCal.getStrideF(); scalar_t const *myF = f + batch*maxFLen*hiddenSize + t*hiddenSize + hOffset; scalar_t const *myG = g + batch*maxGLen*hiddenSize + u*hiddenSize + hOffset; scalar_t *mySum = sum + myBatchOffset + t*strideF + u*hiddenSize + hOffset; uint8_t *myMask = mask + myBatchOffset + t*strideF + u*hiddenSize + hOffset; // The following code is only needed for dropout. We try to bypass them as much as possible. auto seeds = masked ? at::cuda::philox::unpack(philoxArgs) : std::make_tuple(static_cast(0), static_cast(0)); uint64_t tid = masked ? (static_cast(blockIdx.z)*gridDim.y*gridDim.x + blockIdx.y*gridDim.x + blockIdx.x) * blockDim.x + threadIdx.x : 0; Philox ph(std::get<0>(seeds), tid, std::get<1>(seeds)); scalar_t scale = masked ? ((p == 0) ? 0 : 1 / p) : 0; bool dropoutMask[U]; if (t < myFLen and u < myGLen and hOffset+h < hiddenSize){ // register buffers for tiled input reuse scalar_t fBuffer[tileF], gBuffer[tileG]; for (int i = 0; i < tileF; ++i){ if (t + i < myFLen) fBuffer[i] = myF[i*hiddenSize + h]; } for (int j = 0; j < tileG; ++j){ if (u + j < myGLen) gBuffer[j] = myG[j*hiddenSize + h]; } #pragma unroll for (int i = 0; i < tileF; ++i){ if (t + i < myFLen){ #pragma unroll for (int j = 0; j < tileG; ++j){ int idx = i*tileG + j; if (masked and dropout and idx % U == 0){ // For performance, generate 4 random numbers in one shot // auto rand4 = curand_uniform4(&state); auto rand4 = uniform4(ph()); dropoutMask[0] = rand4.x < p; dropoutMask[1] = rand4.y < p; dropoutMask[2] = rand4.z < p; dropoutMask[3] = rand4.w < p; } if (u + j < myGLen){ scalar_t out = fBuffer[i] + gBuffer[j]; if (masked){ // Apply ReLU here when relu is True bool localMask = relu ? (out>0) : 1; localMask = dropout ? localMask & dropoutMask[idx%U] : localMask; out = dropout ? out*localMask*scale : out*localMask; myMask[i*strideF + j*hiddenSize + h] = static_cast(localMask); } mySum[i*strideF + j*hiddenSize + h] = out; } else if (packOutput == false and u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } else if (packOutput == false and t + i < maxFLen){ // Again need to write finite data to don't-care region #pragma unroll for (int j = 0; j < tileG; ++j){ if (u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } } } else if (packOutput == false and t < maxFLen and u < maxGLen and hOffset+h < hiddenSize){ // Only need to ensure the finity in normal mode #pragma unroll for (int i = 0; i < tileF; ++i){ if (t + i < maxFLen){ #pragma unroll for (int j = 0; j < tileG; ++j){ if (u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } } } } /* Bwd operation (reduction) on one input tensor. Since the operation performed for the two input tensors are exactly the same, only one kernel is needed, and the different indexing offsets and strides are handled by OffsetCalBwd. When packing is enabled in the fwd op, unpacking is needed to restore the gradients in a non-packed form. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __device__ void transducer_joint_single_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim, // whether bwd on the faster moving dimension (u) float scale, scalar_t *inGrad, int yBlockOffset=0) { const int batch = blockIdx.z; // For the second input tensor, this offset need to be subtracted because the first yBlockOffset // sets of thread blocks are for the first input tensor. const int x = blockIdx.y-yBlockOffset; const int hOffset = blockIdx.x*C10_WARP_SIZE; const int wid = threadIdx.y; const int lid = threadIdx.x; const int numWarp = blockDim.y; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); OffsetCal offsetCal(batch, batchOffset, fLen, gLen, maxFLen, maxGLen, hiddenSize, packOutput, bwdFasterDim); const auto maxXLen = offsetCal.getMaxXLen(); const auto myXLen = offsetCal.getMyXLen(); const auto myYLen = offsetCal.getMyYLen(); scalar_t *myInGrad = inGrad + batch*maxXLen*hiddenSize + x*hiddenSize + hOffset; if (x < myXLen){ const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideX = offsetCal.getStrideX(); const auto strideY = offsetCal.getStrideY(); const scalar_t *myGrad = grad + myBatchOffset + x*strideX + hOffset; const uint8_t *myMask = masked ? mask + myBatchOffset + x*strideX + hOffset : nullptr; // Each warp reduces numYPerWarp "y" first acc_t warpSum = 0; auto numYPerWarp = (myYLen+numWarp-1)/numWarp; #pragma unroll for (int warpY = 0; warpY < numYPerWarp; ++warpY){ auto y = wid*numYPerWarp + warpY; if (y < myYLen and (hOffset+lid) < hiddenSize) if (masked) warpSum += static_cast(myGrad[y*strideY + lid]) * myMask[y*strideY + lid] * scale; else warpSum += myGrad[y*strideY + lid]; } // transpose partial sum in SMEM and reduce further using warpReduce smem[lid*numWarp + wid] = warpSum; __syncthreads(); auto sum = smem[wid*C10_WARP_SIZE + lid]; sum = warpReduce(sum, numWarp); // a a b b c c d d // a a b b c c d d // a a b b c c d d // a a b b c c d d // example of 4 warps (a, b, c, d) with 8 threads per warp // Each warp need 8 / 4 = 2 threads to write the results. if (hOffset+wid*C10_WARP_SIZE/numWarp+lid/numWarp < hiddenSize){ if (lid % numWarp == 0){ myInGrad[wid*C10_WARP_SIZE/numWarp + lid/numWarp] = sum; } } } else if (wid == 0 and hOffset + lid < hiddenSize){ // Need to ensure the grad is zero for don't care region myInGrad[lid] = 0; } } /* Actual bwd (reduction) kernel get launched. Call transducer_joint_single_backward twice on two input tensors. The two bwd ops are launched together, the first op uses blockIdx.y < maxFLen, and the second op uses the rest. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __global__ void transducer_joint_combined_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, float scale, scalar_t *fGrad, scalar_t *gGrad) { if (blockIdx.y < maxFLen){ transducer_joint_single_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, false, scale, fGrad); } else{ transducer_joint_single_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, true, scale, gGrad, maxFLen); } } /* Vectorized version of transducer_joint_single_backward Doing exact same operation as transducer_joint_single_backward except the load and store are vectorized. When packing is enabled in the fwd op, unpacking is needed to restore the gradients in a non-packed form. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __device__ void transducer_joint_single_vec_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim, float scale, scalar_t *inGrad, int yBlockOffset=0){ const int batch = blockIdx.z; const int x = blockIdx.y - yBlockOffset; const int hOffset = blockIdx.x*C10_WARP_SIZE*V; const int wid = threadIdx.y; const int lid = threadIdx.x; const int numWarp = blockDim.y; // Figure out the vectorization type for mask using mvec_t = mvec_type; OffsetCal offsetCal(batch, batchOffset, fLen, gLen, maxFLen, maxGLen, hiddenSize, packOutput, bwdFasterDim); const auto maxXLen = offsetCal.getMaxXLen(); const auto myXLen = offsetCal.getMyXLen(); const auto myYLen = offsetCal.getMyYLen(); scalar_t *myInGrad = inGrad + batch*maxXLen*hiddenSize + x*hiddenSize + hOffset; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); acc_t warpSum[V]; scalar_t inBuffer[V]; uint8_t maskBuffer[V]; scalar_t outBuffer[V]; auto myInGradVec = reinterpret_cast(myInGrad); auto outBufferVec = reinterpret_cast(outBuffer); if (x < myXLen){ const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideX = offsetCal.getStrideX(); const auto strideY = offsetCal.getStrideY(); const scalar_t *myGrad = grad + myBatchOffset + x*strideX + hOffset; const uint8_t *myMask = masked ? mask + myBatchOffset + x*strideX + hOffset :nullptr; for (int i = 0; i < V; ++i) warpSum[i] = 0; // Each warp reduces numYPerWarp "y" first auto numYPerWarp = (myYLen+numWarp-1)/numWarp; for (int warpY = 0; warpY < numYPerWarp; ++warpY){ auto y = wid*numYPerWarp + warpY; auto myGradVec = reinterpret_cast(myGrad + y*strideY); auto myMaskVec = masked ? reinterpret_cast(myMask + y*strideY) : nullptr; auto inBufferVec = reinterpret_cast(inBuffer); auto maskBufferVec = reinterpret_cast(maskBuffer); if (hOffset + lid*V < hiddenSize and y < myYLen){ *inBufferVec = myGradVec[lid]; // vectorized load if (masked){ *maskBufferVec = myMaskVec[lid]; #pragma unroll for (int i = 0; i < V; ++i) warpSum[i] += static_cast(inBuffer[i]) * maskBuffer[i] * scale; } else{ #pragma unroll for (int i = 0; i < V; ++i) warpSum[i] += inBuffer[i]; } } } // transpose partial sum in SMEM and reduce further using warpReduce for (int i = 0; i < V; ++i){ smem[lid*numWarp + wid] = warpSum[i]; __syncthreads(); auto sum = smem[wid*C10_WARP_SIZE + lid]; if (hOffset+(wid*C10_WARP_SIZE/numWarp)*V < hiddenSize){ sum = warpReduce(sum, numWarp); if (lid % numWarp == 0){ outBuffer[i] = sum; } } __syncthreads(); } // a a b b c c d d // a a b b c c d d // a a b b c c d d // a a b b c c d d // example of 4 warps (a, b, c, d) with 8 threads per warp // Each warp need 8 / 4 = 2 threads to write the results. if (lid % numWarp == 0 and hOffset+(wid*C10_WARP_SIZE/numWarp + lid/numWarp)*V < hiddenSize) myInGradVec[wid*C10_WARP_SIZE/numWarp + lid/numWarp] = *outBufferVec; } else if (wid == 0 and hOffset + lid*V < hiddenSize){ // Need to ensure the grad is zero for don't care region myInGradVec[lid] = 0; } } /* Vecotrized version of transducer_joint_combined_backward Call transducer_joint_single_vec_backward twice on two input tensors. The two bwd ops are launched together, the first op uses blockIdx.y < maxFLen, and the second op uses the rest. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __global__ void transducer_joint_combined_vec_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, float scale, scalar_t *fGrad, scalar_t *gGrad) { if (blockIdx.y < maxFLen){ transducer_joint_single_vec_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, false, scale, fGrad); } else{ transducer_joint_single_vec_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, true, scale, gGrad, maxFLen); } } std::vector transducer_joint_cuda_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize){ auto tensorOpt = f.options(); auto dtype = f.scalar_type(); const auto batchSize = f.size(0); const auto maxFLen = f.size(1); const auto maxGLen = g.size(1); const auto hiddenSize = f.size(2); bool masked = dropout or relu; int64_t *batchOffsetPtr = nullptr; torch::Tensor sum, mask; auto maskOpt = tensorOpt.dtype(torch::kUInt8); if (!packOutput){ sum = torch::empty({batchSize, maxFLen, maxGLen, hiddenSize}, tensorOpt); batchOffsetPtr = nullptr; if (masked) mask = torch::empty({batchSize, maxFLen, maxGLen, hiddenSize}, maskOpt); } else{ sum = torch::empty({packedBatch, hiddenSize}, tensorOpt); batchOffsetPtr = batchOffset.data_ptr(); if (masked) mask = torch::empty({packedBatch, hiddenSize}, maskOpt); } uint8_t *maskPtr = masked ? mask.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); TORCH_CHECK(opt == 0 or opt == 1, "Got an invalid optimization level ", opt); // Simple heuristics const int numThread = std::min(128, (static_cast(hiddenSize)+C10_WARP_SIZE-1) / C10_WARP_SIZE * C10_WARP_SIZE); if (opt == 0){ // vanilla kernel const int threads = numThread; const dim3 blocks(maxGLen, maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_forward", ([&] { transducer_joint_forward <<>>( f.data_ptr(), g.data_ptr(), fLen.data_ptr(), gLen.data_ptr(), batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, sum.data_ptr()); })); } if (opt == 1){ // tiled version. For simplicity, assume tileF == tileG, even though the kernel can // support more general cases. const int threads = numThread; const int hiddenPerBlock = numThread; const int hiddenBlock = (hiddenSize + hiddenPerBlock - 1) / hiddenPerBlock; const dim3 blocks( (maxGLen+tileSize-1)/tileSize * hiddenBlock, (maxFLen+tileSize-1)/tileSize, batchSize); TORCH_CHECK(tileSize == 1 or tileSize == 2 or tileSize == 4, "Expected tileSize to be in [1, 2, 4], but got ", tileSize); at::PhiloxCudaState rng_engine_inputs; if (masked){ // set up PRG when the input is masked. rng_engine_inputs will be used as a space filler // for non-masked calls. // Therefore no need to initialize. c10::optional gen_; auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); // counterOffset records how many cuRAND calls each thread makes. For a tiled kernel, // each thread processes tileF * tileG output elements. int64_t counterOffset = tileSize * tileSize; { std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_cuda_state(counterOffset); } } AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_forward", ([&] { void(*kernel)(const scalar_t*, const scalar_t*, const int*, const int*, const int64_t*, int64_t, int64_t, int64_t, int64_t, bool, bool, bool, float, at::PhiloxCudaState, scalar_t*, uint8_t*); if (masked){ switch (tileSize){ case 2: kernel = &transducer_joint_tiled_forward; break; case 4: kernel = &transducer_joint_tiled_forward; break; } } else{ switch (tileSize){ case 1: kernel = &transducer_joint_tiled_forward; break; case 2: kernel = &transducer_joint_tiled_forward; break; case 4: kernel = &transducer_joint_tiled_forward; break; } } kernel<<>>( f.data_ptr(), g.data_ptr(), fLen.data_ptr(), gLen.data_ptr(), batchOffsetPtr, maxFLen, maxGLen, hiddenSize, hiddenPerBlock, packOutput, relu, dropout, 1.0f - dropoutProb, rng_engine_inputs, sum.data_ptr(), maskPtr); })); } THCudaCheck(cudaGetLastError()); if (masked) return {sum, mask}; else return {sum}; } std::vector transducer_joint_cuda_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale){ auto grad = in[0]; bool masked = (in.size() == 2); uint8_t *maskPtr = masked ? in[1].data_ptr() : nullptr; auto tensorOpt = grad.options(); auto dtype = grad.scalar_type(); const int batchSize = fLen.size(0); const int hiddenSize = grad.size(-1); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const int maxNumWarp = deviceProperties->maxThreadsPerBlock / C10_WARP_SIZE; torch::Tensor fGrad = torch::empty({batchSize, maxFLen, hiddenSize}, tensorOpt); torch::Tensor gGrad = torch::empty({batchSize, maxGLen, hiddenSize}, tensorOpt); int64_t *batchOffsetPtr = (!packOutput) ? nullptr : batchOffset.data_ptr(); // The number "y" I would like each thread to work on const int workPerThread = 32; // Since the bwd for f and g have the same thread block size, we need to use the max of the two. int numWarp = largestPowerOfTwo((std::max(maxFLen, maxGLen) + workPerThread-1) / workPerThread); // Would like to have at least 2 warps numWarp = std::max(2, numWarp); // cap on the maximum number of warps allowed numWarp = std::min(maxNumWarp, numWarp); // Need smem for transposing the partial sum. The partial sum is in a matrix of the shape // numWarp x warpSize const int smemSize = numWarp * C10_WARP_SIZE; const dim3 threads(C10_WARP_SIZE, numWarp, 1); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_cuda_backward_kernel", ([&] { auto gradPtr = grad.data_ptr(); auto fLenPtr = fLen.data_ptr(); auto gLenPtr = gLen.data_ptr(); auto fGradPtr = fGrad.data_ptr(); auto gGradPtr = gGrad.data_ptr(); // resolve the acc_t type using acc_t = at::acc_type; using vec_t = uint64_t; constexpr int vectFactor = sizeof(vec_t) / sizeof(scalar_t); constexpr int vecAlignment = std::alignment_of::value; // if all input and output tensors meet the alignment requirement bool memAlign = (reinterpret_cast(gradPtr) % vecAlignment == 0) and (reinterpret_cast(fGradPtr) % vecAlignment == 0) and (reinterpret_cast(gGradPtr) % vecAlignment == 0); if (vectFactor > 1 and hiddenSize%vectFactor == 0 and memAlign){ // If vectorization helps and the alignment requirement is met, use the vectorized // kernel. For simplicity, hiddenSize needs to be a multiple vecFactor. const dim3 blocks( (hiddenSize+C10_WARP_SIZE*vectFactor-1)/(C10_WARP_SIZE*vectFactor), maxFLen+maxGLen, batchSize); if (masked){ transducer_joint_combined_vec_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } else{ transducer_joint_combined_vec_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } } else{ const dim3 blocks((hiddenSize+C10_WARP_SIZE-1)/C10_WARP_SIZE, maxFLen + maxGLen, batchSize); if (masked){ transducer_joint_combined_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } else{ transducer_joint_combined_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } } })); return {fGrad, gGrad}; } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/transducer/transducer_loss.cpp ================================================ #include #include #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector transducer_loss_cuda_forward( torch::Tensor x, torch::Tensor label, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput); torch::Tensor transducer_loss_cuda_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput); std::vector transducer_loss_forward( torch::Tensor x, torch::Tensor label, torch::Tensor fLen, torch::Tensor yLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput ) { CHECK_INPUT(x); CHECK_INPUT(label); CHECK_INPUT(fLen); CHECK_INPUT(yLen); if (packedInput) CHECK_INPUT(batchOffset); return transducer_loss_cuda_forward( x, label, fLen, yLen, batchOffset, maxFLen, blankIdx, opt, packedInput); } torch::Tensor transducer_loss_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor fLen, torch::Tensor yLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput){ CHECK_INPUT(x); CHECK_INPUT(label); CHECK_INPUT(lossGrad); CHECK_INPUT(alpha); CHECK_INPUT(beta); CHECK_INPUT(fLen); CHECK_INPUT(yLen); if (packedInput) CHECK_INPUT(batchOffset); return transducer_loss_cuda_backward( x, lossGrad, alpha, beta, fLen, yLen, label, batchOffset, maxFLen, blankIdx, opt, fuseSoftmaxBackward, packedInput); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &transducer_loss_forward, "transducer loss forward (CUDA)"); m.def("backward", &transducer_loss_backward, "transducer loss backward (CUDA)"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/transducer/transducer_loss_kernel.cu ================================================ #include #include #include #include #include #include #include #include template __device__ __forceinline__ scalar_t logSumExp(scalar_t a, scalar_t b) { // standard log-sum-exp trick is used here to provide better numerical stability return (a >= b) ? a + std::log1p(exp(b-a)) : b + std::log1p(exp(a-b)); } // Vanilla transducer loss function (i.e. forward-backward algorithm) // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // Forward (alpha) and backward (beta) path are launched together. Input is assumed to be converted // into log scale by the preceding log_softmax layer // Diagonal wavefront advancing usually used in dynamic programming is leveraged here. // alpha and beta are of acc_t type, as they are essentially accumulators. // This loss function supports packed input where a tensor of shape [B, T, U, H] is packed into // [B_packed, H]. // Don't-care region (t > audLen) or (u > txtLen) is removed. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_forward( const scalar_t* x, const int* label, const int* audLen, const int* txtLen, const int64_t* batchOffset, int64_t dictSize, // 64-bit indexing for data tensor int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, acc_t* alpha, acc_t* beta, scalar_t* loss) { const int batch = blockIdx.y; const int tid = threadIdx.x; const auto myFLen = audLen[batch]; // Note that start of the sentence is added as 1 here const auto myGLen = txtLen[batch] + 1; const auto myLabel = label + batch * (maxGLen-1); const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; const scalar_t* myX = x + myBatchOffset * dictSize; int u = tid; if (blockIdx.x == 0){ // alpha path acc_t* myAlpha = alpha + batch*maxFLen*maxGLen; if (u == 0) myAlpha[0] = 0; __syncthreads(); for (int64_t step = 1; step < myFLen+myGLen-1; ++step){ // Move along the diagonal wavefront to leverage available parallelism for (u = tid; u < myGLen; u += blockDim.x){ int64_t t = step - u; if (t >= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(16) in [1] if (u == 0){ // alpha(t, u) = alpha(t-1, u) * null(t-1, u) myAlpha[t*maxGLen + u] = myAlpha[(t-1)*maxGLen] + myX[((t-1)*myStrideT) * dictSize + blankIdx]; } else if (t == 0){ // alpha(t, u-1) = alpha(t, u-1) * y(t, u-1) myAlpha[u] = myAlpha[u - 1] + myX[(u - 1) * dictSize + myLabel[u - 1]]; } else{ // alpha(t, u) = alpha(t-1, u) * null(t-1, u) + alpha(t, u-1) * y(t, u-1) acc_t current = myAlpha[(t-1)*maxGLen + u] + myX[((t-1)*myStrideT + u) * dictSize + blankIdx]; acc_t next = myAlpha[t*maxGLen + u - 1] + myX[(t*myStrideT + u - 1) * dictSize + myLabel[u - 1]]; myAlpha[t*maxGLen + u] = logSumExp(next, current); } } } __syncthreads(); } } else if (blockIdx.x == 1){ // beta path acc_t* myBeta = beta + batch*maxFLen*maxGLen; if (u == 0){ myBeta[(myFLen-1)*maxGLen + myGLen - 1] = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; } __syncthreads(); for (int64_t step = myFLen+myGLen - 3; step >= 0; --step){ for (u = tid; u < myGLen; u += blockDim.x){ int64_t t = step - u; if (t >= 0 and t < myFLen and u >=0 and u < myGLen){ // Eq(18) in [1] if (u == myGLen - 1){ // beta(t, u) = beta(t+1, u) * null(t, u) myBeta[t*maxGLen + u] = myBeta[(t+1)*maxGLen + u] + myX[(t*myStrideT + u) * dictSize + blankIdx]; } else if (t == myFLen - 1){ // beta(t, u) = beta(t, u+1) * y(t, u) myBeta[t*maxGLen + u] = myBeta[t*maxGLen + u + 1] + myX[(t*myStrideT + u) * dictSize + myLabel[u]]; } else{ // beta(t, u) = beta(t+1, u)*null(t, u) + beta(t, u+1)*y(t, u) acc_t current = myBeta[(t+1)*maxGLen + u] + myX[(t*myStrideT + u) * dictSize + blankIdx]; acc_t next = myBeta[t*maxGLen + u + 1] + myX[(t*myStrideT + u) * dictSize + myLabel[u]]; myBeta[t*maxGLen + u] = logSumExp(next, current); } } } __syncthreads(); } if (tid == 0) loss[batch] = -myBeta[0]; } } // transudcer loss function (i.e. forward-backward algorithm) with batch loading optimization. // Compared to the vanilla version, there are two optimizations: // 1. load x in batch through loop unrolling to reduce the latency. // 2. Use registers and shared memory to hold alpha and beta values passed from one step the next. // For simplicity, this kernel currently only supports U <= maxThread, which should be the common // case. For cases where U > maxThread, the vanilla kernel is used as a fallback option. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // Forward (alpha) and backward (beta) path are launched together. Input is assumed to be converted // into log scale by the preceding log_softmax layer // Diagonal wavefront advancing usually used in dynamic programming is leveraged here. // alpha and beta are of acc_t type, as they are essentially accumulators. // This loss function supports packed input where a tensor of shape [B, T, U, H] is packed into // [B_packed, H]. // Don't-care region (t > audLen) or (u > txtLen) is removed. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_batch_load_forward( const scalar_t* x, const int* label, const int* audLen, const int* txtLen, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, acc_t* alpha, acc_t* beta, scalar_t* loss) { const int batch = blockIdx.y; int u = threadIdx.x; const auto myFLen = audLen[batch]; const auto myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; const scalar_t* myX = x + myBatchOffset * dictSize; scalar_t next[batchLdSize], current[batchLdSize]; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); if (blockIdx.x == 0){ // alpha path acc_t* myAlpha = alpha + batch*maxFLen*maxGLen; // two SMEM regions for double buffering read and write data to avoid data race acc_t * const sharedAlpha[2] = {smem, smem+maxGLen}; sharedAlpha[0][u] = 0; __syncthreads(); if (u == 0) myAlpha[0] = 0; auto myAlphaLabel = (u == 0) ? 0 : label[batch*(maxGLen-1) + u - 1]; // register used to pass value to the next step for the same thread acc_t prvStepAlpha = 0; for (int64_t step = 1; step < myFLen+myGLen-1+batchLdSize; step += batchLdSize){ // Move along the diagonal wavefront to leverage available parallelism // Batch loading X through loop unrolling #pragma unroll for (int i = 0; i < batchLdSize; ++i){ if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ if (u == 0){ current[i] = myX[currentId]; } else if (t == 0){ next[i] = myX[nextId]; } else{ current[i] = myX[currentId]; next[i] = myX[nextId]; } } } } // main computing loop for (int i = 0; i < batchLdSize; ++i){ // swap the pointer for double buffering auto sharedAlphaRd = sharedAlpha[(step+i-1)%2]; auto sharedAlphaWr = sharedAlpha[(step+i)%2]; if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(16) in [1] if (u == 0) prvStepAlpha = prvStepAlpha+current[i]; else if (t == 0) prvStepAlpha = sharedAlphaRd[u-1]+next[i]; else prvStepAlpha = logSumExp(prvStepAlpha+current[i], sharedAlphaRd[u-1] + next[i]); sharedAlphaWr[u] = prvStepAlpha; myAlpha[t*maxGLen + u] = prvStepAlpha; } } __syncthreads(); } } } else if (blockIdx.x == 1){ // beta path acc_t* myBeta = beta + batch*maxFLen*maxGLen; // two SMEM regions for double buffering read and write data to avoid data race acc_t * const sharedBeta[2] = {smem, smem + maxGLen}; sharedBeta[0][u] = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; __syncthreads(); auto myBetaLabel = (u == maxGLen - 1) ? 0 : label[batch*(maxGLen-1) + u]; // register used to pass value to the next step for the same thread acc_t prvStepBeta = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; if (u == 0) myBeta[(myFLen-1)*maxGLen + myGLen - 1] = prvStepBeta; for (int64_t step = 1; step < myFLen+myGLen-1; step += batchLdSize){ // Move along the diagonal wavefront to leverage available parallelism // Batch loading X #pragma unroll for (int i = 0; i < batchLdSize; ++i){ if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ if (u == myGLen - 1){ current[i] = myX[currentId]; } else if (t == myFLen - 1){ next[i] = myX[nextId]; } else{ current[i] = myX[currentId]; next[i] = myX[nextId]; } } } } // main computing loop for (int i = 0; i < batchLdSize; ++i){ // swap the pointer for double buffering auto sharedBetaRd = sharedBeta[(step+i-1)%2]; auto sharedBetaWr = sharedBeta[(step+i)%2]; if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(18) in [1] if (u == myGLen - 1) prvStepBeta = prvStepBeta+current[i]; else if (t == myFLen - 1) prvStepBeta = sharedBetaRd[u+1]+next[i]; else prvStepBeta = logSumExp(prvStepBeta+current[i], sharedBetaRd[u+1] + next[i]); sharedBetaWr[u] = prvStepBeta; myBeta[t*maxGLen + u] = prvStepBeta; } } __syncthreads(); } } if (u == 0) loss[batch] = -prvStepBeta; } } // Vanilla transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // For this backward kernel, bwd op for the preceding softmax is assumed to be handled elsewhere, // hence only Eq(20) in [1] is implemented in this kernel. // Each thread block works on [batch, t, :, :] of data. Each thread works on a specific u at a time // Since only gradients for the correct token and null token need to be updated, gradients at other // locations are initialized to 0. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int t = blockIdx.x; const int batch = blockIdx.y; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; auto myX = x + (myBatchOffset + t*myStrideT)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT)*dictSize; auto myLabel = label + batch*(maxGLen-1); int64_t u = tid; while (t < myFLen and u < myGLen){ // Do the update // loss = -ln(Pr(y*|x)) acc_t grad = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; if (u != myGLen - 1) myXGrad[u*dictSize + myLabel[u]] = -std::exp(grad + myBeta[t*maxGLen + u + 1] + myX[u*dictSize + myLabel[u]]); if (t == myFLen - 1 and u == myGLen - 1) myXGrad[u*dictSize + blankIdx] = -std::exp(grad + myX[u*dictSize + blankIdx]); else if (t != myFLen - 1) myXGrad[u*dictSize + blankIdx] = -std::exp(grad + myBeta[(t+1)*maxGLen + u] + myX[u*dictSize + blankIdx]); u += blockDim.x; } } // Fused transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // The bwd op of the preceding softmax layer is fused in this kernel. // Each thread block works on [batch, t, u, :] of data. Each thread works on a specific h at a time // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_fused_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int u = blockIdx.x; const int t = blockIdx.y; const int batch = blockIdx.z; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; __shared__ acc_t commonFactor, myBetaTU, myBetaTUp1, myBetaTp1U, myLabelShared; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT +u)*dictSize; if (t < myFLen and u < myGLen){ auto myX = x + (myBatchOffset + t*myStrideT +u)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myLabel = label + batch*(maxGLen-1); // load and store shared variables in SMEM if (tid == 0){ commonFactor = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; myBetaTU = myBeta[t*maxGLen + u]; myBetaTUp1 = myBeta[t*maxGLen + u + 1]; myBetaTp1U = myBeta[(t+1)*maxGLen + u]; myLabelShared = myLabel[u]; } __syncthreads(); for (int64_t h = tid; h < dictSize; h += blockDim.x){ // Do the update acc_t grad = commonFactor + myX[h]; // loss = -ln(Pr(y*|x)) acc_t myGrad = std::exp(grad + myBetaTU); if (u != myGLen - 1 and h == myLabelShared){ myGrad -= std::exp(grad + myBetaTUp1); } else if (h == blankIdx){ if (t == myFLen - 1 and u == myGLen - 1) myGrad -= std::exp(grad); else if (t != myFLen - 1) myGrad -= std::exp(grad + myBetaTp1U); } myXGrad[h] = myGrad; } } else if (!packedInput){ // In non-pack mode, need to make sure the gradients for don't-care regions are zero. for (int64_t h = tid; h < dictSize; h += blockDim.x){ myXGrad[h] = 0; } } } // Vectorized version of fused transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // The bwd op of the preceding softmax layer is fused in this kernel. // Each thread block works on [batch, t, u, :] of data. Each thread works on a specific h at a time // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_fused_vec_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int u = blockIdx.x; const int t = blockIdx.y; const int batch = blockIdx.z; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; __shared__ acc_t commonFactor, myBetaTU, myBetaTUp1, myBetaTp1U, myLabelShared; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT +u)*dictSize; auto myX = x + (myBatchOffset + t*myStrideT +u)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myLabel = label + batch*(maxGLen-1); // Variabels for vectorization scalar_t myXBuffer[V], myXGradBuffer[V]; auto myXVec = reinterpret_cast(myX); auto myXGradVec = reinterpret_cast(myXGrad); auto myXBufferVec = reinterpret_cast(myXBuffer); auto myXGradBufferVec = reinterpret_cast(myXGradBuffer); if (t < myFLen and u < myGLen){ // load and store shared variables in SMEM if (tid == 0){ commonFactor = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; myBetaTU = myBeta[t*maxGLen + u]; if (t != myFLen - 1) myBetaTp1U = myBeta[(t+1)*maxGLen + u]; if (u != myGLen - 1){ myBetaTUp1 = myBeta[t*maxGLen + u + 1]; myLabelShared = myLabel[u]; } } __syncthreads(); #pragma unroll for (int64_t h0 = tid*V; h0 < dictSize; h0 += blockDim.x*V){ // Load myX in a vector form *myXBufferVec = myXVec[h0/V]; // Do the update for a vector of input #pragma unroll for (int i = 0; i < V; ++i){ auto h = h0 + i; acc_t grad = commonFactor + myXBuffer[i]; // loss = -ln(Pr(y*|x)) acc_t myGrad = std::exp(grad + myBetaTU); if (u != myGLen - 1 and h == myLabelShared){ myGrad -= std::exp(grad + myBetaTUp1); } else if (h == blankIdx){ if (t == myFLen - 1 and u == myGLen - 1) myGrad -= std::exp(grad); else if (t != myFLen - 1) myGrad -= std::exp(grad + myBetaTp1U); } myXGradBuffer[i] = myGrad; } // Store myXGrad in a vector form myXGradVec[h0/V] = *myXGradBufferVec; } } else if (!packedInput){ // In non-pack mode, need to make sure the gradients for don't-care regions are zero. for (int64_t h0 = tid*V; h0 < dictSize; h0 += blockDim.x*V){ myXGradVec[h0/V] = 0; } } } std::vector transducer_loss_cuda_forward( torch::Tensor x, torch::Tensor label, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput){ auto scalarType = x.scalar_type(); auto tensorOpt = x.options(); const int batchSize = label.size(0); const int maxGLen = label.size(1) + 1; const int dictSize = x.size(-1); TORCH_CHECK(blankIdx >= 0 and blankIdx < dictSize, "Expected blank index to be in the range of 0 to ", dictSize-1, ", but got ", blankIdx); TORCH_CHECK(opt == -1 or opt == 0 or opt == 1, "Got an invalid optimization level ", opt); // The data type of alpha and beta will be resolved at dispatch time, // hence defined here and assigned later torch::Tensor alpha; torch::Tensor beta; torch::Tensor loss = torch::empty({batchSize}, tensorOpt); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const auto maxThreadPerBlock = deviceProperties->maxThreadsPerBlock; const auto maxSmemPerBlock = deviceProperties->sharedMemPerBlock; const auto batchOffsetPtr = packedInput ? batchOffset.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); AT_DISPATCH_FLOATING_TYPES_AND_HALF(scalarType, "transducer_loss_cuda_forward", ([&] { // resolve accumulation type using acc_t = at::acc_type; auto accType = c10::CppTypeToScalarType::value; auto accTensorOpt = tensorOpt.dtype(accType); alpha = torch::empty({batchSize, maxFLen, maxGLen}, accTensorOpt); beta = torch::empty({batchSize, maxFLen, maxGLen}, accTensorOpt); // decide what kernel to launch based on the problem size // if the required SMEM size or number threads exceeds the limit, fall back to the vanilla // kernel. const auto smemSize = 2*maxGLen*sizeof(acc_t); const auto optFallBack = (maxGLen > maxThreadPerBlock or smemSize > maxSmemPerBlock) ? 0 : (opt == -1) ? 1 : opt; const int threads = std::min(maxThreadPerBlock, maxGLen); const dim3 blocks(2, batchSize, 1); if (optFallBack == 0) transducer_loss_forward<<>>( x.data_ptr(), label.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, alpha.data_ptr(), beta.data_ptr(), loss.data_ptr()); else if (optFallBack == 1) transducer_loss_batch_load_forward <<>>( x.data_ptr(), label.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, alpha.data_ptr(), beta.data_ptr(), loss.data_ptr()); })); THCudaCheck(cudaGetLastError()); return {alpha, beta, loss}; } torch::Tensor transducer_loss_cuda_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput){ auto dtype = x.scalar_type(); torch::Tensor xGrad; const int batchSize = label.size(0); const int maxGLen = label.size(1) + 1; const int dictSize = x.size(-1); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const int maxThreadPerBlock = deviceProperties->maxThreadsPerBlock; const int warpSize = deviceProperties->warpSize; const auto batchOffsetPtr = packedInput ? batchOffset.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (fuseSoftmaxBackward){ // alloc empty tensors for performance, hence need to ensure zeros are writtern to // don't-care region in the kernel. xGrad = torch::empty_like(x); // Would like each thread to work on 4 hidden units const int workPerThread = 4; // Don't want to have more than 128 threads per thread block const int maxThreadPerElmt = std::min(128, maxThreadPerBlock); const int threads = std::min(maxThreadPerElmt, std::max(warpSize, (dictSize+workPerThread-1)/workPerThread)); const dim3 blocks(maxGLen, maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_loss_cuda_backward", ([&] { using vec_t = uint64_t; using acc_t = at::acc_type; constexpr int vectFactor = sizeof(vec_t) / sizeof(scalar_t); constexpr int vecAlignment = std::alignment_of::value; // if all input and output tensors meet the alignment requirement bool memAlign = reinterpret_cast(x.data_ptr()) % vecAlignment == 0 and reinterpret_cast(xGrad.data_ptr()) % vecAlignment == 0; if (vectFactor > 1 and dictSize%vectFactor == 0 and memAlign){ transducer_loss_fused_vec_backward <<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); } else{ transducer_loss_fused_backward<<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); } })); } else{ // for non-fused kernel, the gradients need to be writtern are very sparse, hence initialize // the tensor with all zeros. xGrad = torch::zeros_like(x); // don't launch more threads than needed. const int threads = std::min(maxThreadPerBlock, maxGLen); const dim3 blocks(maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_loss_cuda_backward", ([&] { using acc_t = at::acc_type; transducer_loss_backward<<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); })); } THCudaCheck(cudaGetLastError()); return xGrad; } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/xentropy/interface.cpp ================================================ #include // CUDA forward declarations std::vector softmax_xentropy_cuda( const at::Tensor &input, const at::Tensor &labels, const float smoothing, const bool half_to_float); at::Tensor softmax_xentropy_backward_cuda( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector softmax_xentropy_forward( const at::Tensor &input, const at::Tensor &labels, const float smoothing, const bool half_to_float) { CHECK_CUDA(input); CHECK_INPUT(labels); return softmax_xentropy_cuda(input, labels, smoothing, half_to_float); } at::Tensor softmax_xentropy_backward( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing) { CHECK_CUDA(grad_loss); CHECK_CUDA(logits); CHECK_INPUT(max_log_sum_exp); CHECK_INPUT(labels); return softmax_xentropy_backward_cuda(grad_loss, logits, max_log_sum_exp, labels, smoothing); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &softmax_xentropy_forward, "Softmax cross entropy loss with label smoothing forward (CUDA)"); m.def("backward", &softmax_xentropy_backward, "Softmax cross entropy loss with label smoothing backward (CUDA)"); } ================================================ FILE: KoSentenceT5/apex/contrib/csrc/xentropy/xentropy_kernel.cu ================================================ /** * From PyTorch: * * Copyright (c) 2016- Facebook, Inc (Adam Paszke) * Copyright (c) 2014- Facebook, Inc (Soumith Chintala) * Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) * Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) * Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) * Copyright (c) 2011-2013 NYU (Clement Farabet) * Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) * Copyright (c) 2006 Idiap Research Institute (Samy Bengio) * Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) * * From Caffe2: * * Copyright (c) 2016-present, Facebook Inc. All rights reserved. * * All contributions by Facebook: * Copyright (c) 2016 Facebook Inc. * * All contributions by Google: * Copyright (c) 2015 Google Inc. * All rights reserved. * * All contributions by Yangqing Jia: * Copyright (c) 2015 Yangqing Jia * All rights reserved. * * All contributions from Caffe: * Copyright(c) 2013, 2014, 2015, the respective contributors * All rights reserved. * * All other contributions: * Copyright(c) 2015, 2016 the respective contributors * All rights reserved. * * Caffe2 uses a copyright model similar to Caffe: each contributor holds * copyright over their contributions to Caffe2. The project versioning records * all such contribution and copyright details. If a contributor wants to further * mark their specific copyright on a particular contribution, they should * indicate their copyright solely in the commit message of the change when it is * committed. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America * and IDIAP Research Institute nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include "type_shim.h" #include "compat.h" #define ALIGN_BYTES 16 using Tensor = at::Tensor; using TensorList = at::TensorList; using ScalarType = at::ScalarType; using at::acc_type; template struct LogSoftMaxForwardEpilogue { __device__ __forceinline__ LogSoftMaxForwardEpilogue(AccumT max_input, AccumT sum) : logsum(max_input + std::log(sum)) {} __device__ __forceinline__ LogSoftMaxForwardEpilogue(AccumT max_log_sum_exp) : logsum(max_log_sum_exp) {} __device__ __forceinline__ OutT operator()(T input) const { return static_cast(input - logsum); } const AccumT logsum; }; template struct LogSoftMaxBackwardEpilogue { __device__ __forceinline__ LogSoftMaxBackwardEpilogue(AccumT sum) : sum(sum) {} __device__ __forceinline__ T operator()(OutT gradOutput, OutT output) const { return static_cast(gradOutput - std::exp(static_cast(output)) * sum); } const AccumT sum; }; const int max_threads = 1024; inline dim3 SoftMax_getBlockSize(int ILP, uint64_t dim_size) { uint64_t block_size = 1; uint64_t max_block_size = std::min(dim_size / ILP, static_cast(max_threads)); while (block_size < (max_block_size/2)) block_size *= 2; // Launch at least a single warp - the kernel assumes that. block_size = std::max(block_size, static_cast(32)); return dim3(block_size); } template struct Add { __device__ __forceinline__ T operator()(T a, T b) const { return a + b; } }; template struct Max { __device__ __forceinline__ T operator()(T a, T b) const { return a < b ? b : a; } }; //////////////////////////////////////////////////////////////////////////////// // Regular kernel (fast when dim_size is large; requires inner_size == 1) //////////////////////////////////////////////////////////////////////////////// template struct MaxFloat { __device__ __forceinline__ AccumT operator()(AccumT max, T v) const { return ::max(max, (AccumT)v); } }; template struct AddFloat { __device__ __forceinline__ AccumT operator()(AccumT sum, T v) const { return sum + v; } }; template struct SumExpFloat { __device__ __forceinline__ SumExpFloat(AccumT v) : max_k(v) {} __device__ __forceinline__ AccumT operator()(AccumT sum, T v) const { return sum + std::exp(v - max_k); } const AccumT max_k; }; template class Reduction, typename AccumT> __device__ __forceinline__ AccumT blockReduce(AccumT* smem, AccumT val, const Reduction& r, AccumT defaultVal) { // To avoid RaW races from chaining blockReduce calls together, we need a sync here __syncthreads(); smem[threadIdx.x] = val; __syncthreads(); AccumT warpVal = defaultVal; // First warp will perform per-warp reductions for the remaining warps uint32_t mask = (((uint64_t)1) << (blockDim.x / 32)) - 1; if (threadIdx.x < 32) { int lane = threadIdx.x % 32; if (lane < blockDim.x / 32) { #pragma unroll for (int i = 0; i < 32; ++i) { warpVal = r(warpVal, smem[lane * 32 + i]); } __syncwarp(mask); smem[lane] = warpVal; } } __syncthreads(); // First thread will perform a reduction of the above per-warp reductions AccumT blockVal = defaultVal; if (threadIdx.x == 0) { for (int i = 0; i < blockDim.x / 32; ++i) { blockVal = r(blockVal, smem[i]); } smem[0] = blockVal; } // Sync and broadcast __syncthreads(); return smem[0]; } template class Reduction1, template class Reduction2, typename AccumT> __device__ __forceinline__ void blockReduce(AccumT* smem, AccumT* reducVal1, AccumT val1, const Reduction1& r1, AccumT defaultVal1, AccumT* reducVal2, AccumT val2, const Reduction2& r2, AccumT defaultVal2) { // To avoid RaW races from chaining blockReduce calls together, we need a sync here __syncthreads(); smem[threadIdx.x] = val1; smem[blockDim.x + threadIdx.x] = val2; __syncthreads(); AccumT warpVal1 = defaultVal1; AccumT warpVal2 = defaultVal2; // First warp will perform per-warp reductions for the remaining warps uint32_t mask = (((uint64_t)1) << (blockDim.x / 32)) - 1; if (threadIdx.x < 32) { int lane = threadIdx.x % 32; if (lane < blockDim.x / 32) { #pragma unroll for (int i = 0; i < 32; ++i) { warpVal1 = r1(warpVal1, smem[lane * 32 + i]); warpVal2 = r2(warpVal2, smem[lane * 32 + i + blockDim.x]); } __syncwarp(mask); smem[lane] = warpVal1; smem[lane + blockDim.x] = warpVal2; } } __syncthreads(); // First thread will perform a reduction of the above per-warp reductions AccumT blockVal1 = defaultVal1; AccumT blockVal2 = defaultVal2; if (threadIdx.x == 0) { for (int i = 0; i < blockDim.x / 32; ++i) { blockVal1 = r1(blockVal1, smem[i]); blockVal2 = r2(blockVal2, smem[i + blockDim.x]); } smem[0] = blockVal1; smem[blockDim.x] = blockVal2; } // Sync and broadcast __syncthreads(); *reducVal1 = smem[0]; *reducVal2 = smem[blockDim.x]; __syncthreads(); } template class Reduction, int ILP, typename T, typename AccumT> __device__ __forceinline__ AccumT ilpReduce(int shift, T* data, int size, const Reduction& r, AccumT defaultVal) { typedef typename std::aligned_storage::type LoadT; AccumT threadVal = defaultVal; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ data -= shift; size += shift; if(threadIdx.x >= shift){ threadVal = r(threadVal, data[offset]); } size -= blockDim.x; data += blockDim.x; } int last = size % (ILP * blockDim.x); T v[ILP]; LoadT* value = reinterpret_cast(&v); for (; offset * ILP < (size - last); offset += blockDim.x) { *value = reinterpret_cast(data)[offset]; for (int j = 0; j < ILP; ++j) { threadVal = r(threadVal, v[j]); } } offset = size - last + threadIdx.x; // Epilogue for (; offset < size; offset += blockDim.x) threadVal = r(threadVal, data[offset]); return threadVal; } template class Reduction1, template class Reduction2, int ILP, typename T, typename AccumT> __device__ __forceinline__ void ilpReduce(int shift, T* data, int size, AccumT* reducVal1, const Reduction1& r1, AccumT defaultVal1, AccumT* reducVal2, const Reduction2& r2, AccumT defaultVal2) { typedef typename std::aligned_storage::type LoadT; AccumT threadVal1 = defaultVal1; AccumT threadVal2 = defaultVal2; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ data -= shift; size += shift; if(threadIdx.x >= shift){ threadVal1 = r1(threadVal1, data[offset]); threadVal2 = r2(threadVal2, data[offset]); } size -= blockDim.x; data += blockDim.x; } int last = size % (ILP * blockDim.x); T v[ILP]; LoadT* value = reinterpret_cast(&v); for (; offset * ILP < (size - last); offset += blockDim.x) { *value = reinterpret_cast(data)[offset]; for (int j = 0; j < ILP; ++j) { threadVal1 = r1(threadVal1, v[j]); threadVal2 = r2(threadVal2, v[j]); } } offset = size - last + threadIdx.x; // Epilogue for (; offset < size; offset += blockDim.x) { threadVal1 = r1(threadVal1, data[offset]); threadVal2 = r2(threadVal2, data[offset]); } *reducVal1 = threadVal1; *reducVal2 = threadVal2; } template class Epilogue> __global__ void cunn_SoftMaxXEntropyForward( accscalar_t *losses, outscalar_t *max_log_sum_exp, scalar_t *input, int64_t *labels, int64_t classes, const float smoothing) { extern __shared__ unsigned char smem[]; auto sdata = reinterpret_cast(smem); // forward pointers to batch[blockIdx.x] // each block handles a sample in the mini-batch input += blockIdx.x * classes; //output += blockIdx.x * classes; const int shift = ((uint64_t)input) % ALIGN_BYTES / sizeof(scalar_t); int64_t label = labels[blockIdx.x]; // find the max and sum accscalar_t threadMax, threadSum, max_k, sum_k; ilpReduce( shift, input, classes, &threadMax, MaxFloat(), -at::numeric_limits::max(), &threadSum, AddFloat(), static_cast(0)); blockReduce( sdata, &max_k, threadMax, Max(), -at::numeric_limits::max(), &sum_k, threadSum, Add(), static_cast(0)); accscalar_t threadExp = ilpReduce(shift, input, classes, SumExpFloat(max_k), static_cast(0)); accscalar_t sumAll = blockReduce( sdata, threadExp, Add(), static_cast(0)); Epilogue epilogue(max_k, sumAll); // calculate per element loss with label smoothing // reserve max + log_sum_exp for bprop if (threadIdx.x == 0) { accscalar_t log_prob = epilogue(static_cast(input[label])); losses[blockIdx.x] = (max_k + std::log(sumAll) - sum_k / classes) \ * smoothing - log_prob * (1 - smoothing); max_log_sum_exp[blockIdx.x] = max_k + std::log(sumAll); } } template __device__ __forceinline__ void apply(scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { accscalar_t smooth_positives = 1.0 - smoothing; accscalar_t smooth_negatives = smoothing / classes; accscalar_t tmpGradOutput = gradOutput[blockIdx.x]; int64_t label = labels[blockIdx.x]; accscalar_t coeff = max_log_sum_exp[blockIdx.x]; int offset = threadIdx.x; int last = classes % (ILP * blockDim.x); for (; offset < classes - last; offset += blockDim.x * ILP) { accscalar_t tmpLogits[ILP]; #pragma unroll for (int j = 0; j < ILP; ++j) { tmpLogits[j] = static_cast(logits[offset + j * blockDim.x]); } #pragma unroll for (int j = 0; j < ILP; ++j) gradInput[offset + j * blockDim.x] = tmpGradOutput * ( std::exp(tmpLogits[j] - coeff) - static_cast( (offset + j * blockDim.x == label) ? 1 : 0) * smooth_positives - smooth_negatives); } for (; offset < classes; offset += blockDim.x) gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast((offset == label) ? 1 : 0) * smooth_positives - smooth_negatives); } template __device__ __forceinline__ void aligned_apply(int shift, scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { accscalar_t smooth_positives = 1.0 - smoothing; accscalar_t smooth_negatives = smoothing / classes; accscalar_t tmpGradOutput = gradOutput[blockIdx.x]; int64_t label = labels[blockIdx.x]; accscalar_t coeff = max_log_sum_exp[blockIdx.x]; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ logits -= shift; gradInput -= shift; classes += shift; if(threadIdx.x >= shift){ gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast(((offset - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } classes -= blockDim.x; gradInput += blockDim.x; logits += blockDim.x; shift -= blockDim.x; } int last = classes % (ILP * blockDim.x); typedef typename std::aligned_storage::type LoadT; // input scalar_t v[ILP]; LoadT* value = reinterpret_cast(&v); // output scalar_t r[ILP]; LoadT* result = reinterpret_cast(&r); for (; offset * ILP < (classes - last); offset += blockDim.x) { *value = reinterpret_cast(logits)[offset]; #pragma unroll for (int j = 0; j < ILP; ++j) { r[j] = tmpGradOutput * (std::exp( static_cast(v[j]) - coeff) - static_cast(((ILP * offset + j - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } reinterpret_cast(gradInput)[offset] = *result; } offset = classes - last + threadIdx.x; for (; offset < classes; offset += blockDim.x) gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast(((offset - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } template class Epilogue> __global__ void cunn_SoftMaxXEntropyBackward( scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { gradInput += blockIdx.x * classes; logits += blockIdx.x * classes; // Do vectorized load/store when input/output have same alignment const int shift = ((uint64_t)logits) % ALIGN_BYTES / sizeof(scalar_t); const int shift_ = ((uint64_t)gradInput) % ALIGN_BYTES / sizeof(scalar_t); if (shift == shift_){ aligned_apply(shift, gradInput, logits, max_log_sum_exp, gradOutput, labels, smoothing, classes); } else { apply(gradInput, logits, max_log_sum_exp, gradOutput, labels, smoothing, classes); } } template class Epilogue> std::vector host_softmax_xentropy( const Tensor & input_, const Tensor & labels_, const float smoothing, const bool half_to_float){ if (half_to_float) AT_ASSERTM(input_.type().scalarType() == ScalarType::Half,"conversion is supported for Half type only"); AT_ASSERTM(labels_.type().scalarType() == ScalarType::Long,"Label type should be CUDA Long"); auto input = input_.contiguous(); Tensor max_log_sum_exp = at::empty_like(labels_, half_to_float ? input.options().dtype(ScalarType::Float) : input.options()); Tensor losses = at::empty_like(labels_, input_.options().dtype(ScalarType::Float)); static_assert(std::is_same, float>::value || std::is_same, double>::value, "accscalar_t for half should be float or double"); AT_ASSERTM(input.dim() == 2, "Currently only 2 dim input supported"); AT_ASSERTM(labels_.dim() == 1, "Labels should be 1 dimensional"); AT_ASSERTM(input.size(0) == labels_.size(0), "Input and label should have same number of examples"); AT_ASSERTM(input.numel() > 0, "Number of classes in input should not be 0"); const int64_t dim = 1; int64_t outer_size = 1; int64_t dim_size = input.size(dim); int64_t inner_size = 1; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); for (int64_t i = 0; i < dim; ++i) outer_size *= input.size(i); for (int64_t i = dim + 1; i < input.dim(); ++i) inner_size *= input.size(i); // This kernel spawns a block per each element in the batch. // XXX: it assumes that inner_size == 1 TORCH_CHECK(inner_size == 1, "Currently only inner size 1 supported"); dim3 grid(outer_size); using namespace at; DISPATCH_FLOAT_AND_HALF(input.scalar_type(), 0, "host_softmax_xentropy", using accscalar_t = at::acc_type; const int ILP = sizeof(float4)/sizeof(scalar_t_0); dim3 block = SoftMax_getBlockSize(ILP, dim_size); if (!half_to_float) { cunn_SoftMaxXEntropyForward <<>>( losses.DATA_PTR(), max_log_sum_exp.DATA_PTR(), input.DATA_PTR(), labels_.DATA_PTR(), dim_size, smoothing ); } else { cunn_SoftMaxXEntropyForward <<>>( losses.DATA_PTR(), max_log_sum_exp.DATA_PTR(), input.DATA_PTR(), labels_.DATA_PTR(), dim_size, smoothing ); } ); THCudaCheck(cudaGetLastError()); std::vector ret = {losses, max_log_sum_exp}; return ret; } template class Epilogue> Tensor host_softmax_xentropy_backward( const at::Tensor &grad_loss, const at::Tensor &logits_, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing, bool half_to_float) { const int64_t dim = 1; Tensor gI = at::empty_like(logits_); if (grad_loss.numel() == 0) { return gI; } auto grad = grad_loss.contiguous(); auto logits = logits_.contiguous(); static_assert(std::is_same, float>::value || std::is_same, double>::value, "accscalar_t for half should be float or double"); if (grad.dim() == 0) grad = grad.view(1); AT_ASSERTM(logits_.dim() == 2, "Currently only 2 dim input supported"); AT_ASSERTM(labels.dim() == 1, "Labels should be 1 dimensional"); AT_ASSERTM(logits_.numel() > 0, "Number of classes in input should not be 0"); AT_ASSERTM(logits_.size(0) == labels.size(0), "Input and label should have same number of examples"); AT_ASSERTM(labels.size(0) == grad.size(0), "Label and loss should have same number of examples"); int64_t outer_size = 1; int64_t dim_size = logits.size(dim); int64_t inner_size = 1; for (int64_t i = 0; i < dim; ++i) outer_size *= logits.size(i); for (int64_t i = dim + 1; i < logits.dim(); ++i) inner_size *= logits.size(i); // See descriptions of kernels above. cudaStream_t stream = at::cuda::getCurrentCUDAStream(); TORCH_CHECK(inner_size == 1, "Currently only inner size 1 supported"); dim3 grid(outer_size); DISPATCH_FLOAT_AND_HALF(gI.scalar_type(), 0, "host_softmax_xentropy_backward", using accscalar_t = acc_type; const int ILP = sizeof(float4)/sizeof(scalar_t_0); dim3 block = SoftMax_getBlockSize(ILP, dim_size); if (!half_to_float) { cunn_SoftMaxXEntropyBackward <<>>( gI.DATA_PTR(), logits.DATA_PTR(), max_log_sum_exp.DATA_PTR(), grad.DATA_PTR(), labels.DATA_PTR(), smoothing, dim_size ); } else { cunn_SoftMaxXEntropyBackward <<>>( gI.DATA_PTR(), logits.DATA_PTR(), max_log_sum_exp.DATA_PTR(), grad.DATA_PTR(), labels.DATA_PTR(), smoothing, dim_size ); } ); THCudaCheck(cudaGetLastError()); return gI; } std::vector softmax_xentropy_cuda(const Tensor &input, const Tensor &labels, const float smoothing, const bool half_to_float){ return host_softmax_xentropy(input, labels, smoothing, half_to_float); } at::Tensor softmax_xentropy_backward_cuda( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing) { bool half_to_float = grad_loss.type().scalarType() != logits.type().scalarType(); if (half_to_float) { AT_ASSERTM((grad_loss.type().scalarType() == ScalarType::Float && logits.type().scalarType() == ScalarType::Half), "expected input and grad types to match, or input to be at::Half and grad to be at::Float"); } return host_softmax_xentropy_backward(grad_loss, logits, max_log_sum_exp, labels, smoothing, half_to_float); } ================================================ FILE: KoSentenceT5/apex/contrib/examples/multihead_attn/func_test_multihead_attn.py ================================================ import torch import torch.nn.functional as F import argparse from apex.contrib.multihead_attn import SelfMultiheadAttn from apex.contrib.multihead_attn import EncdecMultiheadAttn parser = argparse.ArgumentParser(description='Multihead Attention Standalone Test') parser.add_argument('--seq-length', default=64, type=int, help='Sequence Length of Input') parser.add_argument('--num-seqs-start', default=5, type=int, help='Start Range of Number of Sequences') parser.add_argument('--num-seqs-stop', default=80, type=int, help='Stop Range of Number of Sequences') parser.add_argument('--num-seqs-inc', default=5, type=int, help='Range Increment of Number of Sequences') parser.add_argument('--trials', default=20, type=int, help='Number of Trials to Execute') parser.add_argument('--warmup-trials', default=5, type=int, help='Warmup Trials to discard') parser.add_argument('--layers', default=18, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--seed-start', default=1, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--seed-end', default=100, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--hidden-dim', default=1024, type=int, help='Multihead Attention hidden dimension') parser.add_argument('--heads', default=16, type=int, help='Number of Multihead Attention heads') parser.add_argument('--encdec-attn', action='store_true', help='Use Encoder-Decoder Attention instead of Self Attention.') parser.add_argument('--norm-add', action='store_true', help='Include Layer Norm and Dropout-Add in Multihead Attention block.') parser.add_argument('--ref', action='store_true', help='Reference implementation in python pytorch.') parser.add_argument('--native', action='store_true', help='torch.nn.MultitheadAttention Version.') parser.add_argument('--fwd', action='store_true', help='Only execute Fwd Pass.') parser.add_argument('--eval', action='store_true', help='Inference only, no backward pass.') args = parser.parse_args() assert args.seq_length % 64 == 0, "Sequence Length should be a multiple of 64!" if not torch.cuda.is_available(): raise NotImplementedError('Running on CPU is not supported') torch.cuda.set_device(0) dropout_prob = 0.1 for seed in range(args.seed_start, args.seed_end+1) : torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) ref_layer = None if args.encdec_attn : ref_layer = EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='default') else : ref_layer = SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='default') ref_layer.cuda() ref_layer.half() ref_layer.reset_parameters() ref_inputs = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) ref_inputs_kv = None if args.encdec_attn : ref_inputs_kv = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) ref_grads = torch.randn_like(ref_inputs) ref_outputs,_ = ref_layer.forward(ref_inputs, ref_inputs_kv, ref_inputs_kv, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=(not args.eval)) ref_outputs.backward(ref_grads) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) tst_layer = None if args.encdec_attn : tst_layer = EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='fast') else: tst_layer = SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='fast') tst_layer.cuda() tst_layer.half() tst_layer.reset_parameters() tst_inputs = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) tst_inputs_kv = None if args.encdec_attn : tst_inputs_kv = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) assert torch.equal(ref_inputs,tst_inputs), "ERROR: Inputs are different!" tst_grads = torch.randn_like(tst_inputs) tst_outputs,_ = tst_layer.forward(tst_inputs, tst_inputs_kv, tst_inputs_kv, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=(not args.eval)) tst_outputs.backward(tst_grads) fwd_close = torch.equal(ref_outputs, tst_outputs) bwd_close = torch.equal(ref_inputs.grad, tst_inputs.grad) diff_fwd = ref_outputs - tst_outputs diff_cnt_fwd = diff_fwd.ne(0.0).sum() diff_accum_fwd = diff_fwd.abs().sum() diff_bwd = ref_inputs.grad - tst_inputs.grad diff_cnt_bwd = diff_bwd.ne(0.0).sum() diff_accum_bwd = diff_bwd.abs().sum() print(">>> Seed: ", seed, fwd_close, diff_cnt_fwd.item(), diff_accum_fwd.item(), bwd_close, diff_cnt_bwd.item(), diff_accum_bwd.item()) ================================================ FILE: KoSentenceT5/apex/contrib/examples/multihead_attn/perf_test_multihead_attn.py ================================================ import torch import torch.nn.functional as F import argparse from apex.contrib.multihead_attn import SelfMultiheadAttn from apex.contrib.multihead_attn import EncdecMultiheadAttn parser = argparse.ArgumentParser(description='Multihead Attention Standalone Test') parser.add_argument('--seq-length', default=64, type=int, help='Sequence Length of Input') parser.add_argument('--num-seqs-start', default=10, type=int, help='Start Range of Number of Sequences') parser.add_argument('--num-seqs-stop', default=120, type=int, help='Stop Range of Number of Sequences') parser.add_argument('--num-seqs-inc', default=5, type=int, help='Range Increment of Number of Sequences') parser.add_argument('--trials', default=20, type=int, help='Number of Trials to Execute') parser.add_argument('--warmup-trials', default=5, type=int, help='Warmup Trials to discard') parser.add_argument('--layers', default=18, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--hidden-dim', default=1024, type=int, help='Multihead Attention hidden dimension') parser.add_argument('--heads', default=16, type=int, help='Number of Multihead Attention heads') parser.add_argument('--encdec-attn', action='store_true', help='Use Encoder-Decoder Attention instead of Self Attention.') parser.add_argument('--norm-add', action='store_true', help='Include Layer Norm and Dropout-Add in Multihead Attention block.') parser.add_argument('--ref', action='store_true', help='Reference implementation in python pytorch.') parser.add_argument('--native', action='store_true', help='torch.nn.MultitheadAttention Version.') parser.add_argument('--fwd', action='store_true', help='Only execute Fwd Pass.') parser.add_argument('--biases', action='store_true', help='Execute multihead attention with Linear Biases.') args = parser.parse_args() if not torch.cuda.is_available(): raise NotImplementedError('Running on CPU is not supported') torch.cuda.set_device(0) torch.manual_seed(111) if torch.cuda.is_available(): torch.cuda.manual_seed_all(111) attn_layers = [] for idx in range(0, args.layers) : if args.encdec_attn : if args.ref : attn_layers.append(EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=False, impl='default')) else : attn_layers.append(EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='fast')) else : if args.native : attn_layers.append(torch.nn.MultiheadAttention(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases)) elif args.ref : attn_layers.append(SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='default')) else : attn_layers.append(SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='fast')) attn_layers[idx].cuda() attn_layers[idx].half() if not args.native : attn_layers[idx].reset_parameters() start_evt_fwd = [] start_evt_bwd = [] stop_evt_bwd = [] for recorded_trial in range(0, args.trials) : start_evt_fwd.append(torch.cuda.Event(enable_timing=True)) start_evt_bwd.append(torch.cuda.Event(enable_timing=True)) stop_evt_bwd.append(torch.cuda.Event(enable_timing=True)) for sequences in range(args.num_seqs_start, args.num_seqs_stop + args.num_seqs_inc, args.num_seqs_inc) : inputs = torch.randn(args.seq_length, sequences, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) grads = torch.randn_like(inputs) for trial in range(0, args.trials + args.warmup_trials) : layer_inputs = inputs evt_idx = trial - args.warmup_trials if evt_idx >= 0 : start_evt_fwd[evt_idx].record() for lyr_idx in range(0, args.layers) : if args.native : outputs,_ = attn_layers[lyr_idx].forward(layer_inputs, layer_inputs, layer_inputs, key_padding_mask=None, need_weights=False, attn_mask=None) else : outputs,_ = attn_layers[lyr_idx].forward(layer_inputs, layer_inputs, layer_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) layer_inputs = outputs if evt_idx >= 0 : start_evt_bwd[evt_idx].record() if not args.fwd : layer_inputs.backward(grads) if evt_idx >= 0 : stop_evt_bwd[evt_idx].record() torch.cuda.synchronize() elapsed_time_fwd = 0.0 elapsed_time_bwd = 0.0 for evt_idx in range(0, args.trials) : elapsed_time_fwd += start_evt_fwd[evt_idx].elapsed_time(start_evt_bwd[evt_idx]) elapsed_time_bwd += start_evt_bwd[evt_idx].elapsed_time(stop_evt_bwd[evt_idx]) print("[ {} Attn {} ]Total Tokens: {:4d} Sequences: {:3d} Sequence Length: {:3d} Fwd Time / Layer: {:.3f} ms Bwd Time / Layer: {:.3f} ms".format( 'Encdec' if args.encdec_attn else 'Self', \ 'Norm&Add' if args.norm_add else '', \ sequences*args.seq_length, \ sequences, \ args.seq_length, \ elapsed_time_fwd / ( args.trials * args.layers ), \ elapsed_time_bwd / ( args.trials * args.layers ))) ================================================ FILE: KoSentenceT5/apex/contrib/fmha/__init__.py ================================================ from .fmha import FMHAFun ================================================ FILE: KoSentenceT5/apex/contrib/fmha/fmha.py ================================================ ############################################################################### # Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################### import torch import torch.nn.functional as F import fmhalib as mha class FMHAFun(torch.autograd.Function): @staticmethod def forward(ctx, qkv, cu_seqlens, p_dropout, max_s, is_training): batch_size = cu_seqlens.numel() - 1 if batch_size < 4: context, S_dmask = mha.fwd_nl(qkv, cu_seqlens, p_dropout, max_s, is_training, None) else: context, S_dmask = mha.fwd(qkv, cu_seqlens, p_dropout, max_s, is_training, None) ctx.save_for_backward(qkv, S_dmask) ctx.cu_seqlens = cu_seqlens ctx.p_dropout = p_dropout ctx.max_s = max_s return context @staticmethod def backward(ctx, dout): qkv, S_dmask = ctx.saved_tensors batch_size = ctx.cu_seqlens.numel() - 1 if batch_size < 4: dqkv, dp, _ = mha.bwd_nl(dout, qkv, S_dmask, ctx.cu_seqlens, ctx.p_dropout, ctx.max_s) else: dqkv, dp = mha.bwd(dout, qkv, S_dmask, ctx.cu_seqlens, ctx.p_dropout, ctx.max_s) return dqkv, None, None, None, None, None, None class FMHA(torch.nn.Module): def __init__(self, config): super(FMHA, self).__init__() self.p_dropout = config.attention_probs_dropout_prob self.h = config.num_attention_heads self.hidden_size = config.hidden_size self.d = self.hidden_size // self.h assert self.d * self.h == self.hidden_size, "Invalid hidden size/num_heads" def forward(self, qkv, cu_seqlens, max_s, is_training=True): ctx = FMHAFun.apply(qkv.view(-1, 3, self.h, self.d), cu_seqlens, self.p_dropout, max_s, is_training) return ctx.view(-1, self.hidden_size) ================================================ FILE: KoSentenceT5/apex/contrib/groupbn/__init__.py ================================================ try: import torch import bnp from .batch_norm import BatchNorm2d_NHWC del torch del bnp del batch_norm except ImportError as err: print("apex was installed without --bnp flag, contrib.groupbn is not available") ================================================ FILE: KoSentenceT5/apex/contrib/groupbn/batch_norm.py ================================================ import torch import numpy as np from torch.nn.modules.batchnorm import _BatchNorm import bnp class bn_NHWC_impl(torch.autograd.Function): @staticmethod def forward(ctx, x, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, is_train, bn_group, my_data, pair_data, magic, pair_data2, pair_data3, fwd_occup, fwd_grid_x, bwd_occup, bwd_grid_x, multi_stream): if is_train: ctx.save_for_backward(x, s, b, rm, riv, mini_m, mini_riv) ctx.epsilon = epsilon ctx.momentum = mom ctx.ret_cta = ret_cta ctx.fuse_relu = fuse_relu ctx.my_data = my_data ctx.pair_data = pair_data ctx.magic = magic ctx.pair_data2 = pair_data2 ctx.pair_data3 = pair_data3 ctx.bn_group = bn_group ctx.bwd_occup = bwd_occup ctx.bwd_grid_x = bwd_grid_x ctx.multi_stream = multi_stream res = bnp.bn_fwd_nhwc(x, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, fwd_occup, fwd_grid_x, multi_stream) return res else: return bnp.bn_fwd_eval_nhwc(x, s, b, rm, riv, ret_cta, bn_group, mom, epsilon, fuse_relu) @staticmethod def backward(ctx, grad_y): x, s, b, rm, riv, mini_m, mini_riv = ctx.saved_variables epsilon = ctx.epsilon mom = ctx.momentum ret_cta = ctx.ret_cta fuse_relu = ctx.fuse_relu my_data = ctx.my_data pair_data = ctx.pair_data magic = ctx.magic pair_data2 = ctx.pair_data2 pair_data3 = ctx.pair_data3 bn_group = ctx.bn_group bwd_occup = ctx.bwd_occup bwd_grid_x = ctx.bwd_grid_x multi_stream = ctx.multi_stream dx, dscale, dbias = bnp.bn_bwd_nhwc(x, grad_y, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, bwd_occup, bwd_grid_x, multi_stream) return dx, dscale, dbias, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None class bn_addrelu_NHWC_impl(torch.autograd.Function): @staticmethod def forward(ctx, x, z, s, b, rm, riv, mini_m, mini_riv, grid_dim_y, ret_cta, mom, epsilon, is_train, bn_group, my_data, pair_data, magic, pair_data2, pair_data3, fwd_occup, fwd_grid_x, bwd_occup, bwd_grid_x, multi_stream): if is_train: bitmask = torch.cuda.IntTensor(((x.numel()+31)//32) * 2 * grid_dim_y) ctx.save_for_backward(x, s, b, rm, riv, mini_m, mini_riv, bitmask) ctx.epsilon = epsilon ctx.momentum = mom ctx.ret_cta = ret_cta ctx.my_data = my_data ctx.pair_data = pair_data ctx.magic = magic ctx.pair_data2 = pair_data2 ctx.pair_data3 = pair_data3 ctx.bn_group = bn_group ctx.bwd_occup = bwd_occup ctx.bwd_grid_x = bwd_grid_x ctx.multi_stream = multi_stream res = bnp.bn_addrelu_fwd_nhwc(x, z, s, b, rm, riv, mini_m, mini_riv, bitmask, ret_cta, mom, epsilon, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, fwd_occup, fwd_grid_x, multi_stream) return res else: return bnp.bn_addrelu_fwd_eval_nhwc(x, z, s, b, rm, riv, ret_cta, bn_group, mom, epsilon) @staticmethod def backward(ctx, grad_y): x, s, b, rm, riv, mini_m, mini_riv, bitmask = ctx.saved_variables epsilon = ctx.epsilon mom = ctx.momentum ret_cta = ctx.ret_cta my_data = ctx.my_data pair_data = ctx.pair_data magic = ctx.magic pair_data2 = ctx.pair_data2 pair_data3 = ctx.pair_data3 bn_group = ctx.bn_group bwd_occup = ctx.bwd_occup bwd_grid_x = ctx.bwd_grid_x multi_stream = ctx.multi_stream dx, dz, dscale, dbias = bnp.bn_addrelu_bwd_nhwc(x, grad_y, s, b, rm, riv, mini_m, mini_riv, bitmask, ret_cta, mom, epsilon, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, bwd_occup, bwd_grid_x, multi_stream) return dx, dz, dscale, dbias, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None class BatchNorm2d_NHWC(_BatchNorm): # if using BatchNorm2d_NHWC simultaneously with multiple streams set multi_stream to True def __init__(self, num_features, fuse_relu=False, bn_group=1, max_cta_per_sm=2, cta_launch_margin=12, multi_stream=False): super(BatchNorm2d_NHWC, self).__init__(num_features) self.fuse_relu = fuse_relu self.multi_stream = multi_stream self.minibatch_mean = torch.cuda.FloatTensor(num_features) self.minibatch_riv = torch.cuda.FloatTensor(num_features) #defaut to distributed bn disabled self.bn_group = bn_group self.max_cta_per_sm = max_cta_per_sm #used only in training fwd and bwd self.cta_launch_margin = cta_launch_margin #used only in training fwd and bwd self.my_data = None self.pair_data = None self.pair_data2 = None self.pair_data3 = None self.local_rank = 0 self.magic = torch.IntTensor([0]) #calculate cta per sm occupancies assert(max_cta_per_sm>0) # won't be able to do much with 0 CTAs :) self.fwd_occupancy = min(bnp.bn_fwd_nhwc_occupancy(), max_cta_per_sm) self.bwd_occupancy = min(bnp.bn_bwd_nhwc_occupancy(), max_cta_per_sm) self.addrelu_fwd_occupancy = min(bnp.bn_addrelu_fwd_nhwc_occupancy(), max_cta_per_sm) self.addrelu_bwd_occupancy = min(bnp.bn_addrelu_bwd_nhwc_occupancy(), max_cta_per_sm) #calculate grid dimentions based on occupancy numbers mp_count = torch.cuda.get_device_properties(None).multi_processor_count self.fwd_grid_dim_x = max(mp_count*self.fwd_occupancy - cta_launch_margin , 1) self.bwd_grid_dim_x = max(mp_count*self.bwd_occupancy - cta_launch_margin , 1) self.addrelu_fwd_grid_dim_x = max(mp_count*self.addrelu_fwd_occupancy - cta_launch_margin , 1) self.addrelu_bwd_grid_dim_x = max(mp_count*self.addrelu_bwd_occupancy - cta_launch_margin , 1) self.grid_dim_y = (num_features + 63) // 64 # allocate scratch space used by implementation # TODO: scratch space that is not supposed to be exposed at user code. We only need one time initialization, the # same buffer could be reused in future iterations. Currently we exposed it here instead of requesting new # buffer from cache allocator to avoid unnecessary initialization at future iterations. self.ret_cta = torch.cuda.ByteTensor(8192).fill_(0) #FIXME: turn pair handles into an array if bn_group>1: local_rank = torch.distributed.get_rank() world_size = torch.distributed.get_world_size() assert(world_size >= bn_group) assert(world_size % bn_group == 0) bn_sync_steps = 1 if (bn_group==4): bn_sync_steps = 2 if (bn_group==8): bn_sync_steps = 3 self.ipc_buffer = torch.cuda.ByteTensor(bnp.get_buffer_size(bn_sync_steps)) self.my_data = bnp.get_data_ptr(self.ipc_buffer) # we are walking on very thin ice here by utilizing internal `_share_cuda_()` self.storage = self.ipc_buffer.storage() self.share_cuda = self.storage._share_cuda_() internal_cuda_mem = self.share_cuda # internal_cuda_mem[1]: ipc_mem_handle my_handle = torch.cuda.ByteTensor(np.frombuffer(internal_cuda_mem[1], dtype=np.uint8)) # internal_cuda_mem[3]: offset my_offset = torch.cuda.IntTensor([internal_cuda_mem[3]]) handles_all = torch.empty(world_size, my_handle.size(0), dtype=my_handle.dtype, device=my_handle.device) handles_l = list(handles_all.unbind(0)) torch.distributed.all_gather(handles_l, my_handle) offsets_all = torch.empty(world_size, my_offset.size(0), dtype=my_offset.dtype, device=my_offset.device) offsets_l = list(offsets_all.unbind(0)) torch.distributed.all_gather(offsets_l, my_offset) #whom do I actually care about? that would be local_rank XOR 1 self.pair_handle = handles_l[local_rank ^ 1].cpu().contiguous() pair_offset = offsets_l[local_rank ^ 1].cpu() self.pair_data = bnp.get_remote_data_ptr(self.pair_handle, pair_offset) if bn_group>2: self.pair_handle2 = handles_l[local_rank ^ 2].cpu().contiguous() pair_offset2 = offsets_l[local_rank ^ 2].cpu() self.pair_data2 = bnp.get_remote_data_ptr(self.pair_handle2, pair_offset2) if bn_group>4: self.pair_handle3 = handles_l[local_rank ^ 4].cpu().contiguous() pair_offset3 = offsets_l[local_rank ^ 4].cpu() self.pair_data3 = bnp.get_remote_data_ptr(self.pair_handle3, pair_offset3) #FIXME: get magic value into C code and eliminate from here self.magic = torch.IntTensor([2]) self.local_rank = local_rank def forward(self, x, z=None): if z is not None: assert(self.fuse_relu==True) return bn_addrelu_NHWC_impl.apply(x, z, self.weight, self.bias, self.running_mean, self.running_var, self.minibatch_mean, self.minibatch_riv, self.grid_dim_y, self.ret_cta, self.momentum, self.eps, self.training, self.bn_group, self.my_data, self.pair_data, (self.magic), self.pair_data2, self.pair_data3, self.addrelu_fwd_occupancy, self.addrelu_fwd_grid_dim_x, self.addrelu_bwd_occupancy, self.addrelu_bwd_grid_dim_x, self.multi_stream) else: return bn_NHWC_impl.apply(x, self.weight, self.bias, self.running_mean, self.running_var, self.minibatch_mean, self.minibatch_riv, self.ret_cta, self.momentum, self.eps, self.fuse_relu, self.training, self.bn_group, self.my_data, self.pair_data, (self.magic), self.pair_data2, self.pair_data3, self.fwd_occupancy, self.fwd_grid_dim_x, self.bwd_occupancy, self.bwd_grid_dim_x, self.multi_stream) def __del__(self): if self.bn_group>1: bnp.close_remote_data(self.pair_handle) if self.bn_group>2: bnp.close_remote_data(self.pair_handle2) if self.bn_group>4: bnp.close_remote_data(self.pair_handle3) ================================================ FILE: KoSentenceT5/apex/contrib/layer_norm/__init__.py ================================================ from .layer_norm import FastLayerNorm ================================================ FILE: KoSentenceT5/apex/contrib/layer_norm/layer_norm.py ================================================ import torch from torch.nn import init import fast_layer_norm class FastLayerNormFN(torch.autograd.Function): @staticmethod def forward(ctx, x, gamma, beta, epsilon): x = x.contiguous() gamma = gamma.contiguous() beta = beta.contiguous() hidden_size = gamma.numel() xmat = x.view((-1, hidden_size)) ymat, mu, rsigma = fast_layer_norm.ln_fwd(xmat, gamma, beta, epsilon) ctx.save_for_backward(x, gamma, mu, rsigma) return ymat.view(x.shape) @staticmethod def backward(ctx, dy): #assert dy.is_contiguous() dy = dy.contiguous() # this happens! x, gamma, mu, rsigma = ctx.saved_tensors hidden_size = gamma.numel() xmat = x.view((-1, hidden_size)) dymat = dy.view(xmat.shape) dxmat, dgamma, dbeta = fast_layer_norm.ln_bwd(dymat, xmat, mu, rsigma, gamma) dx = dxmat.view(x.shape) return dx, dgamma, dbeta, None class FastLayerNorm(torch.nn.Module): def __init__(self, hidden_size, eps=1e-5): super(FastLayerNorm, self).__init__() self.epsilon = eps self.weight = torch.nn.Parameter(torch.Tensor(hidden_size)) self.bias = torch.nn.Parameter(torch.Tensor(hidden_size)) self.reset_parameters() def reset_parameters(self): init.ones_(self.weight) init.zeros_(self.bias) def forward(self, x): return FastLayerNormFN.apply(x, self.weight, self.bias, self.epsilon) ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/README.md ================================================ # Fast Multihead Attention This implementation has two main features : * A C++ implementation to avoid the CPU overheads of Pytorch found with smaller batch sizes. * The removal of all copies and transposes found in standard implementations of Multihead Attention. | | Python Version | C++ Version | | :----------------------------------------- | :------------: | :---------: | | Layer Norm and Residual Add Variant | X | X | | Includes Linear Biases | X | | | Reduces CPU Overheads | | X | | Fuses masking with Softmax | | X | | Removes Transposes and Copies | X | X | | Includes Self and Encoder/Decoder Variants | X | X | ## How to Instantiate `SelfMultiheadAttn(` _hidden dim_, _heads_, _dropout=prob_, _bias=bool_, _include_norm_add=bool_, _impl='fast'_ `)` `EncdecMultiheadAttn(` _hidden dim_, _heads_, _dropout=prob_, _bias=bool_, _include_norm_add=bool_, _impl='fast'_ `)` `impl` has two options: * `fast` uses C++ Version * `default` uses Python Version ## Instructions to build on Linux ``` $ git clone https://github.com/NVIDIA/apex $ cd apex $ pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" --global-option="--fast_multihead_attn" ./ ``` ## Try Performance Tests Yourself! Perf test script is found here! ``` cd contrib/examples/multihead_attn ``` #### Fast Multihead Attention ``` python perf_test_multihead_attn.py --ref ``` #### Fast Multihead Attention with C++ Implementation ``` python perf_test_multihead_attn.py ``` #### Compare with `torch.nn.MultiheadAttn` ``` python perf_test_multihead_attn.py --native ``` #### Test your own range! ``` python perf_test_multihead_attn.py --seq-length 64 --num-seqs-start 10 --num-seqs-stop 120 --num-seqs-inc 5 ``` ## Performance Comparisons * Performance was measured with 64 token sequence lengths on an NVIDIA TitanV card. * Time is measured across multiple layers to simulate an in model scenario. ![Multihead Attention Forward](MHA_fwd.png) ![Multihead Attention Backward](MHA_bwd.png) ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/__init__.py ================================================ from .self_multihead_attn import SelfMultiheadAttn from .encdec_multihead_attn import EncdecMultiheadAttn from .mask_softmax_dropout_func import fast_mask_softmax_dropout_func ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/encdec_multihead_attn.py ================================================ import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .encdec_multihead_attn_func import encdec_attn_func from .fast_encdec_multihead_attn_func import fast_encdec_attn_func from .fast_encdec_multihead_attn_norm_add_func import fast_encdec_attn_norm_add_func from apex.normalization.fused_layer_norm import FusedLayerNorm if hasattr(torch._C, '_jit_set_profiling_executor') : torch._C._jit_set_profiling_executor(False) if hasattr(torch._C, '_jit_set_profiling_mode') : torch._C._jit_set_profiling_mode(False) @torch.jit.script def jit_dropout_add(x, residual, prob, is_training): # type: (Tensor, Tensor, float, bool) -> Tensor out = F.dropout(x, p=prob, training=True) out = residual + out return out class EncdecMultiheadAttn(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, dropout=0., bias=False, include_norm_add=False, impl='fast'): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.bias = bias self.include_norm_add = include_norm_add self.impl = impl self.scaling = self.head_dim**-0.5 self.in_proj_weight_q = Parameter(torch.Tensor(embed_dim, embed_dim)) self.in_proj_weight_kv = Parameter(torch.Tensor(2*embed_dim, embed_dim)) self.out_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) if self.bias: assert impl != 'fast', "ERROR! The Fast implementation does not support biases!" self.in_proj_bias_q = Parameter(torch.Tensor(embed_dim)) self.in_proj_bias_kv = Parameter(torch.Tensor(2*embed_dim)) self.out_proj_bias = Parameter(torch.Tensor(embed_dim)) else: self.register_parameter('in_proj_bias_q', None) self.register_parameter('in_proj_bias_kv', None) self.in_proj_bias_q = None self.in_proj_bias_kv = None self.out_proj_bias = None if self.include_norm_add: if impl == 'fast': self.lyr_nrm_gamma_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm_beta_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm = None else: self.register_parameter('lyr_norm_gamma_weights', None) self.register_parameter('lyr_norm_beta_weights', None) self.lyr_nrm_gamma_weights = None self.lyr_nrm_beta_weights = None self.lyr_nrm = FusedLayerNorm(embed_dim) self.reset_parameters() if self.include_norm_add: if impl == 'fast' : self.attn_func = fast_encdec_attn_norm_add_func elif impl == 'default' : self.attn_func = encdec_attn_func else : assert False, "Unsupported impl: {} !".format(impl) else: if impl == 'fast' : self.attn_func = fast_encdec_attn_func elif impl == 'default' : self.attn_func = encdec_attn_func else : assert False, "Unsupported impl: {} !".format(impl) def reset_parameters(self): nn.init.xavier_uniform_(self.in_proj_weight_q) # in_proj_weight_kv has shape [2 * hidden, hidden] but it should be # initialized like a [hidden, hidden] matrix. # sqrt(6 / (hidden + hidden)) / sqrt(6 / (2 * hidden + hidden)) = sqrt(1.5) # therefore xavier_uniform gain should be set to sqrt(1.5). nn.init.xavier_uniform_(self.in_proj_weight_kv, gain=math.sqrt(1.5)) nn.init.xavier_uniform_(self.out_proj_weight) if self.bias: nn.init.constant_(self.in_proj_bias_q, 0.) nn.init.constant_(self.in_proj_bias_kv, 0.) nn.init.constant_(self.out_proj_bias, 0.) if self.include_norm_add: if self.impl == 'fast' : nn.init.ones_(self.lyr_nrm_gamma_weights) nn.init.zeros_(self.lyr_nrm_beta_weights) else: self.lyr_nrm.reset_parameters() def forward(self, query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ if key_padding_mask is not None: assert (attn_mask is None), "ERROR attn_mask and key_padding_mask should not be both defined!" mask = key_padding_mask elif attn_mask is not None: mask = attn_mask else: mask = None if self.include_norm_add: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, key, self.lyr_nrm_gamma_weights, self.lyr_nrm_beta_weights, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, mask, self.dropout) else: lyr_nrm_results = self.lyr_nrm(query) outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, lyr_nrm_results, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, self.in_proj_bias_q, self.in_proj_bias_kv, self.out_proj_bias, mask, self.dropout) if is_training: outputs = jit_dropout_add(outputs, query, self.dropout, is_training) else: outputs = outputs + query else: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, mask, self.dropout) else: outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, query, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, self.in_proj_bias_q, self.in_proj_bias_kv, self.out_proj_bias, mask, self.dropout) return outputs,None ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/encdec_multihead_attn_func.py ================================================ import torch import torch.nn.functional as F class EncdecAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, scale, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, input_biases_q, input_biases_kv, output_biases, mask, dropout_prob): use_biases_t = torch.tensor([input_biases_q is not None]) heads_t = torch.tensor([heads]) scale_t = torch.tensor([scale]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) head_dim = inputs_q.size(2) // heads # Input Linear GEMM Q # input1: (activations) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim (1024), embed_dim (1024)] (transpose [0,1]) # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) if use_biases_t[0]: input_lin_q_results = torch.addmm(input_biases_q, inputs_q.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), input_weights_q.transpose(0,1), beta=1., alpha=1.) else: input_lin_q_results = torch.mm(inputs_q.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), input_weights_q.transpose(0,1)) input_lin_q_results = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1), input_weights_q.size(0)) # Input Linear GEMM KV # input1: (activations) [seql_k, seqs, embed_dim(1024)] # input2: (weights) [embed_dim*2 (2048), embed_dim (1024)] (transpose [0,1]) # output: [seql_k, seqs, embed_dim*2] # GEMM: ( (seql_k*seqs) x embed_dim ) x ( embed_dim x embed_dim*2 ) = (seql_k*seqs x embed_dim*2) if use_biases_t[0]: input_lin_kv_results = torch.addmm(input_biases_kv, inputs_kv.view(inputs_kv.size(0) * inputs_kv.size(1), inputs_kv.size(2)), input_weights_kv.transpose(0,1), beta=1., alpha=1.) else: input_lin_kv_results = torch.mm(inputs_kv.view(inputs_kv.size(0) * inputs_kv.size(1), inputs_kv.size(2)), input_weights_kv.transpose(0,1)) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1), input_weights_kv.size(0)) # Slice out k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_kv_results: [seql_k, seqs, heads(16), 2, head_dim(64)] # input_lin_kv_results: [seql_k, batches=seqs*heads, 2, head_dim] queries = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1)*heads, head_dim) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1)*heads, 2, head_dim) keys = input_lin_kv_results[:,:,0,:] values = input_lin_kv_results[:,:,1,:] # Matmul1 Batched GEMMs # The output tensor is specified prior to the Batch GEMM because baddbmm requires its specification # baddbmm is used to apply the scale parameter via the Batched GEMM's alpha parameter instead of # a separate elementwise operation. # Input1: (Queries) [seql_q, seqs*heads, head_dim] tranpose(0,1) # Input2: (Keys) [seql_k, seqs*heads, head_dim] transpose(0,1) # output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul1_results = torch.empty((queries.size(1),queries.size(0),keys.size(0)), dtype=queries.dtype, device=torch.device('cuda')) matmul1_results = torch.baddbmm(matmul1_results, queries.transpose(0,1), keys.transpose(0,1).transpose(1,2), out=matmul1_results, beta=0.0, alpha=scale_t[0]) if mask is not None: # Self Attention Time Mask if use_time_mask: assert (len(mask.size()) == 2), "Timing mask is not 2D!" assert (mask.size(0) == mask.size(1)), "Sequence length should match!" mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask, float('-inf')) # Key Padding Mask else: batches,seql_q,seql_k = matmul1_results.size() seqs = int(batches / heads) matmul1_results = matmul1_results.view(seqs, heads, seql_q, seql_k) mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask.unsqueeze(1).unsqueeze(2), float('-inf')) matmul1_results = matmul1_results.view(seqs*heads, seql_q, seql_k) softmax_results = F.softmax(matmul1_results, dim=-1) # Dropout - is not executed for inference if is_training: dropout_results,dropout_mask = torch._fused_dropout(softmax_results, p=(1.-dropout_prob_t[0])) else: dropout_results = softmax_results dropout_mask = null_tensor # Matmul2 Batched GEMMs # The output tensor specification is needed here to specify the non-standard output. # Given that pytorch cannot currently perform autograd with an output tensor specified, # this requires a backward pass specified. # Input1: from_softmax [seqs*heads, seql_q, seql_k] # Input2: (values) [seql_v, seqs*heads, head_dim] transpose(0,1) # Output: [seql_q, seqs*heads, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = (seql_q x head_dim) matmul2_results = torch.empty((dropout_results.size(1), dropout_results.size(0), values.size(2)), dtype=dropout_results.dtype, device=torch.device('cuda')).transpose(1,0) matmul2_results = torch.bmm(dropout_results, values.transpose(0,1), out=matmul2_results) matmul2_results = matmul2_results.transpose(0, 1).contiguous().view(inputs_q.size(0), inputs_q.size(1), inputs_q.size(2)) # Output Linear GEMM # Input1: (activations) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] transpose(0,1) # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) if use_biases_t[0]: outputs = torch.addmm(output_biases, matmul2_results.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), output_weights.transpose(0,1), beta=1., alpha=1.) else: outputs = torch.mm(matmul2_results.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), output_weights.transpose(0,1)) outputs = outputs.view(inputs_q.size(0), inputs_q.size(1), output_weights.size(0)) ctx.save_for_backward(use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors head_dim = inputs_q.size(2) // heads_t[0] # Slice out k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_kv_results: [seql_k, seqs, heads(16), 2, head_dim(64)] # input_lin_kv_results: [seql_k, batches=seqs*heads, 2, head_dim] queries = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1)*heads_t[0], head_dim) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1)*heads_t[0], 2, head_dim) keys = input_lin_kv_results[:,:,0,:] values = input_lin_kv_results[:,:,1,:] # Slice out k,v from one big set of gradients entering the input linear's bprop (should only impact meta data, no copies!) # The gradients are identical in size to the Input Linear outputs. # The tensor is declared before hand to properly slice out query, key, and value grads. input_lin_kv_results_grads = torch.empty_like(input_lin_kv_results) queries_grads = torch.empty_like(queries) keys_grads = input_lin_kv_results_grads[:,:,0,:] values_grads = input_lin_kv_results_grads[:,:,1,:] # Output Linear GEMM - DGRAD # Input1: (data grads) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) output_lin_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), output_weights) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1), output_weights.size(1)) # Output Linear GEMM - WGRAD # Input1: (data grads) [seql_q*seqs, embed_dim=heads*head_dim] transpose(0,1) # Input2: (activations) [seql_q*seqs, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = ( embed_dim x embed_dim ) output_weight_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)).transpose(0,1), matmul2_results.view(matmul2_results.size(0) * matmul2_results.size(1), matmul2_results.size(2))) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1)*heads_t[0], head_dim).transpose(0,1) if use_biases_t[0]: output_bias_grads = torch.sum(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), 0) else: output_bias_grads = None # Matmul2 - DGRAD1 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul2_dgrad1 = torch.bmm(output_lin_grads, values.transpose(0,1).transpose(1,2)) # Matmul2 - DGRAD2 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) values_grads = torch.bmm(dropout_results.transpose(1,2), output_lin_grads, out=values_grads.transpose(0,1)) # Mask and Scaling for Dropout (not a publically documented op) dropout_grads = torch._masked_scale(matmul2_dgrad1, dropout_mask, 1.0/(1.0-dropout_prob_t[0])) # Softmax Grad (not a publically documented op) softmax_grads = torch._softmax_backward_data(dropout_grads, softmax_results, -1, softmax_results) # Matmul1 - DGRAD1 # Input1: (data grads) [seqs*heads, seql_q, seql_k] # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_q, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = ( seql_q x head_dim ) queries_grads = torch.baddbmm(queries_grads.transpose(0,1), softmax_grads, keys.transpose(0,1), out=queries_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Matmul1 - DGRAD2 # Input1: (data grads) [seqs*heads, seql_q, seql_k] transpose(1,2) # Input2: (activations) [seql_q, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_k, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_k x seql_q ) x ( seql_q x head_dim ) = ( seql_k x head_dim ) keys_grads = torch.baddbmm(keys_grads.transpose(0,1), softmax_grads.transpose(1,2), queries.transpose(0,1), out=keys_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Input Q Linear GEMM - DGRAD # input1: (data grads) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim (1024), embed_dim (1024)] # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) queries_grads = queries_grads.transpose(0,1).view(inputs_q.size(0)*inputs_q.size(1), heads_t[0]*head_dim) input_q_grads = torch.mm(queries_grads, input_weights_q) input_q_grads = input_q_grads.view(inputs_q.size(0), inputs_q.size(1), inputs_q.size(2)) # Input KV Linear GEMM - DGRAD # input1: (data grads) [seql_k, seqs, 2*embed_dim(2048)] # input2: (weights) [embed_dim*2 (2048), embed_dim (1024)] # output: [seql_k, seqs, embed_dim] # GEMM: ( (seql_k*seqs) x 2*embed_dim ) x ( 2*embed_dim x embed_dim ) = (seql_k*seqs x embed_dim) input_lin_kv_results_grads = input_lin_kv_results_grads.view(inputs_kv.size(0)*inputs_kv.size(1), heads_t[0]*2*head_dim) input_kv_grads = torch.mm(input_lin_kv_results_grads, input_weights_kv) input_kv_grads = input_kv_grads.view(inputs_kv.size(0), inputs_kv.size(1), inputs_kv.size(2)) # Input Q Linear GEMM - WGRAD # input1: (data grads) [seql_q*seqs, embed_dim(1024)] # input2: (activations) [seql_q*seqs, embed_dim(1024)] # output: [embed_dim, embed_dim] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = (embed_dim x embed_dim) input_weight_q_grads = torch.mm(queries_grads.transpose(0,1), inputs_q.view(inputs_q.size(0)*inputs_q.size(1), inputs_q.size(2))) # Input KV Linear GEMM - WGRAD # input1: (data grads) [seql_k*seqs, 2*embed_dim(2048)] # input2: (activations) [seql_k*seqs, embed_dim(1024)] # output: [2*embed_dim, embed_dim] # GEMM: ( 2*embed_dim x seql_k*seqs ) x ( seql_k*seqs x embed_dim ) = (2*embed_dim x embed_dim) input_weight_kv_grads = torch.mm(input_lin_kv_results_grads.transpose(0,1), inputs_kv.view(inputs_kv.size(0)*inputs_kv.size(1), inputs_kv.size(2))) if use_biases_t[0]: input_bias_grads_q = torch.sum(queries_grads, 0) input_bias_grads_kv = torch.sum(input_lin_kv_results_grads, 0) else: input_bias_grads_q = None input_bias_grads_kv = None return None, None, None, None, \ input_q_grads, input_kv_grads, \ input_weight_q_grads, input_weight_kv_grads, output_weight_grads, \ input_bias_grads_q, input_bias_grads_kv, output_bias_grads, \ None, None encdec_attn_func = EncdecAttnFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/fast_encdec_multihead_attn_func.py ================================================ import torch import fast_encdec_multihead_attn class FastEncdecAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) input_lin_q_results, \ input_lin_kv_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_encdec_multihead_attn.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors input_q_grads, \ input_kv_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads = \ fast_encdec_multihead_attn.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) return None, None, None, input_q_grads, input_kv_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads, None, None fast_encdec_attn_func = FastEncdecAttnFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/fast_encdec_multihead_attn_norm_add_func.py ================================================ # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import fast_encdec_multihead_attn_norm_add class FastEncdecAttnNormAddFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ input_lin_q_results, \ input_lin_kv_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ dropout_add_mask, \ outputs = \ fast_encdec_multihead_attn_norm_add.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t = ctx.saved_tensors input_q_grads, \ input_kv_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads = \ fast_encdec_multihead_attn_norm_add.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t[0]) #import pdb; pdb.set_trace() return None, None, None, \ input_q_grads, \ input_kv_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads, \ None, None fast_encdec_attn_norm_add_func = FastEncdecAttnNormAddFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/fast_self_multihead_attn_func.py ================================================ import torch import fast_self_multihead_attn import fast_self_multihead_attn_bias import fast_self_multihead_attn_bias_additive_mask class FastSelfAttnFunc(torch.autograd.Function) : @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, pad_mask, mask_additive, dropout_prob): use_biases_t = torch.tensor([input_biases is not None]) heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) mask_additive_t= torch.tensor([mask_additive]) if use_biases_t[0]: if not mask_additive: input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn_bias.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ input_biases, \ output_biases, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ null_tensor, \ null_tensor, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) else: input_lin_results, \ bmm1_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn_bias_additive_mask.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ input_biases, \ output_biases, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ null_tensor, \ bmm1_results, \ pad_mask, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) else: input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ null_tensor, \ null_tensor, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ bmm1_results, \ pad_mask, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors if use_biases_t[0]: if not mask_additive_t[0]: input_grads, \ input_weight_grads, \ output_weight_grads, \ input_bias_grads, \ output_bias_grads = \ fast_self_multihead_attn_bias.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) else: input_grads, \ input_weight_grads, \ output_weight_grads, \ input_bias_grads, \ output_bias_grads = \ fast_self_multihead_attn_bias_additive_mask.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ bmm1_results, \ pad_mask, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) else: input_bias_grads = None output_bias_grads = None input_grads, \ input_weight_grads, \ output_weight_grads = \ fast_self_multihead_attn.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) return None, None, None, input_grads, input_weight_grads, output_weight_grads,input_bias_grads, output_bias_grads, None, None, None fast_self_attn_func = FastSelfAttnFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/fast_self_multihead_attn_norm_add_func.py ================================================ import torch import fast_self_multihead_attn_norm_add class FastSelfAttnNormAddFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ dropout_add_mask, \ outputs = \ fast_self_multihead_attn_norm_add.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t = ctx.saved_tensors input_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_grads, \ output_weight_grads = \ fast_self_multihead_attn_norm_add.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t[0]) return None, None, None, \ input_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_grads, \ output_weight_grads, \ None, None fast_self_attn_norm_add_func = FastSelfAttnNormAddFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/mask_softmax_dropout_func.py ================================================ import torch import fast_mask_softmax_dropout import fast_additive_mask_softmax_dropout class MaskSoftmaxDropout(torch.autograd.Function) : @staticmethod def forward(ctx, is_training, heads, inputs, pad_mask, mask_additive, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) use_mask_t = torch.tensor([use_mask]) mask_additive_t = torch.tensor([mask_additive]) if mask_additive: dropout_results, \ dropout_mask, \ softmax_results = \ fast_additive_mask_softmax_dropout.forward( \ use_mask, \ is_training, \ heads, \ inputs, \ pad_mask if use_mask else null_tensor, \ dropout_prob) else: dropout_results, \ dropout_mask, \ softmax_results = \ fast_mask_softmax_dropout.forward( \ use_mask, \ is_training, \ heads, \ inputs, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward( use_mask_t, \ heads_t, \ softmax_results, \ dropout_mask, \ pad_mask if use_mask else null_tensor, \ mask_additive_t, \ dropout_prob_t) return dropout_results.detach() @staticmethod def backward(ctx, output_grads): use_mask_t, \ heads_t, \ softmax_results, \ dropout_mask, \ pad_mask, \ mask_additive_t, \ dropout_prob_t = ctx.saved_tensors if mask_additive_t[0]: input_grads = \ fast_additive_mask_softmax_dropout.backward( \ use_mask_t[0], \ heads_t[0], \ output_grads, \ softmax_results, \ dropout_mask, \ dropout_prob_t[0]) else: input_grads = \ fast_mask_softmax_dropout.backward( \ use_mask_t[0], \ heads_t[0], \ output_grads, \ softmax_results, \ dropout_mask, \ pad_mask, \ dropout_prob_t[0]) return None, None, input_grads, None, None, None fast_mask_softmax_dropout_func = MaskSoftmaxDropout.apply ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/self_multihead_attn.py ================================================ import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .self_multihead_attn_func import self_attn_func from .fast_self_multihead_attn_func import fast_self_attn_func from .fast_self_multihead_attn_norm_add_func import fast_self_attn_norm_add_func from apex.normalization.fused_layer_norm import FusedLayerNorm if hasattr(torch._C, '_jit_set_profiling_executor') : torch._C._jit_set_profiling_executor(False) if hasattr(torch._C, '_jit_set_profiling_mode') : torch._C._jit_set_profiling_mode(False) @torch.jit.script def jit_dropout_add(x, residual, prob, is_training): # type: (Tensor, Tensor, float, bool) -> Tensor out = F.dropout(x, p=prob, training=True) out = residual + out return out class SelfMultiheadAttn(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, dropout=0., bias=False, include_norm_add=False, impl='fast', separate_qkv_params=False, mask_additive=False): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.bias = bias self.include_norm_add = include_norm_add self.impl = impl self.scaling = self.head_dim**-0.5 self.separate_qkv_params = separate_qkv_params self.mask_additive = mask_additive if mask_additive: assert self.include_norm_add == False, "additive mask not supported with layer norm" assert impl == 'default' or (impl == 'fast' and bias), "additive mask not supported for fast mode without bias" if separate_qkv_params: self.q_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) self.k_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) self.v_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) else: self.in_proj_weight = Parameter(torch.Tensor(3*embed_dim, embed_dim)) self.out_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) if self.bias: if separate_qkv_params: self.q_bias = Parameter(torch.Tensor(embed_dim)) self.k_bias = Parameter(torch.Tensor(embed_dim)) self.v_bias = Parameter(torch.Tensor(embed_dim)) else: self.in_proj_bias = Parameter(torch.Tensor(3*embed_dim)) self.out_proj_bias = Parameter(torch.Tensor(embed_dim)) else: if separate_qkv_params: self.register_parameter('q_bias', None) self.register_parameter('k_bias', None) self.register_parameter('v_bias', None) self.q_bias = None self.k_bias = None self.v_bias = None else: self.register_parameter('in_proj_bias', None) self.in_proj_bias = None self.register_parameter('out_proj_bias', None) self.out_proj_bias = None if self.include_norm_add: if impl == 'fast': self.lyr_nrm_gamma_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm_beta_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm = None else: self.register_parameter('lyr_norm_gamma_weights', None) self.register_parameter('lyr_norm_beta_weights', None) self.lyr_nrm_gamma_weights = None self.lyr_nrm_beta_weights = None self.lyr_nrm = FusedLayerNorm(embed_dim) self.reset_parameters() if self.include_norm_add: if impl == 'fast' : self.attn_func = fast_self_attn_norm_add_func elif impl == 'default' : self.attn_func = self_attn_func else : assert False, "Unsupported impl: {} !".format(impl) else: if impl == 'fast' : self.attn_func = fast_self_attn_func elif impl == 'default' : self.attn_func = self_attn_func else : assert False, "Unsupported impl: {} !".format(impl) def reset_parameters(self): if self.separate_qkv_params: nn.init.xavier_uniform_(self.q_weight) nn.init.xavier_uniform_(self.k_weight) nn.init.xavier_uniform_(self.v_weight) else: # in_proj_weight has shape [3 * hidden, hidden] but it should be # initialized like a [hidden, hidden] matrix. # sqrt(6 / (hidden + hidden)) / sqrt(6 / (3 * hidden + hidden)) = sqrt(2) # therefore xavier_uniform gain should be set to sqrt(2). nn.init.xavier_uniform_(self.in_proj_weight, gain=math.sqrt(2)) nn.init.xavier_uniform_(self.out_proj_weight) if self.bias: if self.separate_qkv_params: nn.init.constant_(self.q_bias, 0.) nn.init.constant_(self.k_bias, 0.) nn.init.constant_(self.v_bias, 0.) else: nn.init.constant_(self.in_proj_bias, 0.) nn.init.constant_(self.out_proj_bias, 0.) if self.include_norm_add: if self.impl == 'fast': nn.init.ones_(self.lyr_nrm_gamma_weights) nn.init.zeros_(self.lyr_nrm_beta_weights) else: self.lyr_nrm.reset_parameters() def forward(self, query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ if self.separate_qkv_params: input_weights = torch.cat([self.q_weight.view(self.num_heads,1,self.head_dim,self.embed_dim), self.k_weight.view(self.num_heads,1,self.head_dim,self.embed_dim), self.v_weight.view(self.num_heads,1,self.head_dim,self.embed_dim)], dim=1).reshape(3*self.embed_dim,self.embed_dim).contiguous() else: input_weights = self.in_proj_weight if self.bias: if self.separate_qkv_params: input_bias = torch.cat([self.q_bias.view(self.num_heads,1,self.head_dim), self.k_bias.view(self.num_heads,1,self.head_dim), self.v_bias.view(self.num_heads,1,self.head_dim)],dim=1).reshape(3*self.embed_dim).contiguous() else: input_bias = self.in_proj_bias else: input_bias=None if key_padding_mask is not None: assert (attn_mask is None), "ERROR attn_mask and key_padding_mask should not be both defined!" mask = key_padding_mask elif attn_mask is not None: assert self.mask_additive == False, "additive mask not supported for time mask" mask = attn_mask else: mask = None if self.include_norm_add: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, self.lyr_nrm_gamma_weights, self.lyr_nrm_beta_weights, input_weights, self.out_proj_weight, mask, self.dropout) else: lyr_nrm_results = self.lyr_nrm(query) outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, lyr_nrm_results, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.dropout) if is_training: outputs = jit_dropout_add(outputs, query, self.dropout, is_training) else: outputs = outputs + query else: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.mask_additive, self.dropout) else: outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, query, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.mask_additive, self.dropout) return outputs,None ================================================ FILE: KoSentenceT5/apex/contrib/multihead_attn/self_multihead_attn_func.py ================================================ import torch import torch.nn.functional as F class SelfAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, scale, inputs, input_weights, output_weights, input_biases, output_biases, mask, is_additive_mask, dropout_prob): use_biases_t = torch.tensor([input_biases is not None]) heads_t = torch.tensor([heads]) scale_t = torch.tensor([scale]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) head_dim = inputs.size(2) // heads # Input Linear GEMM # input1: (activations) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] (transpose [0,1]) # output: [seql_q, seqs, embed_dim*3] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim*3 ) = (seql_q*seqs x embed_dim*3) if use_biases_t[0]: input_lin_results = torch.addmm(input_biases, inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0,1), beta=1., alpha=1.) else: input_lin_results = torch.mm(inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0,1)) input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1), input_weights.size(0)) # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1)*heads, 3, head_dim) queries = input_lin_results[:,:,0,:] keys = input_lin_results[:,:,1,:] values = input_lin_results[:,:,2,:] # Matmul1 Batched GEMMs # The output tensor is specified prior to the Batch GEMM because baddbmm requires its specification # baddbmm is used to apply the scale parameter via the Batched GEMM's alpha parameter instead of # a separate elementwise operation. # Input1: (Queries) [seql_q, seqs*heads, head_dim] tranpose(0,1) # Input2: (Keys) [seql_k, seqs*heads, head_dim] transpose(0,1) # output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul1_results = torch.empty((queries.size(1),queries.size(0),keys.size(0)), dtype=queries.dtype, device=torch.device('cuda')) matmul1_results = torch.baddbmm(matmul1_results, queries.transpose(0,1), keys.transpose(0,1).transpose(1,2), out=matmul1_results, beta=0.0, alpha=scale_t[0]) if mask is not None: # Self Attention Time Mask if use_time_mask: assert (len(mask.size()) == 2), "Timing mask is not 2D!" assert (mask.size(0) == mask.size(1)), "Sequence length should match!" mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask, float('-inf')) # Key Padding Mask else: batches,seql_q,seql_k = matmul1_results.size() seqs = int(batches / heads) matmul1_results = matmul1_results.view(seqs, heads, seql_q, seql_k) if is_additive_mask: matmul1_results = matmul1_results + mask.unsqueeze(1).unsqueeze(2) else: mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask.unsqueeze(1).unsqueeze(2), float('-inf')) matmul1_results = matmul1_results.view(seqs*heads, seql_q, seql_k) softmax_results = F.softmax(matmul1_results, dim=-1) # Dropout - is not executed for inference if is_training: dropout_results,dropout_mask = torch._fused_dropout(softmax_results, p=(1.-dropout_prob_t[0])) else: dropout_results = softmax_results dropout_mask = null_tensor # Matmul2 Batched GEMMs # The output tensor specification is needed here to specify the non-standard output. # Given that pytorch cannot currently perform autograd with an output tensor specified, # this requires a backward pass specified. # Input1: from_softmax [seqs*heads, seql_q, seql_k] # Input2: (values) [seql_v, seqs*heads, head_dim] transpose(0,1) # Output: [seql_q, seqs*heads, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = (seql_q x head_dim) matmul2_results = torch.empty((dropout_results.size(1), dropout_results.size(0), values.size(2)), dtype=dropout_results.dtype, device=torch.device('cuda')).transpose(1,0) matmul2_results = torch.bmm(dropout_results, values.transpose(0,1), out=matmul2_results) matmul2_results = matmul2_results.transpose(0, 1).contiguous().view(inputs.size(0), inputs.size(1), inputs.size(2)) # Output Linear GEMM # Input1: (activations) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] transpose(0,1) # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) if use_biases_t[0]: outputs = torch.addmm(output_biases, matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0,1), beta=1., alpha=1.) else: outputs = torch.mm(matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0,1)) outputs = outputs.view(inputs.size(0), inputs.size(1), output_weights.size(0)) ctx.save_for_backward(use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors head_dim = inputs.size(2) // heads_t[0] # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1)*heads_t[0], 3, head_dim) queries = input_lin_results[:,:,0,:] keys = input_lin_results[:,:,1,:] values = input_lin_results[:,:,2,:] # Slice out q,k,v from one big set of gradients entering the input linear's bprop (should only impact meta data, no copies!) # The gradients are identical in size to the Input Linear outputs. # The tensor is declared before hand to properly slice out query, key, and value grads. input_lin_results_grads = torch.empty_like(input_lin_results) queries_grads = input_lin_results_grads[:,:,0,:] keys_grads = input_lin_results_grads[:,:,1,:] values_grads = input_lin_results_grads[:,:,2,:] # Output Linear GEMM - DGRAD # Input1: (data grads) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) output_lin_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), output_weights) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1), output_weights.size(1)) # Output Linear GEMM - WGRAD # Input1: (data grads) [seql_q*seqs, embed_dim=heads*head_dim] transpose(0,1) # Input2: (activations) [seql_q*seqs, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = ( embed_dim x embed_dim ) output_weight_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)).transpose(0,1), matmul2_results.view(matmul2_results.size(0) * matmul2_results.size(1), matmul2_results.size(2))) output_lin_grads = output_lin_grads.view(inputs.size(0), inputs.size(1)*heads_t[0], head_dim).transpose(0,1) if use_biases_t[0]: output_bias_grads = torch.sum(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), 0) else: output_bias_grads = None # Matmul2 - DGRAD1 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul2_dgrad1 = torch.bmm(output_lin_grads, values.transpose(0,1).transpose(1,2)) # Matmul2 - DGRAD2 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) values_grads = torch.bmm(dropout_results.transpose(1,2), output_lin_grads, out=values_grads.transpose(0,1)) # Mask and Scaling for Dropout (not a publically documented op) dropout_grads = torch._masked_scale(matmul2_dgrad1, dropout_mask, 1.0/(1.0-dropout_prob_t[0])) # Softmax Grad (not a publically documented op) softmax_grads = torch._softmax_backward_data(dropout_grads, softmax_results, -1, softmax_results) # Matmul1 - DGRAD1 # Input1: (data grads) [seqs*heads, seql_q, seql_k] # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_q, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = ( seql_q x head_dim ) queries_grads = torch.baddbmm(queries_grads.transpose(0,1), softmax_grads, keys.transpose(0,1), out=queries_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Matmul1 - DGRAD2 # Input1: (data grads) [seqs*heads, seql_q, seql_k] transpose(1,2) # Input2: (activations) [seql_q, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_k, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_k x seql_q ) x ( seql_q x head_dim ) = ( seql_k x head_dim ) keys_grads = torch.baddbmm(keys_grads.transpose(0,1), softmax_grads.transpose(1,2), queries.transpose(0,1), out=keys_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Input Linear GEMM - DGRAD # input1: (data grads) [seql_q, seqs, 3*embed_dim(3072)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x 3*embed_dim ) x ( 3*embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) input_lin_results_grads = input_lin_results_grads.view(inputs.size(0)*inputs.size(1), heads_t[0]*3*head_dim) input_grads = torch.mm(input_lin_results_grads, input_weights) input_grads = input_grads.view(inputs.size(0), inputs.size(1), inputs.size(2)) # Input Linear GEMM - WGRAD # input1: (data grads) [seql_q*seqs, 3*embed_dim(3072)] # input2: (activations) [seql_q*seqs, embed_dim(1024)] # output: [3*embed_dim, embed_dim] # GEMM: ( 3*embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = (3*embed_dim x embed_dim) input_weight_grads = torch.mm(input_lin_results_grads.transpose(0,1), inputs.view(inputs.size(0)*inputs.size(1), inputs.size(2))) if use_biases_t[0]: input_bias_grads = torch.sum(input_lin_results_grads, 0) else: input_bias_grads = None return None, None, None, None, \ input_grads, \ input_weight_grads, output_weight_grads, \ input_bias_grads, output_bias_grads, \ None, None self_attn_func = SelfAttnFunc.apply ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/__init__.py ================================================ from .fp16_optimizer import FP16_Optimizer from .fused_adam import FusedAdam from .fused_lamb import FusedLAMB ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/distributed_fused_adam.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier import torch.distributed.distributed_c10d as c10d class DistributedFusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) step_supports_amp_scaling(boolean, optional): whether to use customized gradient unscaling logic (default: True) num_process_groups (integer, optional): number of process groups in the app (default: 1) current_process_group (object, optional): the process group to work on (default: None) process_group_id (integer, optional): process group id (default: 0) process_group_size (integer, optional): size of process group (default: 0) clip_grad_norm (boolean, optional): whether to handle gradient clipping (default: True) model_parallel (boolean, optional): whether model parallelism is used (default: False) .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt=False, weight_decay=0., max_grad_norm=0., amsgrad=False, flat_mt=False, overlap_reductions=True, compute_L2_grad_norm=False, dwu_group_size=0, dwu_num_blocks=4, dwu_num_chunks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, predivide=True, e5m2_allgather=False, do_not_flatten_model=False, step_supports_amp_scaling=True, num_process_groups=1, current_process_group=None, process_group_id=0, process_group_size=0, clip_grad_norm=True, model_parallel=False): global fused_adam_cuda, distributed_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") distributed_adam_cuda = importlib.import_module("distributed_adam_cuda") self.multi_tensor_l2norm = amp_C.multi_tensor_l2norm if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdam, self).__init__(params, defaults) # Misc self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False self._step_supports_amp_scaling = step_supports_amp_scaling self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._compute_L2_grad_norm = compute_L2_grad_norm self._L2_grad_norm = None self._flat_mt = flat_mt self._init_done = False self._resume_from_checkpoint = False self._step = 0 # Process group related self._clip_grad_norm = clip_grad_norm self._model_parallel = model_parallel self._num_process_groups = num_process_groups self._current_process_group = current_process_group if current_process_group is not None else c10d._get_default_group() self._available_ranks = list(c10d._pg_group_ranks[self._current_process_group].keys()) self._process_group_id = process_group_id self._process_group_size = torch.cuda.device_count() if process_group_size <= 0 else process_group_size self._world_size = self._process_group_size # world: the current process group self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._num_groups = self._world_size // self._group_size self._global_rank = torch.distributed.get_rank() self._world_rank = self._global_rank // self._num_process_groups self._group_rank = self._world_rank % self._group_size #print("world_size:", self._world_size, ", group_size:", self._group_size, ", num_groups:", self._num_groups, ", global_rank:", self._global_rank, ", world_rank:", self._world_rank, ", group_rank:", self._group_rank) self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg # Master weight, moment, gradient buffers self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_p, self._fp16_g = None, None, None, None, None def _first_step_init(self): p_offset = 0 p_i = 0 self._model_params = [] self._grads_info = [] self._grad_accs = [] self._group_properties = [] for group in self.param_groups: self._param_group = group prev = None beta1, beta2 = group['betas'] bias_correction = 1 if group['bias_correction'] else 0 eps = group['eps'] weight_decay = group['weight_decay'] for p in group['params']: # broadcast from rank 0 of current process group torch.distributed.broadcast(p, src=self._available_ranks[0], group=self._current_process_group) if not p.requires_grad: continue self._model_params.append(p) # Multiple param groups support: # store one hyperparam item per parameter tensor self._group_properties.append(( beta1, beta2, bias_correction, eps, weight_decay )) p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._grads = [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._chunk_size = self._block_size // self._num_chunks self._shard_size = self._chunk_size // self._group_size #print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._chunk_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._chunk_size,self._shard_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i #print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._shard_size # initialize master weights, moments buffers if not loaded from checkpoint if self._fp32_p is None: self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') self._individual_flat_grads = [] for p_i, (grads_info, p) in enumerate(zip(self._grads_info, self._model_params)): self._individual_flat_grads.append(self._flat_grads[grads_info["param_offset"]:grads_info["param_offset"]+grads_info["param_grads_size"]].view_as(p)) def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_chunks = [__chunkify(block) for block in list_of_blocks] list_of_list_of_list_of_shards = [[__shardify(chunk) for chunk in chunks] for chunks in list_of_list_of_chunks] return list_of_blocks, list_of_list_of_chunks, list_of_list_of_list_of_shards self._flat_grads_blocks, self._flat_grads_chunks, self._flat_grads_shards = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._shard_size:(block_id+1)*self._num_chunks*self._shard_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._shard_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): # in the packed format, each chunk contains one shard, so packed_chunk_size == self._shard_size return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params = [] self._contrib_tensor_list = [] self._contrib_group_properties = [] self._non_parallel_grads = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): flat_shard_start = (((block_id * self._num_chunks + chunk_id) * self._group_size) + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for (p, grads_info, group_props) in zip(self._model_params, self._grads_info, self._group_properties): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_chunks[shard_id][block_id][chunk_id][shard_offset:shard_offset+grad_length] self._packed_flat_to_model_params.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._group_rank: # copy model parameters into master buffer master_param_fragment = self._fp32_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_m_fragment = self._fp32_m_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_v_fragment = self._fp32_v_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_g_fragment = self._fp16_g_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_p_fragment = self._fp16_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] #print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) if not self._resume_from_checkpoint: master_param_fragment.copy_(model_param_fragment) self._contrib_group_properties.append(group_props) self._contrib_tensor_list.append((master_param_fragment, opti_state_m_fragment, opti_state_v_fragment, opti_state_g_fragment, opti_state_p_fragment)) # p, m, v, g, p_copy if self._model_parallel and hasattr(p, 'model_parallel') and not p.model_parallel: self._non_parallel_grads.append(opti_state_g_fragment) p, m, v, g, p_copy = list(zip(*self._contrib_tensor_list)) self._contrib_tensor_list = [p, m, v, g, p_copy] math_type = self._fp32_p.dtype beta1, beta2, bias_correction, epsilon, decay = list(zip(*self._contrib_group_properties)) self._contrib_beta1 = torch.tensor(beta1, dtype=math_type, device='cuda') self._contrib_beta2 = torch.tensor(beta2, dtype=math_type, device='cuda') self._contrib_bias_correction = torch.tensor(bias_correction, dtype=torch.int, device='cuda') self._contrib_epsilon = torch.tensor(epsilon, dtype=math_type, device='cuda') self._contrib_weight_decay = torch.tensor(decay, dtype=math_type, device='cuda') p_in, p_out = zip(*self._packed_flat_to_model_params) self._packed_flat_to_model_params = [p_in, p_out] if self._num_groups > 1: self._ar_pg = [] for i in range(self._num_process_groups): # gather global ranks of all members of the current process group ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._group_size): ar_idx = [j+k*self._group_size for k in range(self._num_groups)] ar_rank = [ranks[k] for k in ar_idx] #if self._global_rank in ar_rank: # print("group for all reduce, ranks:", ar_rank) for _ in range(self._num_ar_pg): grp = torch.distributed.new_group(ranks=ar_rank) if self._global_rank in ar_rank: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] for ar_pg in self._ar_pg: torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) self._rs_pg, rs_ranks = [],[] for i in range(self._num_process_groups): ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._num_groups): rs_idx = [j*self._group_size+k for k in range(self._group_size)] rs_rank = [ranks[k] for k in rs_idx] #if self._global_rank in rs_rank: # print("group for reduce scatter, ranks:", rs_rank) for _ in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=rs_rank) if self._global_rank in rs_rank: self._rs_pg.append(grp) if self._compute_L2_grad_norm: l2_grad_norm_pg = torch.distributed.new_group(ranks=rs_rank) if self._global_rank in rs_rank: self._l2_grad_norm_pg = l2_grad_norm_pg torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] for rs_pg in self._rs_pg: torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for i in range(self._num_process_groups): ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._num_groups): ag_rank = rs_ranks[j] #if self._global_rank in ag_rank: # print("group for all gather, ranks:", ag_rank) for _ in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ag_rank) if self._global_rank in ag_rank: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] for ag_pg in self._ag_pg: torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() if self._compute_L2_grad_norm else None self._completion_st = torch.cuda.Stream() self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" def _init_everything(self): if not self._init_done: self._first_step_init() self._init_done = True def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Optionally compute L2 grad norm if self._compute_L2_grad_norm and block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) # for model_parallel_rank=0, keep all gradients # for the rest, subtract non_parallel gradients if self._model_parallel and self._process_group_id: # non zero model_parallel_rank non_parallel_grad_norm_sq = torch.zeros([1], device='cuda') if len(self._non_parallel_grads): # non parallel grads exit non_parallel_grad_norm_sq = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._non_parallel_grads], False)[0]**2 torch.distributed.all_reduce(non_parallel_grad_norm_sq, group=self._l2_grad_norm_pg) l2_grad_norm_sq = l2_grad_norm_sq - non_parallel_grad_norm_sq self._L2_grad_norm = l2_grad_norm_sq.sqrt().item() def __launch_step_kernel(self): # If self._clip_grad_norm is False, we assume gradient clipping already # happened outside the optimizer and self._global_scale has already # been set to the combined scale, i.e. it's no longer the current loss # scale used by the loss scaler. # For model parallelism cases in which we need to get global gradient # norm via all-reduce outside the optimizer to do the clipping. combined_scale = self._global_scale if self._clip_grad_norm and self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) self._step += 1 multi_tensor_applier(distributed_adam_cuda.multi_tensor_fused_adam, self._overflow_buf, self._contrib_tensor_list, # p, m, v, g, p_copy self._contrib_beta1, self._contrib_beta2, self._contrib_bias_correction, self._contrib_epsilon, self._contrib_weight_decay, self._param_group['lr'], combined_scale, self._step, self.eps_mode) def _pipeline_step(self): # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel() torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def has_overflow(self): """Check if overflows were detected by any call to step(...) method. Clears the overflow flag. """ has_overflow = self._has_overflow self._has_overflow = False return has_overflow @property def peek_overflow(self): """Check if overflows were detected by any call to step(...) method. Does not clear overflow flag. """ return self._has_overflow def strided_check_finite(self, output_params, stride=1, start=-1, end=-1, clear=True): """Strided check for overflow. You can get status by calling has_overflow. """ if start >= 0 and start < end: out_p = output_params[start:end] else: out_p = output_params fused_adam_cuda.strided_check_finite(self._overflow_buf, out_p, stride, 1 if clear else 0) self._has_overflow = False if self._overflow_buf.item() == 0 else True return self._has_overflow @property def L2_grad_norm(self): if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm else: return None def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ self._init_everything() if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None): loss = None if closure is not None: loss = closure() self._pipeline_step() with torch.cuda.stream(self._completion_st): # Copy self._new_params to model params multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss def state_dict(self): """ Returns a dict containing the current state of this :class:`DistributedFusedAdam` instance. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ # save step, master weights and first/second moments state_dict = {} state_dict['step'] = self._step state_dict['fp32_p'] = self._fp32_p state_dict['fp32_m'] = self._fp32_m state_dict['fp32_v'] = self._fp32_v return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If an DistributedFusedAdam instance was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``optimizer.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # restore step, master weights and first/second moments self._step = state_dict['step'] self._fp32_p = state_dict['fp32_p'].to(device="cuda") self._fp32_m = state_dict['fp32_m'].to(device="cuda") self._fp32_v = state_dict['fp32_v'].to(device="cuda") self._resume_from_checkpoint = True ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/distributed_fused_adam_v2.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier class DistributedFusedAdamV2(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) num_prestats (integer, optional): number of fp64 stats that will be reduced during first fp16 gradient reduction block. .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0, overlap_reductions=True, full_pipeline=True, compute_L2_grad_norm=False, distributed_weight_update=0, dwu_group_size=0, dwu_num_blocks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, revert_method=1, flat_mt=False, dwu_num_chunks=4, predivide=True, e5m2_allgather=False, do_not_flatten_model=False): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._amp_scale_adjustment = amp_scale_adjustment if use_mt: raise RuntimeError('DistributedFusedAdam does not support use_mt.') if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdamV2, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False assert (len(self.param_groups) == 1), "More than one parameter group is not supported." # Way to revert a step # 3 -> undo kernel + double buffer (debug, print norm of difference) # 2 -> double buffer fp32 parameters # 1 -> undo kernel self._revert_method = revert_method if self._revert_method > 1: print("revert_method -> double buffer fp32 parameters, will consume more memory") self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._full_pipeline = full_pipeline self._compute_L2_grad_norm = compute_L2_grad_norm self._L2_grad_norm = None self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size p_offset = 0 p_i = 0 self._param_state = None self._model_params = [] self._grads_info = [] self._grad_accs = [] for group in self.param_groups: self._param_group = group prev = None for p in group['params']: torch.distributed.broadcast(p,0) if not p.requires_grad: continue self._model_params.append(p) state = self.state[p] if len(state) == 0: state['step'] = 0 if self._param_state is None: self._param_state = state p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._flat_mt = flat_mt self._grads = [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._shard_size = self._block_size // self._group_size self._chunk_size = self._shard_size // self._num_chunks print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._shard_size=%d, self._chunk_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._shard_size,self._chunk_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._chunk_size self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') self._individual_flat_grads = [] for p_i, (grads_info, p) in enumerate(zip(self._grads_info, self._model_params)): self._individual_flat_grads.append(self._flat_grads[grads_info["param_offset"]:grads_info["param_offset"]+grads_info["param_grads_size"]].view_as(p)) def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_shards = [__shardify(block) for block in list_of_blocks] list_of_list_of_list_of_chunks = [[__chunkify(shard) for shard in shards] for shards in list_of_list_of_shards] return list_of_blocks, list_of_list_of_shards, list_of_list_of_list_of_chunks self._flat_grads_blocks, self._flat_grads_shards, self._flat_grads_chunks = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._chunk_size:(block_id+1)*self._num_chunks*self._chunk_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._chunk_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) # current arrangement # # self._flat_grads # self._flat_grads_blocks [x self._num_blocks, self._block_size] # self._flat_grads_chunks [x self._num_chunks, self._chunk_size] # self._flat_grads_shards [x self._group_size, self._shard_size] # # self._new_params # self._new_params_mega_shards [x self._group_size, self._num_blocks*self._num_chunks*self._shard_size] # self._new_params_mega_blocks [x self._num_blocks, self._num_chunks*self._shard_size] # self._new_params_mega_chunks [x self._num_chunks, self._shard_size] # # self._fp32_p # self._fp32_p_blocks [x self._num_blocks, self._num_chunks*self._shard_size] # self._fp32_p_chunks [x self._num_chunks, self._shard_size] # each chunk contains one shard # same for self._fp32_m, self._fp32_v, self._fp16_p and self._fp16_g # # Usage: # # for chunk_id in range(self._num_chunks): # works[chunk_id] = torch.distributed.reduce_scatter(self._flat_grads_chunks[block_id][chunk_id], self._fp16_g_chunks[block_id][chunk_id], ...) # # ---------------------------------------------------------------------------------------- # # new arrangement # # NB! New equations for self._shard_size and self._chunk_size # # self._flat_grads # self._flat_grads_blocks [x self._num_blocks, self._block_size] # self._flat_grads_shards [x self._group_size, self._shard_size] # self._flat_grads_chunks [x self._num_chunks, self._chunk_size] # # self._new_params # self._new_params_mega_shards [x self._group_size, self._num_blocks*self._num_chunks*self._chunk_size] # self._new_params_mega_blocks [x self._num_blocks, self._num_chunks*self._chunk_size] # self._new_params_mega_chunks [x self._num_chunks, self._chunk_size] # # self._fp32_p # self._fp32_p_blocks [x self._num_blocks, self._num_chunks*self._chunk_size] # self._fp32_p_chunks [x self._num_chunks, self._chunk_size] # same for self._fp32_m, self._fp32_v, self._fp16_p and self._fp16_g # # Usage: # # work = torch.distributed.reduce_scatter(self._flat_grads_blocks[block_id], self._fp16_g[block_id], ...) # for chunk_id in range(self._num_chunks): # work.wait() # works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id], ...) # or # work.wait() # works[0] = torch.distributed.all_reduce(self._fp16_g_blocks[block_id], ...) # # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): flat_shard_start = (block_id * self._group_size + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for p, grads_info in zip(self._model_params, self._grads_info): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_blocks[shard_id][block_id][shard_offset:shard_offset+grad_length] self._packed_flat_to_model_params.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._rank_in_group: # copy model parameters into master buffer master_param_fragment = self._fp32_p_blocks[block_id][shard_offset:shard_offset+grad_length] print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) master_param_fragment.copy_(model_param_fragment) p_in, p_out = zip(*self._packed_flat_to_model_params) self._packed_flat_to_model_params = [p_in, p_out] self._distributed_weight_update = distributed_weight_update # Is this still needed? self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg if self._num_groups > 1: self._ar_pg = [] for dev_i in range(self._group_size): ranks = [dev_i+j*self._group_size for j in range(self._num_groups)] for i in range(self._num_ar_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] for ar_pg in self._ar_pg: torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) rs_ranks = [] for group_i in range(self._num_groups): rs_ranks.append([group_i*self._group_size+j for j in range(self._group_size)]) self._rs_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._rs_pg.append(grp) if self._compute_L2_grad_norm and torch.distributed.get_rank() in ranks: self._l2_grad_norm_pg = torch.distributed.new_group(ranks=ranks) torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] for rs_pg in self._rs_pg: torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] for ag_pg in self._ag_pg: torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() if self._compute_L2_grad_norm else None self._completion_st = torch.cuda.Stream() self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks rs_stream = self._rs_st[block_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): rs_work = torch.distributed.reduce_scatter(self._fp16_g_blocks[block_id],self._flat_grads_shards[block_id],group=self._rs_pg[block_id%self._num_rs_pg],async_op=True,no_copy=True) for chunk_id in range(self._num_chunks): works[chunk_id] = rs_work # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): rs_work.wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Optionally compute L2 grad norm if self._compute_L2_grad_norm and block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) self._L2_grad_norm = l2_grad_norm_sq.sqrt().item() def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def _pipeline_block_step(self, block_id): # Call step kernel once per block ag_stream = self._ag_st[block_id%self._num_ag_pg] with torch.cuda.stream(ag_stream): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel( self._fp32_p_blocks[block_id], self._fp16_p_blocks[block_id], self._fp32_m_blocks[block_id], self._fp32_v_blocks[block_id], self._fp16_g_blocks[block_id]) # Call all-gather once per step. # FIXME: Determine which is faster, one all-gather per block or a single all-gather at end if block_id == 0: for other_ag_stream in self._ag_st: self._completion_st.wait_stream(other_ag_stream) with torch.cuda.stream(self._completion_st): torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _pipeline_step(self): # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel( self._fp32_p, self._fp16_p, self._fp32_m, self._fp32_v, self._fp16_g) torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) if self._full_pipeline: self._pipeline_block_step(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def has_overflow(self): """Check if overflows were detected by any call to step(...) method. Clears the overflow flag. """ has_overflow = self._has_overflow self._has_overflow = False return has_overflow @property def peek_overflow(self): """Check if overflows were detected by any call to step(...) method. Does not clear overflow flag. """ return self._has_overflow def strided_check_finite(self, output_params, stride=1, start=-1, end=-1, clear=True): """Strided check for overflow. You can get status by calling has_overflow. """ if start >= 0 and start < end: out_p = output_params[start:end] else: out_p = output_params fused_adam_cuda.strided_check_finite(self._overflow_buf, out_p, stride, 1 if clear else 0) self._has_overflow = False if self._overflow_buf.item() == 0 else True return self._has_overflow @property def L2_grad_norm(self): if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm else: return None def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def revert_step(self): """Revert effect of previously calling partial_step. """ # Call undo kernel once per step combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.maybe_adam_undo( torch.empty([0]), self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def step(self, closure=None, skip_overflow_check=False): loss = None if closure is not None: loss = closure() if self._last_step or not self._overlap_reductions or not self._full_pipeline: self._pipeline_step() with torch.cuda.stream(self._completion_st): # Check for overflow # Store state for loss scaler calculation has_overflow = False if skip_overflow_check else self.strided_check_finite(self._new_params, stride=self._shard_size, start=0, end=self._net_total_param_size) if has_overflow: self.revert_step() else: # Copy self._new_params to model params for p in self._model_params: self.state[p]['step'] += 1 multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/distributed_fused_adam_v3.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier class DistributedFusedAdamV3(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) num_prestats (integer, optional): number of fp64 stats that will be reduced during first fp16 gradient reduction block. .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0, overlap_reductions=True, full_pipeline=True, compute_L2_grad_norm=False, distributed_weight_update=0, dwu_group_size=0, dwu_num_blocks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, revert_method=1, flat_mt=False, dwu_num_chunks=4, predivide=True, e5m2_allgather=False, do_not_flatten_model=False): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._amp_scale_adjustment = amp_scale_adjustment if use_mt: raise RuntimeError('DistributedFusedAdam does not support use_mt.') if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdamV3, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) assert (len(self.param_groups) == 1), "More than one parameter group is not supported." # Way to revert a step # 3 -> undo kernel + double buffer (debug, print norm of difference) # 2 -> double buffer fp32 parameters # 1 -> undo kernel self._revert_method = revert_method if self._revert_method > 1: print("revert_method -> double buffer fp32 parameters, will consume more memory") self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._full_pipeline = full_pipeline self._L2_grad_norm = None self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size p_offset = 0 p_i = 0 self._param_state = None self._model_params = [] self._grads_info = [] self._grad_accs = [] for group in self.param_groups: self._param_group = group prev = None for p in group['params']: torch.distributed.broadcast(p,0) if not p.requires_grad: continue self._model_params.append(p) state = self.state[p] if len(state) == 0: state['step'] = 0 if self._param_state is None: self._param_state = state p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._flat_mt = flat_mt self._grads = [] self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._shard_size = self._total_param_size // self._group_size print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._shard_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._flat_params = torch.zeros_like(self._flat_grads) def _flat_split(flat): def __flat_blockify(flat): return [flat[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __flat_shardify(flat): return [flat[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] return __flat_blockify(flat), __flat_shardify(flat) self._flat_grads_blocks, self._flat_grads_shards = _flat_split(self._flat_grads) self._flat_params_blocks, self._flat_params_shards = _flat_split(self._flat_params) # master params self._fp32_p = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') # copy model params to flat_params and set_ model params to flat_params. self._individual_flat_grads = [] with torch.no_grad(): for p, grads_info in zip(self._model_params, self._grads_info): start = grads_info["param_offset"] end = start + grads_info["param_grads_size"] flat_p = self._flat_params[start:end].view_as(p) flat_p.copy_(p) p.set_(flat_p) flat_grad = self._flat_grads[start:end] self._individual_flat_grads.append(flat_grad) self._fp32_p.copy_(self._flat_params_shards[self._rank_in_group].float()) self._dwu_st = torch.cuda.Stream() self._l2_grad_norm_st = torch.cuda.Stream() for group_i in range(self._num_groups): ranks = [group_i*self._group_size+local_rank for local_rank in range(self._group_size)] pg = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg = pg torch.distributed.all_reduce(self._overflow_buf, group=self._ag_pg) import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" @property def has_overflow(self): return True if not self.L2_grad_norm is None and not math.isfinite(self.L2_grad_norm) else False def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step and self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._dwu_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._dwu_st): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) torch.distributed.all_reduce(self._flat_grads_blocks[block_id]) if block_id == 0: self._l2_grad_norm_st.wait_stream(self._dwu_st) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float32, p=2).item() flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def L2_grad_norm(self): torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, flat_grad in enumerate(self._individual_flat_grads): if not self._grads_generated[param_i]: flat_grad.zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions self._dwu_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._dwu_st): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) torch.distributed.all_reduce(self._flat_grads) self._l2_grad_norm_st.wait_stream(self._dwu_st) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float32, p=2).item() self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None, skip_overflow_check=False): loss = None if closure is not None: loss = closure() with torch.cuda.stream(self._dwu_st): self.__launch_step_kernel( self._fp32_p, self._flat_params_shards[self._rank_in_group], self._fp32_m, self._fp32_v, self._flat_grads_shards[self._rank_in_group]) torch.distributed.all_gather(self._flat_params_shards, self._flat_params_shards[self._rank_in_group], group=self._ag_pg, no_copy=True) for p in self._model_params: self.state[p]['step'] += 1 torch.cuda.current_stream().wait_stream(self._dwu_st) return loss ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/distributed_fused_lamb.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier import torch.distributed.distributed_c10d as c10d class DistributedFusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) use_nvlamb (boolean, optional): Apply adaptive learning rate to 0.0 weight decay parameter (default: False) step_supports_amp_scaling(boolean, optional): whether to use customized gradient unscaling logic (default: True) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ class AtomicCounter(object): def __init__(self): self.value = 0 self.order = [] import threading self._lock = threading.Lock() def add(self, idx): with self._lock: self.value += 1 self.order.append(idx) def __init__(self, params, lr=1e-3, bias_correction = True, grad_averaging=True, betas=(0.9, 0.999), eps=1e-8, weight_decay=0., max_grad_norm=0., adam_w_mode=True, use_nvlamb=False, step_supports_amp_scaling=True, overlap_reductions=True, dwu_group_size=0, dwu_num_blocks=4, dwu_num_chunks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, e5m2_allgather=False, verbose=False, clip_after_ar=True): defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(DistributedFusedLAMB, self).__init__(params, defaults) global fused_adam_cuda, distributed_lamb_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") distributed_lamb_cuda = importlib.import_module("distributed_lamb_cuda") self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False self.multi_tensor_lamb_compute_update_term = distributed_lamb_cuda.multi_tensor_lamb_compute_update_term self.multi_tensor_lamb_update_weights = distributed_lamb_cuda.multi_tensor_lamb_update_weights import amp_C self.multi_tensor_l2norm = amp_C.multi_tensor_l2norm self._grad_averaging = grad_averaging self._adam_w_mode = 1 if adam_w_mode else 0 self._use_nvlamb = use_nvlamb self._step_supports_amp_scaling = step_supports_amp_scaling self._is_accumulation_step = False self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._e5m2_allgather = e5m2_allgather self._verbose = verbose self._clip_after_ar = clip_after_ar self._L2_grad_norm = None self._current_process_group = c10d._get_default_group() self._available_ranks = list(c10d._pg_group_ranks[self._current_process_group].keys()) self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size self._lr = torch.tensor(0.0, dtype=torch.float32, device='cuda') self._resume_from_checkpoint = False self._step = torch.cuda.IntTensor([0]) # Master weight, moment, gradient buffers self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_p, self._fp16_g = None, None, None, None, None import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg if self._num_groups > 1: self._ar_pg = [] for dev_i in range(self._group_size): ranks = [dev_i+j*self._group_size for j in range(self._num_groups)] for i in range(self._num_ar_pg): if self._verbose: print(f"creating new group {i}: {ranks}") grp = torch.distributed.new_group(ranks=ranks) if grp != torch.distributed.GroupMember.NON_GROUP_MEMBER: if self._verbose: print(f"group {i}: init barrier (device: {torch.cuda.current_device()})") torch.distributed.barrier(group=grp, device_ids=[torch.cuda.current_device()]) if self._verbose: print(f"created new group {i}") if torch.distributed.get_rank() in ranks: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] #for ar_pg in self._ar_pg: # torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) rs_ranks = [] for group_i in range(self._num_groups): rs_ranks.append([group_i*self._group_size+j for j in range(self._group_size)]) self._rs_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._rs_pg.append(grp) l2_grad_norm_pg = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._l2_grad_norm_pg = l2_grad_norm_pg #torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] #for rs_pg in self._rs_pg: # torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] #for ag_pg in self._ag_pg: # torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() self._completion_st = torch.cuda.Stream() self._step.record_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks self._one = torch.cuda.IntTensor([1]) self._first_step = True self._lazy_init_stage1_done, self._lazy_init_stage2_done = False, False self._param_order = self.AtomicCounter() def _lazy_init_stage1(self): if self._lazy_init_stage1_done: return p_offset = 0 p_i = 0 self._model_params = [] self._grad_accs = [] self._group_properties = [] for group in self.param_groups: prev = None beta1, beta2 = group['betas'] beta3 = 1.0 - beta1 if self._grad_averaging else 1.0 bias_correction = 1 if group['bias_correction'] else 0 eps = group['eps'] weight_decay = group['weight_decay'] for p in group['params']: torch.distributed.broadcast(p, 0) if not p.requires_grad: continue self._model_params.append(p) self._group_properties.append(( weight_decay, bias_correction, beta1, beta2, beta3, eps )) p_grads_size = p.numel() def wrapper(param, param_i): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): if self._first_step: # first time self._param_order.add(param_i) else: idx = self._param_order.order.index(param_i) self._do_overlapped_reduction(idx, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) wrapper(p, p_i) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._model_params) self._grads_fp16, self._grads_fp32 = [], [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._chunk_size = self._block_size // self._num_chunks self._shard_size = self._chunk_size // self._group_size #print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._chunk_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._chunk_size,self._shard_size)) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._shard_size # initialize master weights, moments buffers if not loaded from checkpoint if self._fp32_p is None: self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_u = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_chunks = [__chunkify(block) for block in list_of_blocks] list_of_list_of_list_of_shards = [[__shardify(chunk) for chunk in chunks] for chunks in list_of_list_of_chunks] return list_of_blocks, list_of_list_of_chunks, list_of_list_of_list_of_shards self._flat_grads_blocks, self._flat_grads_chunks, self._flat_grads_shards = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._shard_size:(block_id+1)*self._num_chunks*self._shard_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._shard_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): # in the packed format, each chunk contains one shard, so packed_chunk_size == self._shard_size return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp32_u_blocks, self._fp32_u_chunks = _packed_split(self._fp32_u) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) self._lazy_init_stage1_done = True def _lazy_init_stage2(self): if self._lazy_init_stage2_done: return self._param_order.order.reverse() # re-order model_params, grad_accs, group_properties lists self._model_params = [self._model_params[i] for i in self._param_order.order] self._grad_accs = [self._grad_accs[i] for i in self._param_order.order] self._group_properties = [self._group_properties[i] for i in self._param_order.order] # re-collect grads info (size, offset) after ordering prev = None p_offset = 0 self._grads_info = [] self._individual_flat_grads = [] for i, p in enumerate(self._model_params): p_grads_size = p.numel() self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) self._individual_flat_grads.append(self._flat_grads[p_offset:p_offset+p_grads_size].view_as(p)) # for the first iteration self._do_overlapped_reduction(i, p) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i #print("self._low_param_i", self._low_param_i) # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params_fp16 = [] self._packed_flat_to_model_params_fp32 = [] self._model_params_num = len(self._model_params) self._contrib_tensor_list = [] self._contrib_min_param_i, self._contrib_max_param_i = -1, -1 self._contrib_update_frag_for_norm = [] self._contrib_model_param_for_norm_fp16 = [] self._contrib_model_param_for_norm_fp32 = [] self._contrib_model_param_for_norm_is_fp16 = [] self._model_param_is_contrib = [] self._contrib_group_properties = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): flat_shard_start = (((block_id * self._num_chunks + chunk_id) * self._group_size) + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for param_i, (p, grads_info, group_props) in enumerate(zip(self._model_params, self._grads_info, self._group_properties)): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_chunks[shard_id][block_id][chunk_id][shard_offset:shard_offset+grad_length] if model_param_fragment.dtype == torch.float16: self._packed_flat_to_model_params_fp16.append( (new_param_packed_fragment, model_param_fragment) ) else: self._packed_flat_to_model_params_fp32.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._rank_in_group: self._model_param_is_contrib.append(param_i) # copy model parameters into master buffer master_param_fragment = self._fp32_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_m_fragment = self._fp32_m_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_v_fragment = self._fp32_v_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_u_fragment = self._fp32_u_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_g_fragment = self._fp16_g_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_p_fragment = self._fp16_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] #print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) if not self._resume_from_checkpoint: master_param_fragment.copy_(model_param_fragment) self._contrib_group_properties.append(group_props) self._contrib_tensor_list.append((master_param_fragment, opti_state_m_fragment, opti_state_v_fragment, opti_state_u_fragment, opti_state_g_fragment, opti_state_p_fragment)) # p, m, v, u, g, p_copy self._contrib_update_frag_for_norm.append(opti_state_u_fragment) if p.dtype == torch.float16: self._contrib_model_param_for_norm_fp16.append(p) else: self._contrib_model_param_for_norm_fp32.append(p) self._contrib_model_param_for_norm_is_fp16.append(True if p.dtype == torch.float16 else False) if self._contrib_min_param_i < 0: self._contrib_min_param_i = param_i self._contrib_max_param_i = param_i self._contrib_model_param_for_norm_num = len(self._contrib_model_param_for_norm_is_fp16) if len(self._contrib_model_param_for_norm_fp16) == 0: self._contrib_model_param_for_norm_fp16 = None if len(self._contrib_model_param_for_norm_fp32) == 0: self._contrib_model_param_for_norm_fp32 = None self._contrib_model_param_for_norm_is_fp32 = torch.tensor([not is_fp16 for is_fp16 in self._contrib_model_param_for_norm_is_fp16], dtype=torch.bool, device='cuda') self._contrib_model_param_for_norm_is_fp16 = torch.tensor([is_fp16 for is_fp16 in self._contrib_model_param_for_norm_is_fp16], dtype=torch.bool, device='cuda') self._offsets = torch.tensor(self._model_param_is_contrib, dtype=torch.int64, device='cuda') p, m, v, u, g, p_copy = list(zip(*self._contrib_tensor_list)) self._contrib_compute_update_term_tensor_list = [g, p, m, v, u] self._contrib_update_weights_tensor_list = [u, p, p_copy] math_type = self._fp32_u.dtype decay, bias_correction, beta1, beta2, beta3, epsilon = list(zip(*self._contrib_group_properties)) self._contrib_beta1 = torch.tensor(beta1, dtype=math_type, device='cuda') self._contrib_beta2 = torch.tensor(beta2, dtype=math_type, device='cuda') self._contrib_beta3 = torch.tensor(beta3, dtype=math_type, device='cuda') self._contrib_bias_correction = torch.tensor(bias_correction, dtype=torch.int, device='cuda') self._contrib_epsilon = torch.tensor(epsilon, dtype=math_type, device='cuda') self._contrib_weight_decay = torch.tensor(decay, dtype=math_type, device='cuda') self._packed_flat_to_model_params_fp16 = list(zip(*self._packed_flat_to_model_params_fp16)) if len(self._packed_flat_to_model_params_fp16) > 0 else None self._packed_flat_to_model_params_fp32 = list(zip(*self._packed_flat_to_model_params_fp32)) if len(self._packed_flat_to_model_params_fp32) > 0 else None self._lazy_init_stage2_done = True self.complete_reductions() self._first_step = False def set_is_accumulation_step(self, is_accumulation_step): self._is_accumulation_step = is_accumulation_step def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): if self._clip_after_ar: self._flatten_grad_mt(1.0/self._world_size) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Compute L2 grad norm if block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) self._L2_grad_norm = l2_grad_norm_sq.sqrt() else: # Copy model grads to flat grads buffer self._flatten_grad_mt(1.0) # Compute L2 grad norm self._l2_grad_norm_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float16, p=2).float() torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) # Apply clipping & pre-reduction scaling on grads loss_scale = self.global_scale max_grad_norm = loss_scale*self.defaults['max_grad_norm'] coeff = max_grad_norm /(1e-6+self.L2_grad_norm) coeff = (coeff>1) * self._one + (coeff<=1) * coeff tmp = torch.cat(((self._one), (coeff))) index = (coeff+1>coeff).int() scale = tmp.index_select(0, index).half()/self._world_size self._flat_grads.mul_(scale) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) rs_stream.wait_stream(self._l2_grad_norm_st) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works if block_id == 0: for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() def __compute_contrib_param_norm(self): if self._contrib_model_param_for_norm_fp16 is not None and self._contrib_model_param_for_norm_fp32 is not None: gnorm_fp16 = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp16], True)[1] gnorm_fp32 = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp32], True)[1] gnorm = torch.empty(size=[self._contrib_model_param_for_norm_num], dtype=torch.bool, device='cuda') gnorm.masked_scatter_(self._contrib_model_param_for_norm_is_fp16, gnorm_fp16) gnorm.masked_scatter_(self._contrib_model_param_for_norm_is_fp32, gnorm_fp32) elif self._contrib_model_param_for_norm_fp16 is not None: gnorm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp16], True)[1] elif self._contrib_model_param_for_norm_fp32 is not None: gnorm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp32], True)[1] return gnorm def __compute_contrib_update_norm(self): l2_norm = torch.zeros(size=[self._model_params_num], dtype=torch.float32, device='cuda') local_contrib_l2_norm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_update_frag_for_norm], True)[1] ** 2 l2_norm.scatter_(dim=0, index=self._offsets, src=local_contrib_l2_norm) torch.distributed.all_reduce(l2_norm, group=self._ag_pg[0]) l2_norm = torch.sqrt(l2_norm) return l2_norm def _pipeline_step(self): global_scale = self.global_scale # if clip before ar, set max_grad_norm to 0 max_grad_norm = self.defaults['max_grad_norm'] * self._clip_after_ar self._completion_st.wait_stream(self._l2_grad_norm_st) global_grad_norm = self.L2_grad_norm # check global_grad_norm and fill overflow_buf is_finite = (global_grad_norm + 1 > global_grad_norm).int() self._overflow_buf = self._one * (is_finite ^ self._one) # toggle between 0 and 1 torch.distributed.all_reduce(is_finite, op=torch.distributed.ReduceOp.MIN, group=self._current_process_group) torch.distributed.all_reduce(self._overflow_buf, op=torch.distributed.ReduceOp.MAX, group=self._current_process_group) # increment step counter if no overflow self._step += is_finite self._completion_st.wait_stream(torch.cuda.current_stream()) self._completion_st.wait_stream(self._l2_grad_norm_st) # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() param_norm = self.__compute_contrib_param_norm() multi_tensor_applier(self.multi_tensor_lamb_compute_update_term, self._overflow_buf, self._contrib_compute_update_term_tensor_list, # g, p, m, v, u self._contrib_beta1, self._contrib_beta2, self._contrib_beta3, self._contrib_bias_correction, self._step, self._contrib_epsilon, self._adam_w_mode, self._contrib_weight_decay, global_scale, global_grad_norm, max_grad_norm) upd_norm = self.__compute_contrib_update_norm() multi_tensor_applier(self.multi_tensor_lamb_update_weights, self._overflow_buf, self._contrib_update_weights_tensor_list, # u, p, p_copy param_norm, upd_norm, self._offsets, self._lr, self._contrib_weight_decay, global_grad_norm, self._use_nvlamb) torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if len(self._grads_fp16) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads_fp16)), scale) self._grads_fp16 = [] if len(self._grads_fp32) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads_fp32)), scale) self._grads_fp32 = [] def _do_overlapped_reduction(self, param_i, param): if not self._is_accumulation_step: # handle overlapped reductions if param.dtype == torch.float16: self._grads_fp16.append( (param.grad, self._individual_flat_grads[param_i]) ) else: self._grads_fp32.append( (param.grad, self._individual_flat_grads[param_i]) ) self._grads_generated[param_i]=True if not self._first_step and not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def L2_grad_norm(self): torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._first_step or self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None, grad_scaler=None): loss = None if closure is not None: loss = closure() self._pipeline_step() if grad_scaler is not None: found_inf = self._overflow_buf.float() optimizer_state = grad_scaler._per_optimizer_states[id(self)] current_device = torch.device('cuda', torch.cuda.current_device()) optimizer_state["found_inf_per_device"][current_device] = found_inf self._completion_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._completion_st): # Copy self._new_params to model params with torch.no_grad(): if self._packed_flat_to_model_params_fp16 is not None: multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params_fp16) if self._packed_flat_to_model_params_fp32 is not None: multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params_fp32) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss def state_dict(self): """ Returns a dict containing the current state of this :class:`DistributedFusedAdam` instance. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ # save step, master weights and first/second moments state_dict = {} state_dict['step'] = self._step state_dict['fp32_p'] = self._fp32_p state_dict['fp32_m'] = self._fp32_m state_dict['fp32_v'] = self._fp32_v return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If an DistributedFusedAdam instance was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``optimizer.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # restore step, master weights and first/second moments self._step = state_dict['step'] self._fp32_p = state_dict['fp32_p'].to(device="cuda") self._fp32_m = state_dict['fp32_m'].to(device="cuda") self._fp32_v = state_dict['fp32_v'].to(device="cuda") self._resume_from_checkpoint = True ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/fp16_optimizer.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FP16_Optimizer(object): """ :class:`FP16_Optimizer` A cutdown version of apex.fp16_utils.FP16_Optimizer. Designed only to wrap apex.contrib.optimizers.FusedAdam, FusedSGD. Refer to apex.fp16_utils documents for more information. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = apex.contrib.optimizers.FusedSGD(model.parameters()) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... # loss.backward() becomes: optimizer.backward(loss) ... Example with dynamic loss scaling:: ... optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True) # optional arg to control dynamic loss scaling behavior # dynamic_loss_args={'scale_window' : 500}) # Usually, dynamic_loss_args is not necessary. """ def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=True): print("\nThis fp16_optimizer is designed to only work with apex.contrib.optimizers.*") print("To update, use updated optimizers with AMP.") # The fused optimizer does all the work. We need this layer for two reason: # 1. maintain same user API from apex.fp16_utils # 2. keep common stuff here in case we need to add new fused optimizer later if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.optimizer = init_optimizer self.fp16_groups = [] # model params self.fp32_groups = [] # master weights # iterate over param_groups for param_group in self.optimizer.param_groups: fp16_group = [] fp32_group = [] for p in param_group['params']: fp16_group.append(p) fp32_group.append(p.clone().float().detach()) self.fp16_groups.append(fp16_group) self.fp32_groups.append(fp32_group) param_group['params'] = fp32_group if multi_tensor_applier.available: import amp_C self.overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm else: raise RuntimeError('FP16_Optimizer requires cuda extensions') # we may have a way of fusing dynamic scale. Do not support for now if dynamic_loss_scale: if dynamic_loss_args is not None: raise SystemError("Do not support dynamic loss scale args for now.") self.dynamic_loss_scale = True self.cur_scale = 2**16 self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = 2 self.scale_window = 1000 else: self.dynamic_loss_scale = False self.cur_iter = 0 self.cur_scale = static_loss_scale self.verbose = verbose def zero_grad(self, set_grads_to_None=True): """ Zero FP16 parameter grads. """ # FP32 grad should never exist. # For speed, set model fp16 grad to None by default for group in self.fp16_groups: for p in group: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() def step(self, closure=None): """ Not supporting closure. """ fp16_grads = [] norm_groups = [] skip = False for group in self.fp16_groups: fp16_grad = [] for i, p in enumerate(group): fp16_grad.append(p.grad) fp16_grads.append(fp16_grad) # nan check self.overflow_buf.zero_() for fp16_grad in fp16_grads: if len(fp16_grad) > 0: norm, norm_per_tensor = multi_tensor_applier(self.multi_tensor_l2norm, self.overflow_buf, [fp16_grad], True) norm_groups.append(norm) if self.overflow_buf.item() != 0: skip = True if skip: self._update_scale(skip) return # norm is in fact norm*cur_scale self.optimizer.step(grads=fp16_grads, output_params=self.fp16_groups, scale=self.cur_scale, grad_norms=norm_groups) self._update_scale(False) return def backward(self, loss): """ :attr:`backward` performs the following steps: 1. fp32_loss = loss.float() 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's fp16 leaves """ scaled_loss = (loss.float()) * self.cur_scale scaled_loss.backward() def _update_scale(self, skip): if self.dynamic_loss_scale: if skip: if self.verbose: print("\nGrad overflow on iteration", self.cur_iter) print("Using dynamic loss scale of", self.cur_scale) self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor else: if skip: print("\nGrad overflow on iteration", self.cur_iter) print("Using static loss scale of", self.cur_scale) self.cur_iter +=1 return # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups) def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict['cur_iter'] = self.cur_iter if state_dict['dynamic_loss_scale']: state_dict['last_overflow_iter'] = self.last_overflow_iter state_dict['scale_factor'] = self.scale_factor state_dict['scale_window'] = self.scale_window state_dict['optimizer_state_dict'] = self.optimizer.state_dict() state_dict['fp32_groups'] = self.fp32_groups return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.cur_scale = state_dict['cur_scale'] self.cur_iter = state_dict['cur_iter'] if state_dict['dynamic_loss_scale']: self.last_overflow_iter = state_dict['last_overflow_iter'] self.scale_factor = state_dict['scale_factor'] self.scale_window = state_dict['scale_window'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) # At this point, the optimizer's references to the model's fp32 parameters are up to date. # The optimizer's hyperparameters and internal buffers are also up to date. # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still # out of date. There are two options. # 1: Refresh the master params from the model's fp16 params. # This requires less storage but incurs precision loss. # 2: Save and restore the fp32 master copies separately. # We choose option 2. # # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device # of their associated parameters, because it's possible those buffers might not exist yet in # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been # constructed in the same way as the one whose state_dict we are loading, the same master params # are guaranteed to exist, so we can just copy_() from the saved master params. for current, saved in zip(self.fp32_groups, state_dict['fp32_groups']): for _current, _saved in zip(current, saved): _current.data.copy_(_saved.data) ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/fused_adam.py ================================================ import types import torch import importlib from apex.multi_tensor_apply import multi_tensor_applier class FusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) .. _Adam - A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._use_multi_tensor = False if use_mt: if not multi_tensor_applier.available: print("Warning: multi_tensor_applier is unavailable") else: self._use_multi_tensor = True self._overflow_buf = torch.cuda.IntTensor([0]) self._amp_scale_adjustment = amp_scale_adjustment if amsgrad: raise RuntimeError('FusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(FusedAdam, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 def step(self, closure=None, grads=None, output_params=None, scale=1., grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use for the optimizer update. If gradients have type torch.half, parameters are expected to be in type torch.float. (default: None) output params (list of tensors, optional): A reduced precision copy of the updated weights written out in addition to the regular updated weights. Have to be of same type as gradients. (default: None) scale (float, optional): factor to divide gradient tensor values by before applying to weights. (default: 1) """ loss = None if closure is not None: loss = closure() if hasattr(self, "_amp_stash"): grads = self._amp_stash.grads output_params = self._amp_stash.output_params scale = self._amp_stash.scale*self._amp_scale_adjustment grad_norms = self._amp_stash.grad_norms if grads is None: grads_group = [None]*len(self.param_groups) # backward compatibility # assuming a list/generator of parameter means single group elif isinstance(grads, types.GeneratorType): grads_group = [grads] elif type(grads[0])!=list: grads_group = [grads] else: grads_group = grads if output_params is None: output_params_group = [None]*len(self.param_groups) elif isinstance(output_params, types.GeneratorType): output_params_group = [output_params] elif type(output_params[0])!=list: output_params_group = [output_params] else: output_params_group = output_params if grad_norms is None: grad_norms = [None]*len(self.param_groups) for group, grads_this_group, output_params_this_group, grad_norm in zip(self.param_groups, grads_group, output_params_group, grad_norms): if grads_this_group is None: grads_this_group = [None]*len(group['params']) if output_params_this_group is None: output_params_this_group = [None]*len(group['params']) # compute combined scale factor for this group combined_scale = scale if group['max_grad_norm'] > 0: # norm is in fact norm*scale clip = ((grad_norm / scale) + 1e-6) / group['max_grad_norm'] if clip > 1: combined_scale = clip * scale bias_correction = 1 if group['bias_correction'] else 0 if self._use_multi_tensor: if output_params: tensorlists = [[],[],[],[],[]] else: tensorlists = [[],[],[],[]] tensordevice = None for p, grad, output_param in zip(group['params'], grads_this_group, output_params_this_group): #note: p.grad should not ever be set for correct operation of mixed precision optimizer that sometimes sends None gradients if p.grad is None and grad is None: continue if grad is None: grad = p.grad.data if grad.is_sparse: raise RuntimeError('FusedAdam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] beta1, beta2 = group['betas'] state['step'] += 1 out_p = torch.tensor([], dtype = torch.float) if output_param is None else output_param if self._use_multi_tensor: pl = [p.data, exp_avg, exp_avg_sq, grad] if output_param is not None: pl.append(out_p) for tl, t in zip(tensorlists, pl): tl.append(t) if tensordevice is None: tensordevice = p.device elif tensordevice != p.device: raise RuntimeError('FusedAdam does not support use_mt with tensors on multiple device') else: with torch.cuda.device(p.device): fused_adam_cuda.adam(p.data, out_p, exp_avg, exp_avg_sq, grad, group['lr'], beta1, beta2, group['eps'], combined_scale, state['step'], self.eps_mode, bias_correction, group['weight_decay']) if self._use_multi_tensor: with torch.cuda.device(tensordevice): multi_tensor_applier( fused_adam_cuda.adam_mt, self._overflow_buf, tensorlists, group['lr'], beta1, beta2, group['eps'], combined_scale, state['step'], self.eps_mode, bias_correction, group['weight_decay']) return loss ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/fused_lamb.py ================================================ import torch import importlib import math from apex.multi_tensor_apply import multi_tensor_applier class FusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" --global-option="--deprecated_fused_lamb" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.contrib.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.contrib.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01, amsgrad=False, adam_w_mode=True, grad_averaging=True, set_grad_none=True, max_grad_norm=1.0): if amsgrad: raise RuntimeError('FusedLAMB does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(FusedLAMB, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm self._dummy_overflow_buf = torch.cuda.IntTensor([0]) fused_lamb_cuda = importlib.import_module("fused_lamb_cuda") self.multi_tensor_lamb = fused_lamb_cuda.lamb else: raise RuntimeError('apex.contrib.optimizers.FusedLAMB requires cuda extensions') self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedLAMB, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() # create separate grad lists for fp32 and fp16 params g_all_32, g_all_16 = [], [] for group in self.param_groups: for p in group['params']: if p.grad is None: continue if p.dtype == torch.float32: g_all_32.append(p.grad.data) elif p.dytpe == torch.float16: g_all_16.append(p.grad.data) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') g_norm_32, g_norm_16 = 0.0, 0.0 # compute grad norm for two lists if len(g_all_32) > 0: g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_32], False)[0].item() if len(g_all_16) > 0: g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_16], False)[0].item() # blend two grad norms to get global grad norm global_grad_norm = math.sqrt(g_norm_32 * g_norm_32 + g_norm_16 * g_norm_16) max_grad_norm = self.defaults['max_grad_norm'] for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedLAMB does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm) return loss ================================================ FILE: KoSentenceT5/apex/contrib/optimizers/fused_sgd.py ================================================ import types import torch from torch.optim.optimizer import Optimizer, required from apex.multi_tensor_apply import multi_tensor_applier class FusedSGD(Optimizer): r"""Implements stochastic gradient descent (optionally with momentum). This version of fused SGD implements 2 fusions. * Fusion of the SGD update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.contrib.optimizers.FusedSGD` should be used without AMP. :class:`apex.contrib.optimizers.FusedSGD` only works in the case where all parameters require grad. Nesterov momentum is based on the formula from `On the importance of initialization and momentum in deep learning`__. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float): learning rate momentum (float, optional): momentum factor (default: 0) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) dampening (float, optional): dampening for momentum (default: 0) nesterov (bool, optional): enables Nesterov momentum (default: False) Example: model = ... model.half() optimizer = apex.contrib.optimizers.FusedSGD(model.parameters()) # wrap with FP16_Optimizer optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True) optimizer.zero_grad() ... optimizer.backward(loss) optmizer.step() __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf .. note:: The implementation of SGD with Momentum/Nesterov subtly differs from Sutskever et. al. and implementations in some other frameworks. Considering the specific case of Momentum, the update can be written as .. math:: v = \rho * v + g \\ p = p - lr * v where p, g, v and :math:`\rho` denote the parameters, gradient, velocity, and momentum respectively. This is in contrast to Sutskever et. al. and other frameworks which employ an update of the form .. math:: v = \rho * v + lr * g \\ p = p - v The Nesterov version is analogously modified. """ def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, wd_after_momentum=False, materialize_master_grads=True): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super(FusedSGD, self).__init__(params, defaults) self.wd_after_momentum = wd_after_momentum if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_sgd = amp_C.multi_tensor_sgd else: raise RuntimeError('apex.contrib.optimizers.FusedSGD requires cuda extensions') def __setstate__(self, state): super(FusedSGD, self).__setstate__(state) for group in self.param_groups: group.setdefault('nesterov', False) def get_momentums(self, params): momentums = [] first_run = True for p in params: param_state = self.state[p] # torch.optim.SGD initializes momentum in the main loop, we have # to do it here, and track whether or not we've done so, so that # momentum application can be skipped in the main kernel. if 'momentum_buffer' not in param_state: first_run = True buf = param_state['momentum_buffer'] = torch.zeros_like(p.data) momentums.append(buf) else: first_run = False momentums.append(param_state['momentum_buffer']) return momentums, first_run def step(self, closure=None, grads=None, output_params=None, scale=1., grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use for the optimizer update. If gradients have type torch.half, parameters are expected to be in type torch.float. (default: None) output_params (list of tensors, optional): A reduced precision copy of the updated weights written out in addition to the regular updated weights. Have to be of same type as gradients. (default: None) scale (float, optional): factor to divide gradient tensor values by before applying to weights. (default: 1) """ if hasattr(self, "_amp_stash"): raise RuntimeError('apex.contrib.optimizers.FusedSGD should not be used with AMP.') loss = None if closure is not None: loss = closure() if grads is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD must be wrapped \ with apex.contrib.optimizers.FP16_Optimizer \ which provides grads.') # backward compatibility # assuming a list/generator of parameter means single group elif isinstance(grads, types.GeneratorType): grads_group = [grads] elif type(grads[0])!=list: grads_group = [grads] else: grads_group = grads if output_params is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD must be wrapped \ with apex.contrib.optimizers.FP16_Optimizer \ which provides output_params.') elif isinstance(output_params, types.GeneratorType): output_params_group = [output_params] elif type(output_params[0])!=list: output_params_group = [output_params] else: output_params_group = output_params for group, grads_this_group, output_params_this_group in zip(self.param_groups, grads_group, output_params_group): if grads_this_group is None or output_params_this_group is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD only works \ when all parameters require grad.') weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] lr = group['lr'] first_runs = [True, True] # output_params_this_group: original weights (either fp16 or fp32) # group['params']: master weights (fp32) # grad_type, param_to_update_type, momentum_type, requires_fp16_model_copy # fp32, fp32, fp32, No fp32_grads = [g for (p, g) in zip(output_params_this_group, grads_this_group) if p.dtype == torch.float32] fp32_params = [p2 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float32] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) fp32_set = [fp32_grads, fp32_params, fp32_momentums] # fp16, fp32, fp32, Yes fp16_grads = [g for (p, g) in zip(output_params_this_group, grads_this_group) if p.dtype == torch.float16] fp32_from_fp16_params = [p2 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float16] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_params = [p1 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float16] fp16_set = [fp16_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_params] launch_sets = [fp16_set, fp32_set] for launch_set, first_run in zip(launch_sets, first_runs): assert len(launch_set[0]) == len(launch_set[1]) assert len(launch_set[0]) == len(launch_set[2]) if len(launch_set[0]) > 0: multi_tensor_applier( self.multi_tensor_sgd, self._dummy_overflow_buf, launch_set, weight_decay, momentum, dampening, lr, nesterov, first_run, self.wd_after_momentum, 1.0/scale) return loss ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/README.md ================================================ # Introduction to ASP This serves as a quick-start for ASP (Automatic SParsity), a tool that enables sparse training and inference for PyTorch models by adding 2 lines of Python. ## Importing ASP ``` from apex.contrib.sparsity import ASP ``` ## Initializing ASP Apart from the import statement, it is sufficient to add just the following line of code before the training phase to augment the model and the optimizer for sparse training/inference: ``` ASP.prune_trained_model(model, optimizer) ``` In the context of a typical PyTorch training loop, it might look like this: ``` ASP.prune_trained_model(model, optimizer) x, y = DataLoader(args) for epoch in range(epochs): y_pred = model(x) loss = loss_function(y_pred, y) loss.backward() optimizer.step() torch.save(...) ``` The `prune_trained_model` step calculates the sparse mask and applies it to the weights. This is done once, i.e., sparse locations in the weights matrix remain fixed after this step. ## Generate a Sparse Network The following approach serves as a guiding example on how to generate a pruned model that can use Sparse Tensor Cores in the NVIDIA Ampere Architecture. This approach generates a model for deployment, i.e. inference mode. ``` (1) Given a fully trained (dense) network, prune parameter values in a 2:4 sparse pattern. (2) Fine-tune the pruned model with optimization method and hyper-parameters (learning-rate, schedule, number of epochs, etc.) exactly as those used to obtain the trained model. (3) (If required) Quantize the model. ``` In code, below is a sketch on how to use ASP for this approach (steps 1 and 2 above). ``` model = define_model(..., pretrained=True) # define model architecture and load parameter tensors with trained values (by reading a trained checkpoint) criterion = ... # compare ground truth with model predition; use the same criterion as used to generate the dense trained model optimizer = ... # optimize model parameters; use the same optimizer as used to generate the dense trained model lr_scheduler = ... # learning rate scheduler; use the same schedule as used to generate the dense trained model from apex.contrib.sparsity import ASP ASP.prune_trained_model(model, optimizer) #pruned a trained model x, y = DataLoader(args) for epoch in range(epochs): # train the pruned model for the same number of epochs as used to generate the dense trained model y_pred = model(x) loss = criterion(y_pred, y) lr_scheduler.step() loss.backward() optimizer.step() torch.save(...) # saves the pruned checkpoint with sparsity masks ``` ## Non-Standard Usage If your goal is to easily perpare a network for accelerated inference, please follow the recipe above. However, ASP can also be used to perform experiments in advanced techniques like training with sparsity from initialization. For example, in order to recompute the sparse mask in between training steps, use the following method: ``` ASP.compute_sparse_masks() ``` A more thorough example can be found in `./test/toy_problem.py`. ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/__init__.py ================================================ from .sparse_masklib import create_mask from .asp import ASP ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/asp.py ================================================ import types import torch from .sparse_masklib import create_mask torchvision_imported=True try: import torchvision except ImportError: print("[ASP][Warning] torchvision cannot be imported.") torchvision_imported=False def eligible_modules(model, whitelist_layer_types, allowed_layer_names, disallowed_layer_names): eligible_modules_list = [] for name, mod in model.named_modules(): if isinstance(mod, whitelist_layer_types) and name not in disallowed_layer_names: if allowed_layer_names is not None and name not in allowed_layer_names: continue eligible_modules_list.append((name, mod)) return eligible_modules_list class ASP: __model = None __verbosity = 0 __optimizer = None __sparse_parameters = [] __calculate_mask = None @classmethod def init_model_for_pruning(cls, model, mask_calculator="m4n2_1d", verbosity=3, whitelist=[torch.nn.Linear, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d], allowed_layer_names=None, disallowed_layer_names=[], allow_recompute_mask=False, custom_layer_dict={}): """Call this method to modify your model to take advantage of sparse matrix multiplication. Note that this call alone only augments the model with additional buffers needed for sparse MMA, it does not enable use of sparse MMA. If you are starting with a fresh model: model = ... ASP.init_model_for_pruning(model, mask_calculator, ...) if (training) ASP.init_optimizer_for_pruning(optimizer) ASP.compute_sparse_masks() // sparsity is off by default, call when youy want to enable it. If you are starting from a checkpoint: model = ... ASP.init_model_for_pruning(model, mask_calculator, ...) torch.load(...) if (training) ASP.init_optimizer_for_pruning(optimizer) Arguments: model The model mask_calculator Either callable that computes mask given a tensor OR pattern string for sparse mask lib. verbosity Integer controling verbosity level. 0 -> Only errors. 1 -> Errors and warnings. 2 -> Errors, warnings and info. 3 -> Errors, warnings, info and debug. whitelist Module types approved for sparsity. allowed_layer_names If not None, only layer names that appear in this list are considered for sparsity. disallowed_layer_names If not [], only layer names that do not appear in this list are considered for sparsity. allow_recompute_mask If True, stores pruned values so that dense weights can be restored. Pruned weights are stored in CPU memory, hence this option does not increase GPU memory usage. custom_layer_dict Dictionary of additional layer paremeters to sparsify. e.g. {CustomLinear: ['weight']} [Future] Support for allow_recompute_mask can be removed, it is not part of sparse inference recipe -- AKM. """ assert (cls.__model is None), "ASP has been initialized already." cls.__model = model cls.__verbosity = verbosity if isinstance(mask_calculator, str): def create_mask_from_pattern(param): return create_mask(param, mask_calculator).bool() cls.__calculate_mask = create_mask_from_pattern else: cls.__calculate_mask = mask_calculator #user defined function # function to extract variables that will be sparsified. # idea is that you will add one of these functions for each module type that can be sparsified. if torchvision_imported: print("[ASP] torchvision is imported, can work with the MaskRCNN/KeypointRCNN from torchvision.") sparse_parameter_list = {torch.nn.Linear: ['weight'], torch.nn.Conv1d: ['weight'], torch.nn.Conv2d: ['weight'], torch.nn.Conv3d: ['weight'], torchvision.ops.misc.Conv2d: ['weight']} else: sparse_parameter_list = {torch.nn.Linear: ['weight'], torch.nn.Conv1d: ['weight'], torch.nn.Conv2d: ['weight'], torch.nn.Conv3d: ['weight']} if custom_layer_dict: # Update default list to include user supplied custom (layer type : parameter tensor), make sure this tensor type is something ASP knows how to prune sparse_parameter_list.update(custom_layer_dict) whitelist += list(custom_layer_dict.keys()) for module_type in whitelist: assert (module_type in sparse_parameter_list), "Module %s :: Don't know how to sparsify module." % module.dtype() # find all sparse modules, extract sparse parameters and decorate def add_sparse_attributes(module_name, module): sparse_parameters = sparse_parameter_list[type(module)] for p_name, p in module.named_parameters(): if p_name in sparse_parameters and p.requires_grad: # check for NVIDIA's TC compatibility: we check along the horizontal direction if p.dtype == torch.float32 and ((p.size()[0] % 8) != 0 or (p.size()[1] % 16) != 0): #User defines FP32 and APEX internally uses FP16 math print("[ASP] Auto skipping pruning %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) continue if p.dtype == torch.float16 and ((p.size()[0] % 8) != 0 or (p.size()[1] % 16) != 0): #For Conv2d dim= K x CRS; we prune along C print("[ASP] Auto skipping pruning %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) continue if cls.__verbosity >= 3: print("[ASP] Sparsifying %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) mask = torch.ones_like(p).bool() buffname = p_name.split(".")[-1] # buffer names cannot contain "." module.register_buffer('__%s_mma_mask' % buffname, mask) if allow_recompute_mask: pruned = torch.zeros_like(p).cpu() module.register_buffer('__%s_mma_pruned_p' % buffname, pruned) else: pruned = None cls.__sparse_parameters.append((module_name, module, p_name, p, mask, pruned)) else: if cls.__verbosity >= 3: print("[ASP] Not sparsifying %s::%s of size=%s and type=%s" % (module_name, p_name, str(p.size()), str(p.dtype))) for name, sparse_module in eligible_modules(model, tuple(whitelist), allowed_layer_names, disallowed_layer_names): add_sparse_attributes(name, sparse_module) @classmethod def init_optimizer_for_pruning(cls, optimizer): """Call this method to monkey patch optimizer step function so that masks can be applied to gradients and weights during training. You must call init_model_for_pruning(...) before calling init_optimizer_for_pruning(...) """ assert (cls.__optimizer is None), "ASP has initialized optimizer already." assert (cls.__calculate_mask is not None), "Called ASP.init_optimizer_for_pruning before ASP.init_model_for_pruning." # store pointer to original optimizer step method cls.__optimizer = optimizer cls.__optimizer.__step = optimizer.step def __step(opt_self, *args, **kwargs): # prune gradients before step method with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if p.grad is not None: #thx pjudd p.grad.mul_(mask) # call original optimizer step method rval = opt_self.__step(*args, **kwargs) # prune parameters after step method with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: p.mul_(mask) return rval cls.__optimizer.step = types.MethodType(__step, cls.__optimizer) @classmethod def compute_sparse_masks(cls): """Call this method to enable sparsity. If init(...) was called with allow_recompute_mask=False AND sparsity is disabled, pruned field can be None. """ with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if mask.sum() < mask.numel(): # when recalculating masks # restore dense parameter if allow_recompute_mask is enabled assert (pruned is not None), "Unable to restore dense parameter because allow_recompute_mask == False" p.add_(pruned.cuda()) mask.set_(cls.__calculate_mask(p)) if pruned is not None: # stow away pruned weights to cpu pruned.set_((p * (~mask)).cpu()) p.mul_(mask) # in-place multiplication, so pruned weights are 0-values, hence checkpoint will have 0s for pruned weights if cls.__verbosity >= 2: print("[ASP] Enabled %.2f%% sparsity for %s::%s of size=%s and type=%s" % (100.0*mask.sum()/mask.numel(), module_name, p_name, str(p.size()), str(p.dtype))) @classmethod def restore_pruned_weights(cls): """Call this method to disable sparsity and restore all weights. This will only work if init(...) was called with allow_recompute=True. """ with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if mask.sum() < mask.numel(): assert (pruned is not None), "Unable to restore dense parameter because allow_recompute_mask == False" p.add_(pruned.cuda()) mask.fill_(1) pruned.zero_() if cls.__verbosity >= 2: print("[ASP] Disabled sparsity for %s::%s (dense weights restored)" % (module_name, p_name)) @classmethod def is_sparsity_enabled(cls): """Call this method to determine if sparsity is enabled in the model. The typical use case is right after checkpoint has been loaded. """ total,sp100,sp50 = 0,0,0 for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: total += 1 mask_sum = mask.sum() mask_numel = mask.numel() if mask_sum == mask_numel: sp100 += 1 elif mask_sum*2 == mask_numel: sp50 += 1 assert (total == sp100 or total == sp50), "Inconsistent model sparsity" if total == sp100: return False elif total == sp50: return True @classmethod def prune_trained_model(cls, model, optimizer): # add mask buffers to model (init_model_for_pruning), augment optimizer (init_optimizer_for_pruning) and compute masks (compute_sparse_masks) cls.init_model_for_pruning(model, mask_calculator="m4n2_1d", verbosity=2, whitelist=[torch.nn.Linear, torch.nn.Conv2d], allow_recompute_mask=False) cls.init_optimizer_for_pruning(optimizer) cls.compute_sparse_masks() ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/sparse_masklib.py ================================================ import sys import torch import numpy as np import collections from itertools import permutations """ compute density (helper fn to compute % NNZs in a tensor) """ def fill(x): return float(x.nonzero().size(0))/torch.numel(x) """ reshape matrix into m-dimensional vectors: (h,w) -> (hw/m, m) """ def reshape_1d(matrix, m): # If not a nice multiple of m, fill with zeroes. if matrix.shape[1] % m > 0: mat = torch.cuda.FloatTensor(matrix.shape[0], matrix.shape[1] + (m-matrix.shape[1]%m)).fill_(0) mat[:, :matrix.shape[1]] = matrix shape = mat.shape return mat.view(-1,m),shape else: return matrix.view(-1,m), matrix.shape """ return all possible m:n patterns in a 1d vector """ valid_m4n2_1d_patterns = None def compute_valid_1d_patterns(m,n): # Early exit if patterns was already created. global valid_m4n2_1d_patterns if m==4 and n==2 and valid_m4n2_1d_patterns is not None: return valid_m4n2_1d_patterns patterns = torch.zeros(m) patterns[:n] = 1 valid_patterns = torch.Tensor(list(set(permutations(patterns.tolist())))) if m == 4 and n == 2: valid_m4n2_1d_patterns = valid_patterns return valid_patterns """ m:n 1d structured best """ def mn_1d_best(matrix, m, n): # Find all possible patterns. patterns = compute_valid_1d_patterns(m,n).cuda() # Find the best m:n pattern (sum of non-masked weights). mask = torch.cuda.IntTensor(matrix.shape).fill_(1).view(-1,m) mat,shape = reshape_1d(matrix,m) pmax = torch.argmax(torch.matmul(mat.abs(),patterns.t()), dim=1) mask[:] = patterns[pmax[:]] mask = mask.view(matrix.shape) return mask def m4n2_1d(mat, density): return mn_1d_best(mat, 4, 2) """ Below 2d-masking related code is targeted more for training (from scratch). 2d-pruning of a weight tensor is done to accelerate DGRAD step during backprop phase of training algorithm. Acceleration comes from using SpMMA instructions in Tensor Cores of NVIDIA Ampere GPU Architecture (note: this code does not do the acceleration, GPU kernels are required for this). 1d pruning of weight tensor helps speed up FPROP step by pruning in 2:4 pattern along the horizontal (logical) direction. During DGRAD step, weight tensor is transposed. 2d pruning functions below, mask weight tensor such that their transposed versions are also 2:4 sparse along the horizontal (logical) direction. Thus, with 2d pruning, weight tensors are 2:4 sparse along row and column directions. """ """ m:n 2d structured pruning: greedy method to select mask """ def mn_2d_greedy(matrix, m, n): # Convert to numpy mat = matrix.cpu().detach().numpy() mask = np.ones(mat.shape, dtype=int) rowCount = int(mat.shape[0]/m) * m colCount = int(mat.shape[1]/m) * m for rowStartIdx in range(0, rowCount, m): rowEndIdx = rowStartIdx + m for colStartIdx in range(0, colCount, m): colEndIdx = colStartIdx + m matrixSub = np.absolute(np.squeeze(mat[rowStartIdx:rowEndIdx, colStartIdx:colEndIdx])) maskSub = np.squeeze(mask[rowStartIdx:rowEndIdx, colStartIdx:colEndIdx]) maskSub.fill(0.0) matrixVecView = matrixSub.reshape(-1) maskVecView = maskSub.reshape(-1) linearIdx = np.argsort(matrixVecView) matrixIdx = [(int(x/m), x % m) for x in linearIdx] rowCounter = collections.Counter() colCounter = collections.Counter() for currIdx in range(len(linearIdx) - 1, -1, -1): currMatrixEntry = matrixIdx[currIdx] if (rowCounter[currMatrixEntry[0]] == n) or (colCounter[currMatrixEntry[1]] == n): continue #end if maskSub[currMatrixEntry[0], currMatrixEntry[1]] = 1.0 rowCounter[currMatrixEntry[0]] += 1 colCounter[currMatrixEntry[1]] += 1 return torch.tensor(mask.cuda()) def m4n2_2d_greedy(mat, density): return mn_2d_greedy(mat, 4, 2) """ return all possible m:n patterns in a mxn block. """ valid_m4n2_2d_patterns = None def compute_valid_2d_patterns(m,n): # Early exit if patterns was already created. global valid_m4n2_2d_patterns if valid_m4n2_2d_patterns is not None: return valid_m4n2_2d_patterns patterns = torch.zeros(m) patterns[:n] = 1 patterns = list(set(permutations(patterns.tolist()))) patterns = patterns + patterns patterns = torch.Tensor(list(set(permutations(patterns,m)))) valid = ((patterns.sum(dim=1) <= n).sum(dim=1) == m).nonzero().view(-1) valid_patterns = torch.Tensor(valid.shape[0],m,m) valid_patterns[:] = patterns[valid[:]] if m == 4 and n == 2: valid_m4n2_2d_patterns = valid_patterns return valid_patterns """ m:n 2d structured pruning: exhaustive method to select best mask """ def mn_2d_best(matrix, m, n): # Find all possible patterns. patterns = compute_valid_2d_patterns(m,n).cuda() # Find the best m:n pattern (sum of non-masked weights). mask = torch.cuda.IntTensor(matrix.shape).fill_(1) mat = reshape_2d(matrix,m,m).abs() pmax = torch.argmax(torch.matmul(mat,patterns.view(patterns.shape[0],m*m).t()), dim=2) # Copy best m:n patterns into mask. mat = mat.view(mat.shape[0]*mat.shape[1],-1) pmax = pmax.view(pmax.shape[0]*pmax.shape[1]).unsqueeze(1).expand(-1,mat.shape[1]) patterns = patterns.view(patterns.shape[0],patterns.shape[1]*patterns.shape[2]) mat = torch.gather(patterns,0,pmax) mat = reshape_2d_inv(mat.view(matrix.shape[0]//m,matrix.shape[1]//m,m,m)) mask.copy_(mat.type(mask.type())) return mask def m4n2_2d_best(mat, density): return mn_2d_best(mat, 4, 2) """ returns a sparse mask """ def create_mask(tensor, pattern="m4n2_1d", density=0.5): # Reshape tensor and mask. shape = tensor.shape ttype = tensor.type() t = tensor.float().contiguous() # 1d-tensor if len(shape) == 1: t = t.view(1, shape[0]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 2d-tensor (in, out) elif len(shape) == 2: t = t.view(shape[0], shape[1]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 3d-tensor (batch, in, out) elif len(shape) == 3: t = t.view(shape[0]*shape[1], shape[2]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 4d-tensor (in, out, h, w) elif len(shape) == 4: """ # transformers (bmm) t = t.view(shape[0]*shape[1]*shape[2], shape[3]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) """ # convs t = t.permute(2,3,0,1).contiguous().view(shape[2]*shape[3]*shape[0], shape[1]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) mask = mask.view(shape[2], shape[3], shape[0], shape[1]).permute(2,3,0,1).contiguous() return mask.view(shape).type(ttype) ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/test/checkpointing_test_part1.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): # # PART1 # torch.manual_seed(args.seed) model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, verbosity=args.verbosity, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.enable_sparsity() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) torch.save({ 'step': step, 'verbosity': args.verbosity, 'seed2': args.seed2, 'pattern': args.pattern, 'whitelist': args.whitelist, 'allow_recompute_mask': args.allow_recompute_mask, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), }, args.checkpoint_path) if __name__ == '__main__': class Args: verbosity=3 seed = 4873 seed2 = 99875 pattern = "m4n2_2d_best" whitelist = [torch.nn.Linear] allow_recompute_mask = True batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(args) ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/test/checkpointing_test_part2.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(step, args, model_state_dict, optimizer_state_dict): # # PART2 # model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, verbosity=args.verbosity, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) torch.manual_seed(args.seed2) model.load_state_dict(model_state_dict) optimizer.load_state_dict(optimizer_state_dict) print("Model sparsity is %s" % ("enabled" if ASP.sparsity_is_enabled() else "disabled")) # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) if __name__ == '__main__': checkpoint = torch.load("part1.chkp") class Args: verbosity = checkpoint['verbosity'] seed = 4873 seed2 = checkpoint['seed2'] pattern = checkpoint['pattern'] whitelist = checkpoint['whitelist'] allow_recompute_mask = checkpoint['allow_recompute_mask'] batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(checkpoint['step'], args, checkpoint['model_state_dict'], checkpoint['optimizer_state_dict']) ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/test/checkpointing_test_reference.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP # # Reference run for checkpointing test (part1 + part2) # def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): # # PART1 # torch.manual_seed(args.seed) model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.enable_sparsity() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) # # PART 2 # torch.manual_seed(args.seed2) # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) if __name__ == '__main__': class Args: seed = 4873 seed2 = 99875 pattern = "m4n2_2d_best" whitelist = [torch.nn.Linear] allow_recompute_mask = True batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(args) ================================================ FILE: KoSentenceT5/apex/contrib/sparsity/test/toy_problem.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) # only prune linear layers, even though we also support conv1d, conv2d and conv3d ASP.init_model_for_pruning(model, "m4n2_1d", whitelist=[torch.nn.Linear], allow_recompute_mask=True) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.compute_sparse_masks() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) # recompute sparse masks ASP.compute_sparse_masks() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) # turn off sparsity print("SPARSE :: ",one_ll) ASP.restore_pruned_weights() # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps_2) if __name__ == '__main__': class Args: batch_size = 32 input_features = 16 output_features = 8 hidden_features = 40 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 num_dense_steps_2 = 1500 args = Args() main(args) ================================================ FILE: KoSentenceT5/apex/contrib/test/fmha/test_fmha.py ================================================ ############################################################################### # Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################### import sys import torch import numpy as np import unittest import math import fmhalib as mha def py_mha(qkv, amask, b, s, h, d): qkv = qkv.view(b, s, h, 3, d) q = qkv[:, :, :, 0, :].permute(0,2,1,3) k = qkv[:, :, :, 1, :].permute(0,2,1,3) v = qkv[:, :, :, 2, :].permute(0,2,1,3) p = torch.matmul(q.float(), k.permute(0,1,3,2).float()) p_masked = p / math.sqrt(d) + (1.0 - amask) * -10000.0 s = torch.softmax(p_masked, -1).to(qkv.dtype) ctx = torch.matmul(s, v) ctx = ctx.permute(0,2,1,3).contiguous() ctx.retain_grad() return ctx class TestFMHA(unittest.TestCase): def run_test(self, s, b): print(f'Test s={s} b={b}') torch.manual_seed(1234) torch.cuda.manual_seed(1234) dtype = torch.float16 device = torch.device('cuda') h = 16 d = 64 slens = [s] * b a = torch.tensor(np.array([0] + slens), dtype=torch.int32) amask = torch.ones(b,h,s,s, dtype=dtype, device=device) seqlens = torch.tensor(slens, dtype=torch.int32, device=device) cu_seqlens = torch.cumsum(a, 0).to(dtype=torch.int32, device=device) total = cu_seqlens[-1].item() qkv = torch.randn((b,s,h,3,d), device=device, dtype=dtype) qkv_vs = qkv.permute(0,1,3,2,4).contiguous().view(b*s, 3, h,d) qkv.requires_grad = True if b < 4: ctx, S_ = mha.fwd_nl(qkv_vs, cu_seqlens, 0.0, s, True, None) else: ctx, S_ = mha.fwd(qkv_vs, cu_seqlens, 0.0, s, True, None) ctx = ctx.view(b,s,h,d) ctx_ref = py_mha(qkv, amask, b,s,h,d) self.assertTrue(torch.allclose(ctx_ref.float(), ctx.float(), atol=1e-3)) labels = torch.randn_like(ctx_ref) diff = ctx_ref - labels l = (diff * diff).sum() / b l.backward() dw = ctx_ref.grad.permute(0,2,1,3) dw2 = dw.permute(0,2,1,3).clone().detach().contiguous() if b < 4: dqkv2, _, _ = mha.bwd_nl(dw2, qkv_vs, S_, cu_seqlens, 0.0, s) else: dqkv2, _ = mha.bwd(dw2, qkv_vs, S_, cu_seqlens, 0.0, s) dqkv2 = dqkv2.permute(0,2,1,3).view(b,s, h,3,d) self.assertTrue(torch.allclose(qkv.grad.float(), dqkv2.float(), atol=1e-3)) def test_128(self): self.run_test(128, 32) def test_256(self): self.run_test(256, 32) def test_384(self): self.run_test(384, 32) def test_512(self): self.run_test(512, 32) self.run_test(512, 2) self.run_test(512, 3) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/layer_norm/test_fast_layer_norm.py ================================================ import torch import unittest import numpy as np import torch.nn.functional as F from apex.contrib.layer_norm import FastLayerNorm import fast_layer_norm as fln class GPUTimer: def __init__(self, stream): self.start_ = torch.cuda.Event(enable_timing=True) self.stop_ = torch.cuda.Event(enable_timing=True) self.stream_ = stream def start(self): self.stream_.record_event(self.start_) def stop(self): self.stream_.record_event(self.stop_) def sync(self): self.stream_.synchronize() def millis(self): return self.start_.elapsed_time(self.stop_) def size_in_bytes(t): return torch.numel(t) * t.element_size() def abs_err(x, y): xf = x.float() yf = y.float() return ((xf-yf).abs().sum() / yf.abs().sum()).item() class TestFastLayerNorm(unittest.TestCase): def setUp(self, seed=1234): seed = 1234 torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def test_ln_fp32(self): self.run_test_layer_norm(torch.float32, atol=1e-5) def test_ln_fp16(self): self.run_test_layer_norm(torch.float16, atol=1e-2, rtol=1e-3) def run_test_layer_norm(self, dtype, atol, rtol=1e-5): device = torch.device('cuda') s = 512 b = 32 hidden_size = 1024 epsilon = 1e-5 x = torch.randn((s,b,hidden_size), dtype=dtype, device=device) beta = torch.randn(hidden_size, dtype=dtype, device=device) gamma = torch.randn(hidden_size, dtype=dtype, device=device) x.requires_grad = True beta.requires_grad = True gamma.requires_grad = True x2 = x.clone().detach() beta2 = beta.clone().detach() gamma2 = gamma.clone().detach() x2.requires_grad = True beta2.requires_grad = True gamma2.requires_grad = True dummy_label = torch.randn_like(x) y = F.layer_norm(x, [hidden_size], gamma, beta, epsilon) diff = y-dummy_label l = (diff * diff).sum() / b l.backward() fln = FastLayerNorm(hidden_size).cuda() fln.load_state_dict({'bias': beta2, 'weight':gamma2}) if dtype == torch.float16: fln = fln.half() y2 = fln(x2) diff2 = (y2 - dummy_label) l2 = (diff2 * diff2).sum() / b l2.backward() self.assertTrue(torch.allclose(y2, y, atol=atol, rtol=rtol)) self.assertTrue(torch.allclose(x2.grad, x.grad, atol=atol,rtol=rtol)) self.assertTrue(torch.allclose(fln.bias.grad, beta.grad, atol=atol, rtol=rtol)) self.assertTrue(torch.allclose(fln.weight.grad, gamma.grad, atol=atol, rtol=rtol)) def test_performance(self): print() runs = 1000 device = torch.device('cuda') dtype =torch.float16 s = 512 b = 32 hidden_size = 1024 epsilon = 1e-5 x = torch.randn((s*b,hidden_size), dtype=dtype, device=device) beta = torch.randn(hidden_size, dtype=dtype, device=device) gamma = torch.randn(hidden_size, dtype=dtype, device=device) dy = torch.randn_like(x) stream = torch.cuda.Stream() with torch.cuda.stream(stream): timer = GPUTimer(stream) #warmup for r in range(runs): y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5) timer.start() for r in range(runs): y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5) timer.stop() timer.sync() total_bytes_fwd = (size_in_bytes(x) + size_in_bytes(y) + size_in_bytes(gamma) + size_in_bytes(beta) + size_in_bytes(mu) + size_in_bytes(rsigma) ) ms_fwd = timer.millis() / runs print('[FWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_fwd, total_bytes_fwd * 1e-6 / ms_fwd )) timer.start() for r in range(runs): dx, dgamma, dbeta = fln.ln_bwd(dy, x, mu, rsigma, gamma) timer.stop() timer.sync() total_bytes_bwd = (size_in_bytes(x) + size_in_bytes(dx) + size_in_bytes(dy) + size_in_bytes(gamma) + size_in_bytes(dgamma) + size_in_bytes(dbeta) + size_in_bytes(mu) + size_in_bytes(rsigma) ) ms_bwd = timer.millis() / runs print('[BWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_bwd, total_bytes_bwd * 1e-6 / ms_bwd )) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_encdec_multihead_attn.py ================================================ import torch import unittest from apex.contrib.multihead_attn import EncdecMultiheadAttn class EncdecMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.ref_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_encdec_multihead_attn(self) : grads = torch.randn_like(self.tst_inputs_q) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) def test_encdec_multihead_attn_time_mask(self) : grads = torch.randn_like(self.tst_inputs_q) time_mask_byte = torch.triu(torch.ones(self.tst_inputs_q.size(0), self.tst_inputs_k.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) time_mask_bool = time_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=time_mask_bool, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=time_mask_byte, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) def test_encdec_multihead_attn_pad_mask(self) : grads = torch.randn_like(self.tst_inputs_q) pad_mask_byte = torch.tril(torch.ones(self.tst_inputs_k.size(1), self.tst_inputs_k.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) pad_mask_bool = pad_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=pad_mask_bool, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=pad_mask_byte, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_encdec_multihead_attn_norm_add.py ================================================ import torch import unittest from apex.contrib.multihead_attn import EncdecMultiheadAttn class EncdecMultiheadAttnNormAddTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.ref_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_encdec_multihead_attn_norm_add(self) : grads = torch.randn_like(self.tst_inputs_q) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_fast_self_multihead_attn_bias.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=True, include_norm_add=False, separate_qkv_params=True, mask_additive=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=True, include_norm_add=False, separate_qkv_params=True, mask_additive=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn_additive_mask(self) : grads = torch.randn_like(self.tst_inputs) mask = ((torch.randn(self.sequences, self.seq_length) > 0) * -10000.0).half().cuda() ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=mask, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=mask, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_mha_fused_softmax.py ================================================ import torch import unittest import torch.nn.functional as F from apex.contrib.multihead_attn import fast_mask_softmax_dropout_func class FusedSoftmaxTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.mask = (torch.randn(self.sequences,self.seq_length)>0).cuda() self.mask = self.mask.half()*-10000 self.ref_inputs = torch.randn(self.heads * self.sequences, self.seq_length, self.seq_length, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs = self.ref_inputs.clone().detach().requires_grad_(True) def test_fused_softmax(self) : grads = torch.randn_like(self.tst_inputs) y_ref = self.ref_inputs.view(self.sequences, self.heads, self.seq_length, self.seq_length) y_ref = y_ref + self.mask.unsqueeze(1).unsqueeze(2) y_ref = y_ref.view(self.sequences*self.heads, self.seq_length, self.seq_length) y_ref = F.softmax(y_ref, dim=-1) y_ref = torch._fused_dropout(y_ref, 1.0) y_tst = fast_mask_softmax_dropout_func(True, self.heads, self.tst_inputs, self.mask, True, 0.0) y_ref[0].backward(grads) y_tst.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(y_ref[0], y_tst, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_self_multihead_attn.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn(self) : grads = torch.randn_like(self.tst_inputs) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) def test_self_multihead_attn_time_mask(self) : grads = torch.randn_like(self.tst_inputs) time_mask_byte= torch.triu(torch.ones(self.tst_inputs.size(0), self.tst_inputs.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) time_mask_bool= time_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=time_mask_bool, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=time_mask_byte, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) def test_self_multihead_attn_pad_mask(self) : grads = torch.randn_like(self.tst_inputs) pad_mask_byte = torch.tril(torch.ones(self.tst_inputs.size(1), self.tst_inputs.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) pad_mask_bool = pad_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=pad_mask_bool, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=pad_mask_byte, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/multihead_attn/test_self_multihead_attn_norm_add.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnNormAddTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn_norm_add(self) : grads = torch.randn_like(self.tst_inputs) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/test_label_smoothing.py ================================================ import torch from apex.contrib import xentropy as label_smoothing import unittest import warnings import random import numpy as np import time def label_smoothing_raw(x, target, padding_idx, smoothing): logprobs = torch.nn.functional.log_softmax(x, dim=-1, dtype=torch.float32) non_pad_mask = (target != padding_idx) nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1)) nll_loss = nll_loss.squeeze(1)[non_pad_mask] smooth_loss = -logprobs.mean(dim=-1)[non_pad_mask] loss = (1.0 - smoothing) * nll_loss + smoothing * smooth_loss return loss def label_smoothing_opt_1(x, target, padding_idx, smoothing): logprobs = torch.nn.functional.log_softmax(x, dim=-1, dtype=torch.float32) pad_mask = (target == padding_idx) ll_loss = logprobs.gather(dim=-1, index=target.unsqueeze(1)).squeeze(1) smooth_loss = logprobs.mean(dim=-1) loss = (smoothing - 1.0) * ll_loss - smoothing * smooth_loss loss.masked_fill_(pad_mask, 0) return loss class LabelSmoothingTest(unittest.TestCase): def setUp(self, seed=1234): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Set pytorch print precision torch.set_printoptions(precision=10) def gen_test_inputs(self, N, T, H, smoothing, padding_idx): logits = torch.randn((N*T, H), dtype=torch.half, device='cuda', requires_grad=True) labels = torch.randint(0, H, [N*T], device='cuda') for i in random.sample(range(N*T), N*T//6): labels[i] = padding_idx half_to_float = (logits.dtype == torch.half) return logits, labels, half_to_float def print_max_diff_elem(self, ref, tst): ref, tst = ref.flatten(), tst.flatten() diff = (ref - tst).abs().max() idx = (ref - tst).abs().argmax() print("Max atol idx: {}, diff: {:.6f}, ref: {:.6f}, tst: {:.6f}".format( idx, diff, ref[idx], tst[idx])) def test_label_smoothing_function(self): # Set label smoothing configuration smoothing, padding_idx = 0.1, 0 N, T, H = 128, 74, 32320 iters = 10 loss_func = label_smoothing.SoftmaxCrossEntropyLoss.apply for i in range(iters): logits, labels, half_to_float = self.gen_test_inputs( N, T, H, smoothing, padding_idx) # Run original softmax cross entropy with label smoothing logits.grad = None losses = label_smoothing_raw(logits, labels, padding_idx, smoothing) loss = losses.sum() loss.backward() ref_loss = loss.clone().detach() ref_grad = logits.grad.clone().detach() # Run optimized softmax cross entropy with label smoothing logits.grad = None losses = loss_func(logits, labels, smoothing, padding_idx, half_to_float) loss = losses.sum() loss.backward() val_loss = loss.clone().detach() val_grad = logits.grad.clone().detach() # Validate self.print_max_diff_elem(ref_grad, val_grad) self.assertTrue(torch.allclose(ref_loss, val_loss, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_grad, val_grad, atol=1e-5, rtol=1e-5)) def test_label_smoothing_perf(self): # Set label smoothing configuration smoothing, padding_idx = 0.1, 0 N, T, H = 128, 74, 32320 iters = 1000 loss_func = label_smoothing.SoftmaxCrossEntropyLoss.apply print() logits, labels, half_to_float = self.gen_test_inputs( N, T, H, smoothing, padding_idx) # Run original softmax cross entropy with label smoothing torch.cuda.synchronize() ts = time.time() for i in range(iters): logits.grad = None losses = label_smoothing_raw(logits, labels, padding_idx, smoothing) loss = losses.sum() / N loss.backward() torch.cuda.synchronize() print("Raw time {:.2f} s elapsed for {} iterations, norm {:.4f}".format( time.time() - ts, iters, logits.grad.norm())) # Run optimized softmax cross entropy with label smoothing torch.cuda.synchronize() ts = time.time() for i in range(iters): logits.grad = None losses = loss_func(logits, labels, smoothing, padding_idx, half_to_float) loss = losses.sum() / N loss.backward() torch.cuda.synchronize() print("Opt time {:.2f} s elapsed for {} iterations, norm {:.4f}".format( time.time() - ts, iters, logits.grad.norm())) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/transducer/test_transducer_joint.py ================================================ import torch import unittest from apex.contrib.transducer import TransducerJoint import transducer_ref class TransducerJointTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def gen_input(self, for_vector_kernel): self.B = 4 T_min = 51 T_max = 101 U_min = 12 U_max = 25 if for_vector_kernel: H = 512 else: H = 509 dtype = torch.float16 device = "cuda" self.f_tst = torch.randn((self.B, T_max, H), dtype=dtype, requires_grad=True, device=device) self.g_tst = torch.randn((self.B, U_max, H), dtype=dtype, requires_grad=True, device=device) self.h_grad = torch.randn(self.B, T_max, U_max, H, dtype=dtype, device=device) self.f_len = torch.randint(T_min, T_max+1, (self.B,), dtype=torch.int, device=device) self.g_len = torch.randint(U_min, U_max+1, (self.B,), dtype=torch.int, device=device) self.f_len[torch.randint(0, self.B, (1,)).item()] = T_max self.g_len[torch.randint(0, self.B, (1,)).item()] = U_max self.dropout_prob = 0.5 # Make sure gradients from out-of-bound locations are zero. This should be guaranteed by # the loss function for b in range(self.B): self.h_grad[b, self.f_len[b]:, :, :] = 0 self.h_grad[b, :, self.g_len[b]:, :] = 0 self.h_grad_packed = self._pack(self.h_grad, self.f_len, self.g_len) def _pack(self, x, f_len, g_len): B = x.size(0) list_x = [] for b in range(B): list_x_row = [x[b, t, :g_len[b]] for t in range(f_len[b])] x_row = torch.cat(list_x_row) list_x.append(x_row) x_packed = torch.cat(list_x).data.clone() x_packed.requires_grad = True batch_offset = torch.cumsum(f_len * g_len, dim=0) return x_packed def _unpack(self, x, f_len, g_len): batch_offset = torch.cumsum(f_len * g_len, dim=0) x_unpacked = torch.zeros_like(self.h_grad, dtype=torch.uint8) B = self.h_grad.size(0) H = self.h_grad.size(-1) for b in range(B): my_batch_offset = 0 if b == 0 else batch_offset[b-1] my_f_len = f_len[b] my_g_len = g_len[b] for t in range(my_f_len): x_unpacked[b, t, :my_g_len] = x[my_batch_offset + t*my_g_len : my_batch_offset + t*my_g_len + my_g_len] return x_unpacked def run_transducer_joint(self, for_vector_kernel, pack_output, relu, dropout): self.gen_input(for_vector_kernel=for_vector_kernel) # Generate reference f_ref = self.f_tst.data.clone() g_ref = self.g_tst.data.clone() f_ref.requires_grad = True g_ref.requires_grad = True my_joint = TransducerJoint(pack_output=pack_output, relu=relu, dropout=dropout, dropout_prob=self.dropout_prob, probe_mask=True) if not pack_output: h_tst = my_joint( f=self.f_tst, g=self.g_tst, f_len=self.f_len, g_len=self.g_len) h_tst.backward(self.h_grad) if dropout: mask = my_joint.mask_probe[0] else: batch_offset = torch.cumsum(self.f_len * self.g_len, dim=0) h_tst = my_joint( f=self.f_tst, g=self.g_tst, f_len=self.f_len, g_len=self.g_len, batch_offset=batch_offset, packed_batch=batch_offset[-1]) h_tst.backward(self.h_grad_packed) if dropout: mask_packed = my_joint.mask_probe[0] mask = self._unpack(mask_packed, self.f_len, self.g_len) # reference h_ref, f_grad_ref, g_grad_ref \ = transducer_ref.transducer_joint_reference(f=f_ref, g=g_ref, h_grad=self.h_grad, f_len=self.f_len, g_len=self.g_len, pack_output=pack_output, relu=relu, dropout=dropout, dropout_prob=self.dropout_prob, mask=mask if dropout else None) f_grad_tst = self.f_tst.grad g_grad_tst = self.g_tst.grad self.assertTrue(torch.allclose(h_ref, h_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(f_grad_ref, f_grad_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(g_grad_ref, g_grad_tst, atol=1e-4, rtol=1e-4)) def test_transducer_joint(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=False, dropout=False) def test_transducer_joint_vec(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=False, dropout=False) def test_transducer_joint_pack(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=False, dropout=False) def test_transducer_joint_vec_pack(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=False, dropout=False) def test_transducer_joint_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=False) def test_transducer_joint_vec_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=True, dropout=False) def test_transducer_joint_pack_relu(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=True, dropout=False) def test_transducer_joint_vec_pack_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=False) def test_transducer_joint_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=True) def test_transducer_joint_vec_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=True, dropout=True) def test_transducer_joint_pack_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=True, dropout=True) def test_transducer_joint_vec_pack_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=True) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/transducer/test_transducer_loss.py ================================================ import torch import unittest from apex.contrib.transducer import TransducerLoss import transducer_ref class TransducerLossTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def gen_input(self, scalar_t, for_vector_kernel): self.B = 5 T_min = 23 T_max = 51 U_min = 12 U_max = 25 V = 16 if for_vector_kernel else 14 self.blank_idx = V - 1 device = "cuda" self.x_tst = torch.randn((self.B, T_max, U_max, V), dtype=scalar_t, requires_grad=True, device=device) self.y = torch.randint(0, self.blank_idx, (self.B, U_max-1), dtype=torch.int, device=device) self.f_len = torch.randint(T_min, T_max+1, (self.B,), dtype=torch.int, device=device) self.y_len = torch.randint(U_min-1, U_max, (self.B,), dtype=torch.int, device=device) self.f_len[torch.randint(0, self.B, (1,)).item()] = T_max self.y_len[torch.randint(0, self.B, (1,)).item()] = U_max-1 self.x_tst_packed, self.batch_offset = self._pack(self.x_tst) # Generate reference x_ref = self.x_tst.data.clone() x_ref.requires_grad = True loss_grad = torch.ones(x_ref.size(0), dtype=x_ref.dtype, device=x_ref.device)/x_ref.size(0) _, _, self.grad_ref, self.loss_ref \ = transducer_ref.transducer_loss_reference( x=x_ref, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx, loss_grad=loss_grad) def _pack(self, x): list_x = [] for b in range(self.B): list_x_row = [x[b, t, : self.y_len[b]+1] for t in range(self.f_len[b])] x_row = torch.cat(list_x_row) list_x.append(x_row) x_packed = torch.cat(list_x).data.clone() x_packed.requires_grad = True batch_offset = torch.cumsum(self.f_len * (self.y_len+1), dim=0) return x_packed, batch_offset def _unpack(self, x): x_unpacked = torch.zeros(self.B, self.f_len.max(), self.y_len.max()+1, x.size(-1), dtype=x.dtype, device=x.device) for b in range(self.B): my_batch_offset = 0 if b == 0 else self.batch_offset[b-1] my_f_len = self.f_len[b] my_g_len = self.y_len[b] + 1 for t in range(my_f_len): for u in range(my_g_len): x_unpacked[b, t, u] = x[my_batch_offset + t*my_g_len + u] return x_unpacked def run_transducer_loss(self, scalar_t, fuse_softmax_backward, packed_input, for_vector_kernel): self.gen_input(scalar_t, for_vector_kernel) my_loss = TransducerLoss( fuse_softmax_backward=fuse_softmax_backward, packed_input=packed_input) if not packed_input: loss_tst = my_loss( x=self.x_tst, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx) loss_tst.mean().backward() grad_tst = self.x_tst.grad else: loss_tst = my_loss( x=self.x_tst_packed, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx, batch_offset=self.batch_offset, max_f_len=max(self.f_len)) loss_tst.mean().backward() grad_tst_packed = self.x_tst_packed.grad grad_tst = self._unpack(grad_tst_packed) return loss_tst, grad_tst def test_transducer_loss_fp32(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float32, fuse_softmax_backward=False, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-5, rtol=1e-5)) def test_transducer_loss_fp16(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=False, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion_packed(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=True, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion_packed_vec(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=True, for_vector_kernel=True) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSentenceT5/apex/contrib/test/transducer/transducer_ref.py ================================================ import torch import numpy as np import pdb def transducer_loss_reference(x, label, f_len, y_len, blank_idx, loss_grad): def log_sum_exp(a, b): if (a >= b): return a + torch.log(1 + torch.exp(b-a)) else: return b + torch.log(1 + torch.exp(a-b)) def forward_alpha(x, label, f_len, y_len, blank_idx): B, T, U, V = x.size() acc_t = torch.float32 if x.dtype in [torch.float16, torch.float32] else x.dtype alpha = torch.zeros((B, T, U), dtype=acc_t, device=x.device) for b in range(B): alpha[b, 0, 0] = 0 for t in range(1, f_len[b]): alpha[b, t, 0] = alpha[b, t-1, 0] + x[b, t-1, 0, blank_idx] for u in range(1, y_len[b]+1): alpha[b, 0, u] = alpha[b, 0, u-1] + x[b, 0, u-1, label[b, u-1]] for t in range(1, f_len[b]): for u in range(1, y_len[b]+1): curr_ = alpha[b, t-1, u] + x[b, t-1, u, blank_idx] next_ = alpha[b, t, u-1] + x[b, t, u-1, label[b, u-1]] alpha[b, t, u] = log_sum_exp(curr_, next_) return alpha def forward_beta(x, label, f_len, y_len, blank_idx): B, T, U, V = x.shape acc_t = torch.float32 if x.dtype in [torch.float16, torch.float32] else x.dtype beta = torch.zeros((B, T, U), dtype=acc_t, device=x.device) for b in range(B): beta[b, f_len[b]-1, y_len[b]] = x[b, f_len[b]-1, y_len[b], blank_idx] for t in range(f_len[b]-2, -1, -1): beta[b, t, y_len[b]] = beta[b, t+1, y_len[b]] + x[b, t, y_len[b], blank_idx] for u in range(y_len[b]-1, -1, -1): beta[b, f_len[b]-1, u] = beta[b, f_len[b]-1, u+1] + x[b, f_len[b]-1, u, label[b, u]] for t in range(f_len[b]-2, -1, -1): for u in range(y_len[b]-1, -1, -1): curr_ = beta[b, t+1, u] + x[b, t, u, blank_idx] next_ = beta[b, t, u+1] + x[b, t, u, label[b, u]] beta[b, t, u] = log_sum_exp(curr_, next_) return beta def backward(x, label, f_len, y_len, alpha, beta, loss_grad, blank_idx): grad = torch.zeros_like(x) B, T, U, V = x.size() for b in range(B): common_factor = torch.log(loss_grad[b]) + alpha - beta[b, 0, 0] # next for u in range(y_len[b]): grad[b, :f_len[b], u, label[b, u]] = -torch.exp(common_factor[b, :f_len[b], u] + beta[b, :f_len[b], u+1] + x[b, :f_len[b], u, label[b, u]]) # current grad[b, :f_len[b]-1, :y_len[b]+1, blank_idx] \ = -torch.exp(common_factor[b, :f_len[b]-1, :y_len[b]+1] + beta[b, 1:f_len[b], :y_len[b]+1] + x[b, :f_len[b]-1, :y_len[b]+1, blank_idx]) grad[b, f_len[b]-1, y_len[b], blank_idx] = -torch.exp(common_factor[b, f_len[b]-1, y_len[b]] + x[b, f_len[b]-1, y_len[b], blank_idx]) return grad x_log = torch.nn.functional.log_softmax(x, dim=-1) alpha = forward_alpha(x_log, label, f_len, y_len, blank_idx) beta = forward_beta(x_log, label, f_len, y_len, blank_idx) grad = backward(x_log, label, f_len, y_len, alpha, beta, loss_grad, blank_idx) x_log.backward(grad) loss = -beta[:, 0, 0] loss = loss.to(x.dtype) return alpha, beta, x.grad, loss def transducer_joint_reference(f, g, h_grad, f_len, g_len, pack_output, relu, dropout, dropout_prob=0, mask=None): if dropout and mask == None: raise NotImplementedError("mask needs to supplied to test dropout.") B, T, H = f.size() U = g.size(1) f_expand = f.unsqueeze(dim=2) g_expand = g.unsqueeze(dim=1) h = f_expand + g_expand if relu: h = torch.nn.functional.relu(h) if dropout: h *= mask scale = 1/(1-dropout_prob) h *= scale h.backward(h_grad) if pack_output == False: # intentionally set don't-care region to -1 to test if transducer joint # write these regions to avoid NaN and inf for b in range(B): h[b, f_len[b]:] = -1 h[b, :, g_len[b]:] = -1 return h, f.grad, g.grad # packing list_to_pack = [] for b in range(B): list_to_pack.append(h[b, :f_len[b], :g_len[b], :].reshape(-1, H)) h_packed = torch.cat(list_to_pack) return h_packed, f.grad, g.grad ================================================ FILE: KoSentenceT5/apex/contrib/transducer/__init__.py ================================================ from .transducer import TransducerJoint from .transducer import TransducerLoss ================================================ FILE: KoSentenceT5/apex/contrib/transducer/transducer.py ================================================ import torch import transducer_loss_cuda import transducer_joint_cuda class TransducerJoint(torch.nn.Module): """Transducer joint Detail of this loss function can be found in: Sequence Transduction with Recurrent Neural Networks Arguments: pack_output (bool, optional): whether to pack the output in a compact form with don't-care data being removed. (default: False) relu (bool, optional): apply ReLU to the output of the joint operation. Requires opt=1 (default: False) dropout (bool, optional): apply dropout to the output of the joint operation. Requires opt=1 (default: False) opt (int, optional): pick the optimization level in [0, 1]. opt=1 picks a tiled algorithm. (default: 1) fwd_tile_size (int, optional): tile size used in forward operation. This argument will be ignored if opt != 1. (default: 4) dropout_prob (float, optional): dropout probability. (default: 0.0) probe_mask (bool, optional): a flag used to probe the mask generated by ReLU and/or dropout operation. When this argument is set to True, the mask can be accessed through self.mask_probe. (default: false) """ def __init__(self, pack_output=False, relu=False, dropout=False, opt=1, fwd_tile_size=4, dropout_prob=0, probe_mask=False): super(TransducerJoint, self).__init__() self.pack_output = pack_output self.relu = relu self.dropout = dropout self.dropout_prob = dropout_prob self.opt = opt self.fwd_tile_size = fwd_tile_size self.dummy_batch_offset = torch.empty(0) masked = self.relu or self.dropout self.mask_probe = [] if masked and probe_mask else None if masked and opt != 1: raise NotImplementedError("ReLU and dropout fusion is only supported with opt=1") def forward(self, f, g, f_len, g_len, batch_offset=None, packed_batch=0): """Forward operation of transducer joint Arguments: f (tensor): transcription vector from encode block of shape (B, T, H). g (tensor): prediction vector form predict block of shape (B, U, H). f_len (tensor): length of transcription vector for each batch. g_len (tensor): length of prediction vector minus 1 for each batch. batch_offset (tensor, optional): tensor containing the offset of each batch in the results. For example, batch offset can be obtained from: batch_offset = torch.cumsum(f_len*g_len, dim=0) This argument is required if pack_output == True, and is ignored if pack_output == False. (default: None) packed_batch (int, optional): the batch size after packing. This argument is ignored if pack_output == False. (default: 0) """ my_batch_offset = batch_offset if self.pack_output else self.dummy_batch_offset if self.pack_output and (batch_offset is None or packed_batch == 0): raise Exception("Please specify batch_offset and packed_batch when packing is enabled") dropout = self.dropout and self.training # only dropout for training return TransducerJointFunc.apply(f, g, f_len, g_len, self.pack_output, self.relu, dropout, my_batch_offset, packed_batch, self.opt, self.fwd_tile_size, self.dropout_prob, self.mask_probe) class TransducerLoss(torch.nn.Module): """Transducer loss Detail of this loss function can be found in: Sequence Transduction with Recurrent Neural Networks Arguments: fuse_softmax_backward (bool, optional) whether to fuse the backward of transducer loss with softmax. (default: True) opt (int, optional): pick the optimization level in [0, 1]. opt=1 picks a more optimized algorithm. In some cases, opt=1 might fall back to opt=0. (default: 1) packed_input (bool, optional): whether to pack the output in a compact form with don't-care data being removed. (default: False) """ def __init__(self, fuse_softmax_backward=True, opt=1, packed_input=False): super(TransducerLoss, self).__init__() self.fuse_softmax_backward = fuse_softmax_backward self.opt = opt self.packed_input = packed_input self.dummy_batch_offset = torch.empty(0) def forward(self, x, label, f_len, y_len, blank_idx, batch_offset=None, max_f_len=None, debug_list=None): """Forward operation of transducer joint Arguments: x (tensor): input tensor to the loss function with a shape of (B, T, U, H). label (tensor): labels for the input data. f_len (tensor): lengths of the inputs in the time dimension for each batch. y_len (tensor): lengths of the labels for each batch. blank_idx (int): index for the null symbol. batch_offset (tensor, optional): tensor containing the offset of each batch in the input. For example, batch offset can be obtained from: batch_offset = torch.cumsum(f_len*(y_len+1), dim=0) This argument is required if packed_input == True, and is ignored if packed_input == False. (default: None) max_f_len (int, optional): maximum length of the input in the time dimension. For example, it can be obtained as max_f_len = max(f_len) This argument is required if packed_input == True, and is ignored if packed_input == False. (default: None) (default: None) debug_list (list, optional): when an empty list is supplied, Alpha and Beta generated in the forward operation will be attached to this list for debug purpose. (default: None) """ if self.packed_input: if batch_offset is None or max_f_len is None: raise Exception("Please specify batch_offset and max_f_len when packing is \ enabled") my_batch_offset = batch_offset my_max_f_len = max_f_len else: my_batch_offset = self.dummy_batch_offset my_max_f_len = x.size(1) return TransducerLossFunc.apply(x, label, f_len, y_len, my_batch_offset, my_max_f_len, blank_idx, self.fuse_softmax_backward, debug_list, self.opt, self.packed_input) class TransducerLossFunc(torch.autograd.Function): @staticmethod def forward(ctx, x, label, f_len, y_len, batch_offset, max_f_len, blank_idx, fuse_softmax_backward, debug_list, opt, packed_input): if fuse_softmax_backward == False: with torch.enable_grad(): x = torch.nn.functional.log_softmax(x, dim=-1) else: x = torch.nn.functional.log_softmax(x, dim=-1) alpha, beta, loss = transducer_loss_cuda.forward( x, label, f_len, y_len, batch_offset, max_f_len, blank_idx, opt, packed_input) if debug_list == []: debug_list += [alpha, beta] ctx.save_for_backward(x, alpha, beta, f_len, y_len, label, batch_offset) ctx.blank_idx = blank_idx ctx.fuse_softmax_backward = fuse_softmax_backward ctx.opt = opt ctx.packed_input = packed_input ctx.max_f_len = max_f_len return loss @staticmethod def backward(ctx, loss_grad): x, alpha, beta, f_len, y_len, label, batch_offset = ctx.saved_tensors x_grad = transducer_loss_cuda.backward( x, loss_grad, alpha, beta, f_len, y_len, label, batch_offset, ctx.max_f_len, ctx.blank_idx, ctx.opt, ctx.fuse_softmax_backward, ctx.packed_input) if ctx.fuse_softmax_backward == False: x_grad = x.backward(x_grad) return x_grad, None, None, None, None, None, None, None, None, None, None class TransducerJointFunc(torch.autograd.Function): @staticmethod def forward(ctx, f, g, f_len, g_len, pack_output, relu, dropout, batch_offset, packed_batch, opt, fwd_tile_size, dropout_prob, mask_probe): h = transducer_joint_cuda.forward(f, g, f_len, g_len, batch_offset, packed_batch, opt, pack_output, relu, dropout, dropout_prob, fwd_tile_size) masked = relu or dropout if masked: ctx.save_for_backward(h[1], f_len, g_len, batch_offset) if mask_probe is not None: mask_probe.append(h[1]) else: ctx.save_for_backward(f_len, g_len, batch_offset) ctx.pack_output = pack_output ctx.masked = relu or dropout ctx.max_f_len = f.size(1) ctx.max_g_len = g.size(1) ctx.scale = 1 / (1-dropout_prob) if dropout and dropout_prob != 1 else 1 return h[0] @staticmethod def backward(ctx, loss_grad): if ctx.masked: mask, f_len, g_len, batch_offset = ctx.saved_tensors inp = [loss_grad, mask] else: f_len, g_len, batch_offset = ctx.saved_tensors inp = [loss_grad] f_grad, g_grad = transducer_joint_cuda.backward( inp, f_len, g_len, batch_offset, ctx.max_f_len, ctx.max_g_len, ctx.pack_output, ctx.scale) return f_grad, g_grad, None, None, None, None, None, None, None, None, None, None, None, \ None, None, None ================================================ FILE: KoSentenceT5/apex/contrib/xentropy/__init__.py ================================================ try: import torch import xentropy_cuda from .softmax_xentropy import SoftmaxCrossEntropyLoss del torch del xentropy_cuda del softmax_xentropy except ImportError as err: print("apex was installed without --xentropy flag, contrib.xentropy is not available") ================================================ FILE: KoSentenceT5/apex/contrib/xentropy/softmax_xentropy.py ================================================ import torch import xentropy_cuda class SoftmaxCrossEntropyLoss(torch.autograd.Function): @staticmethod def forward(ctx, logits, labels, smoothing=0.0, padding_idx=0, half_to_float=False): losses, max_log_sum_exp = xentropy_cuda.forward( logits, labels, smoothing, half_to_float) losses.masked_fill_(labels==padding_idx, 0) ctx.save_for_backward(logits, max_log_sum_exp, labels, torch.FloatTensor([smoothing]), torch.LongTensor([padding_idx])) return losses @staticmethod def backward(ctx, grad_loss): logits, max_log_sum_exp, labels, smoothing, padding_idx = ctx.saved_tensors if not grad_loss.is_contiguous(): grad_loss = grad_loss.contiguous() grad_loss.masked_fill_(labels==padding_idx.item(), 0) grad_logits = xentropy_cuda.backward( grad_loss.contiguous(), logits, max_log_sum_exp, labels, smoothing.item()) return grad_logits, None, None, None, None ================================================ FILE: KoSentenceT5/apex/fp16_utils/README.md ================================================ fp16_optimizer.py contains `FP16_Optimizer`, a Python class designed to wrap an existing Pytorch optimizer and automatically enable master parameters and loss scaling in a manner transparent to the user. To use `FP16_Optimizer`, only two lines of one's Python model need to change. #### [FP16_Optimizer API documentation](https://nvidia.github.io/apex/fp16_utils.html#automatic-management-of-master-params-loss-scaling) #### [Simple examples with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/FP16_Optimizer_simple) #### [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) #### [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model) fp16_util.py contains a number of utilities to manually manage master parameters and loss scaling, if the user chooses. #### [Manual management documentation](https://nvidia.github.io/apex/fp16_utils.html#manual-master-parameter-management) The [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) and [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model) directories also contain `main.py` files that demonstrate manual management of master parameters and static loss scaling. These examples illustrate what sort of operations `FP16_Optimizer` is performing automatically. ================================================ FILE: KoSentenceT5/apex/fp16_utils/__init__.py ================================================ from .fp16util import ( BN_convert_float, network_to_half, prep_param_lists, model_grads_to_master_grads, master_params_to_model_params, tofp16, to_python_float, clip_grad_norm, convert_module, convert_network, FP16Model, ) from .fp16_optimizer import FP16_Optimizer from .loss_scaler import LossScaler, DynamicLossScaler ================================================ FILE: KoSentenceT5/apex/fp16_utils/fp16_optimizer.py ================================================ import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from ..amp._amp_state import _amp_state, maybe_print from ..amp.scaler import LossScaler from ..multi_tensor_apply import multi_tensor_applier from .fp16util import model_grads_to_master_grads, master_params_to_model_params, clip_grad_norm # TODO: Update overflow check + downscale to use Carl's fused kernel. class FP16_Optimizer(object): def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=True): print("Warning: FP16_Optimizer is deprecated and dangerous, and will be deleted soon. " "If it still works, you're probably getting lucky. " "For mixed precision, use the documented API https://nvidia.github.io/apex/amp.html, with opt_level=O1.") if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.verbose = verbose self.optimizer = init_optimizer # init_state_dict sets up an alternative way to cast per-param state tensors. # Stashing here in case https://github.com/pytorch/pytorch/issues/7733 makes it necessary. # init_state_dict = init_optimizer.state_dict() self.fp16_groups = [] self.fp32_from_fp16_groups = [] self.fp32_from_fp32_groups = [] for i, param_group in enumerate(self.optimizer.param_groups): self.maybe_print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(param_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': self.maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}" .format(param.size())) fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True param_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) # Reset existing state dict key to the new master param. # We still need to recast per-param state tensors, if any, to FP32. if param in self.optimizer.state: self.optimizer.state[master_param] = self.optimizer.state.pop(param) elif param.type() == 'torch.cuda.FloatTensor': self.maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}" .format(param.size())) fp32_params_this_group.append(param) param_group['params'][i] = param else: raise TypeError("Wrapped parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) self.fp16_groups.append(fp16_params_this_group) self.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) self.fp32_from_fp32_groups.append(fp32_params_this_group) self.all_fp16_params = [] for group in self.fp16_groups: self.all_fp16_params += group self.all_fp32_from_fp16_params = [] for group in self.fp32_from_fp16_groups: self.all_fp32_from_fp16_params += group self.all_fp32_from_fp32_params = [] for group in self.fp32_from_fp32_groups: self.all_fp32_from_fp32_params += group # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors self.optimizer.load_state_dict(self.optimizer.state_dict()) # alternative way to cast per-param state tensors: # self.optimizer.load_state_dict(init_state_dict) if dynamic_loss_scale: self.dynamic_loss_scale = True if dynamic_loss_args is not None: self.loss_scaler = LossScaler("dynamic", **dynamic_loss_args) else: self.loss_scaler = LossScaler("dynamic") else: self.dynamic_loss_scale = False self.loss_scaler = LossScaler(static_loss_scale) self.overflow = False self.first_closure_call_this_step = True self.clip_grad_norm = clip_grad_norm # TODO: Centralize exposure and import error checking for the C backend. if multi_tensor_applier.available: import amp_C self.multi_tensor_scale = amp_C.multi_tensor_scale self._dummy_overflow_buf = torch.cuda.IntTensor([0]); # Having self.maybe_print distinct from _amp_state.maybe_print is another artifact # of having to support FP16_Optimizer separately, for the time being. def maybe_print(self, msg): if self.verbose: print(msg) def __getstate__(self): raise RuntimeError("FP16_Optimizer should be serialized using state_dict().") def __setstate__(self, state): raise RuntimeError("FP16_Optimizer should be deserialized using load_state_dict().") def zero_grad(self, set_grads_to_None=False): """ Zero fp32 and fp16 parameter grads. """ # In principle, only the .grad attributes of the model params need to be zeroed, # because gradients are copied into the FP32 master params. However, we zero # all gradients owned by the optimizer, just to be safe: for group in self.optimizer.param_groups: for p in group['params']: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() # Zero fp16 gradients owned by the model: for fp16_group in self.fp16_groups: for param in fp16_group: if set_grads_to_None: param.grad = None else: if param.grad is not None: param.grad.detach_() # as in torch.optim.optimizer.zero_grad() param.grad.zero_() # Should not be used anymore. # def _check_overflow(self): # params = [] # for group in self.fp16_groups: # for param in group: # params.append(param) # for group in self.fp32_from_fp32_groups: # for param in group: # params.append(param) # self.overflow = self.loss_scaler.has_overflow(params) # def _update_scale(self, has_overflow=False): # self.loss_scaler.update_scale(has_overflow) def _master_params_to_model_params(self): if multi_tensor_applier.available: if len(self.all_fp16_params) > 0: multi_tensor_applier( self.multi_tensor_scale, self._dummy_overflow_buf, [self.all_fp32_from_fp16_params, self.all_fp16_params], 1.0) else: for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): master_params_to_model_params(fp16_group, fp32_from_fp16_group) # To consider: Integrate distributed with this wrapper by registering a hook on each variable # that does the overflow check, gradient copy + downscale, and fp32 allreduce in a different stream. # def _model_grads_to_master_grads(self): # for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): # model_grads_to_master_grads(fp16_group, fp32_from_fp16_group) # def _downscale_master(self): # if self.loss_scale != 1.0: # for group in self.optimizer.param_groups: # for param in group['params']: # if param.grad is not None: # param.grad.data.mul_(1./self.loss_scale) def clip_master_grads(self, max_norm, norm_type=2): """ Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the current fp32 gradients (viewed as a single vector). .. warning:: Returns -1 if the most recently computed fp16 gradients overflowed (that is, if ``self.overflow`` is ``True``). """ if not self.overflow: fp32_params = [] for param_group in self.optimizer.param_groups: for param in param_group['params']: fp32_params.append(param) return self.clip_grad_norm(fp32_params, max_norm, norm_type) else: return -1 def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step state_dict['optimizer_state_dict'] = self.optimizer.state_dict() state_dict['fp32_from_fp16'] = self.fp32_from_fp16_groups return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] self.first_closure_call_this_step = state_dict['first_closure_call_this_step'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) # At this point, the optimizer's references to the model's fp32 parameters are up to date. # The optimizer's hyperparameters and internal buffers are also up to date. # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still # out of date. There are two options. # 1: Refresh the master params from the model's fp16 params. # This requires less storage but incurs precision loss. # 2: Save and restore the fp32 master copies separately. # We choose option 2. # # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device # of their associated parameters, because it's possible those buffers might not exist yet in # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been # constructed in the same way as the one whose state_dict we are loading, the same master params # are guaranteed to exist, so we can just copy_() from the saved master params. for current_group, saved_group in zip(self.fp32_from_fp16_groups, state_dict['fp32_from_fp16']): for current, saved in zip(current_group, saved_group): current.data.copy_(saved.data) def step(self, closure=None): # could add clip option. """ If no closure is supplied, :attr:`step` should be called after ``fp16_optimizer_obj.backward(loss)``. :attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to :class:`FP16_Optimizer`'s constructor, then copies the updated fp32 params into the fp16 params originally referenced by :class:`FP16_Optimizer`'s constructor, so the user may immediately run another forward pass using their model. If a closure is supplied, :attr:`step` may be called without a prior call to :attr:`backward(loss)`. This control flow is identical to `ordinary Pytorch optimizer use`_ with closures. However, the user should take care that any ``loss.backward()`` call within the closure has been replaced by ``fp16_optimizer_obj.backward(loss)``. Args: closure (optional): Closure that will be supplied to the underlying optimizer originally passed to :class:`FP16_Optimizer`'s constructor. closure should call :attr:`zero_grad()` on the :class:`FP16_Optimizer` object, compute the loss, call :attr:`backward(loss)`, and return the loss. Example with closure:: # optimizer is assumed to be an FP16_Optimizer object, previously constructed from an # existing pytorch optimizer. for input, target in dataset: def closure(): optimizer.zero_grad() output = model(input) loss = loss_fn(output, target) # loss.backward() becomes: optimizer.backward(loss) return loss optimizer.step(closure) .. warning:: Currently, calling :attr:`step` with a closure is not compatible with dynamic loss scaling. .. _`ordinary Pytorch optimizer use`: http://pytorch.org/docs/master/optim.html#optimizer-step-closure """ scale = self.loss_scaler.loss_scale() # To consider: Should this be in step(), or update_master_grads? It works either way, # but I should make it consistent with the Amp control flow, which updates the scale # during backward context manager exit. # self._update_scale(self.overflow) if self.overflow: # Using _amp_state.maybe_print instead of self.print here is intentional. maybe_print("Gradient overflow. Skipping step, reducing " + "loss scale to {}".format(self.loss_scaler.loss_scale())) return if closure is not None: retval = self._step_with_closure(closure) else: # torch.cuda.nvtx.range_push("pytorch optimizer step") retval = self.optimizer.step() # torch.cuda.nvtx.range_pop() self._master_params_to_model_params() return retval def _step_with_closure(self, closure): def wrapped_closure(): # helpful for debugging # print("Calling wrapped_closure, first_closure_call_this_step = {}" # .format(self.first_closure_call_this_step)) if self.first_closure_call_this_step: # We expect that the fp16 params are initially fresh on entering self.step(), # so _master_params_to_model_params() is unnecessary the first time wrapped_closure() # is called within self.optimizer.step(). self.first_closure_call_this_step = False else: # If self.optimizer.step() internally calls wrapped_closure more than once, # it may update the fp32 params after each call. However, self.optimizer # doesn't know about the fp16 params at all. If the fp32 params get updated, # we can't rely on self.optimizer to refresh the fp16 params. We need # to handle that manually: self._master_params_to_model_params() # Our API expects the user to give us ownership of the backward() call by # replacing all calls to loss.backward() with optimizer.backward(loss). # This requirement holds whether or not the call to backward() is made within a closure. # If the user is properly calling optimizer.backward(loss) within "closure," # calling closure() here will give the fp32 master params fresh gradients # for the optimizer to play with, so all wrapped_closure needs to do is call # closure() and return the loss. temp_loss = closure() while(self.overflow): scale = self.loss_scaler.loss_scale() # self._update_scale(self.overflow) # now done at the end of backward print("OVERFLOW within closure! Skipping step, reducing loss scale to {}".format( self.loss_scaler.loss_scale())) temp_loss = closure() return temp_loss retval = self.optimizer.step(wrapped_closure) self.first_closure_call_this_step = True return retval def backward(self, loss, update_master_grads=True, retain_graph=False): """ :attr:`backward` performs the following conceptual steps: 1. fp32_loss = loss.float() (see first Note below) 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's leaves (which may be fp16, fp32, or a mixture, depending how your model was defined). 4. fp16 grads are then copied to the master params' ``.grad`` attributes (see second Note), which are guaranteed to be fp32. 5. Finally, master grads are divided by loss_scale. In this way, after :attr:`backward`, the master params have fresh gradients, and :attr:`step` may be called. .. note:: :attr:`backward` internally converts the loss to fp32 before applying the loss scale. This provides some additional safety against overflow if the user has supplied an fp16 loss value. However, for maximum overflow safety, the user should compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to :attr:`backward`. .. warning:: The gradients found in a model's leaves after the call to :attr:`backward` should not be regarded as valid in general, because it's possible they have been scaled (and in the case of dynamic loss scaling, the scale factor may change over time). If the user wants to inspect gradients after a call to :attr:`backward`, only the master gradients should be regarded as valid. These can be retrieved via :attr:`inspect_master_grad_data()`. Args: loss: The loss output by the user's model. loss may be either float or half (but see first Note above). update_master_grads (bool, optional, default=True): Option to copy fp16 grads to fp32 grads on this call. By setting this to False, the user can delay the copy, which is useful to eliminate redundant fp16->fp32 grad copies if :attr:`backward` is being called on multiple losses in one iteration. If set to False, the user becomes responsible for calling :attr:`update_master_grads` before calling :attr:`step`. retain_graph (bool, optional, default=False): Forwards the usual ``retain_graph=True`` option to the internal call to ``loss.backward``. If ``retain_graph`` is being used to accumulate gradient values from multiple backward passes before calling ``optimizer.step``, passing ``update_master_grads=False`` is also recommended (see Example below). Example:: # Ordinary operation: optimizer.backward(loss) # Naive operation with multiple losses (technically valid, but less efficient): # fp32 grads will be correct after the second call, but # the first call incurs an unnecessary fp16->fp32 grad copy. optimizer.backward(loss1) optimizer.backward(loss2) # More efficient way to handle multiple losses: # The fp16->fp32 grad copy is delayed until fp16 grads from all # losses have been accumulated. optimizer.backward(loss1, update_master_grads=False) optimizer.backward(loss2, update_master_grads=False) optimizer.update_master_grads() """ # To consider: try multiple backward passes using retain_grad=True to find # a loss scale that works. After you find a loss scale that works, do a final dummy # backward pass with retain_graph=False to tear down the graph. Doing this would avoid # discarding the iteration, but probably wouldn't improve overall efficiency. scaled_loss = loss.float()*self.loss_scaler.loss_scale() scaled_loss.backward(retain_graph=retain_graph) if update_master_grads: self.update_master_grads() def update_master_grads(self): # torch.cuda.nvtx.range_push("update_master_grads") """ Copy the ``.grad`` attribute from stored references to fp16 parameters to the ``.grad`` attribute of the fp32 master parameters that are directly updated by the optimizer. :attr:`update_master_grads` only needs to be called if ``fp16_optimizer_obj.backward`` was called with ``update_master_grads=False``. """ # if self.dynamic_loss_scale: # self._check_overflow() # if self.overflow: return # self._model_grads_to_master_grads() # self._downscale_master() # Use the one-shot multi-tensor apply kernel self.loss_scaler.clear_overflow_state() if len(self.all_fp16_params) > 0: # print("Model grads before") # print([param.grad.data for param in self.all_fp16_params]) # I'm ONLY writing this as an incremental way to make some tests pass until # I can refactor the tests as well. # FP16_Optimizer should not be used by anyone. model_grads = [] master_grads = [] for model_param, master_param in zip(self.all_fp16_params, self.all_fp32_from_fp16_params): if model_param.grad is not None: model_grads.append(model_param.grad) if master_param.grad is None: master_param.grad = torch.empty_like(master_param) master_grads.append(master_param.grad) self.loss_scaler.unscale( model_grads, master_grads, self.loss_scaler.loss_scale()) # print("Master grads after") # print([param.grad.data for param in self.all_fp32_from_fp16_params]) if len(self.all_fp32_from_fp32_params) > 0: model_grads = [] master_grads = [] for model_param, master_param in zip(self.all_fp32_from_fp32_params, self.all_fp32_from_fp32_params): if model_param.grad is not None: model_grads.append(model_param.grad) master_grads.append(master_param.grad) # print("Model grads before") # print([param.grad.data for param in self.all_fp32_from_fp32_params]) self.loss_scaler.unscale( model_grads, master_grads, self.loss_scaler.loss_scale()) # print("Master grads after") # print([param.grad.data for param in self.all_fp32_from_fp32_params]) # quit() self.overflow = self.loss_scaler.update_scale() # torch.cuda.nvtx.range_pop() def inspect_master_grad_data(self): """ When running with :class:`FP16_Optimizer`, ``.grad`` attributes of a model's fp16 leaves should not be regarded as truthful, because they might be scaled. After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was encountered, the fp32 master params' ``.grad`` attributes will contain valid gradients properly divided by the loss scale. However, because :class:`FP16_Optimizer` flattens some parameters, accessing them may be nonintuitive. :attr:`inspect_master_grad_data` allows those gradients to be viewed with shapes corresponding to their associated model leaves. Returns: List of lists (one list for each parameter group). The list for each parameter group is a list of the ``.grad.data`` attributes of the fp32 master params belonging to that group. """ if self.overflow: print("Warning: calling FP16_Optimizer.inspect_master_grad_data while in an overflow state. " "Gradients are currently invalid (may be inf, nan, or stale). Returning None.") return None else: # The optimizer owns only references to master params. master_grads_data = [] for param_group in self.optimizer.param_groups: master_grads_this_group = [] for param in param_group['params']: if param.grad is not None: master_grads_this_group.append(param.grad.data) else: master_grads_this_group.append(None) master_grads_data.append(master_grads_this_group) return master_grads_data # Promote loss scale so it can be retrieved or set via "fp16_optimizer_instance.loss_scale" def _get_loss_scale(self): return self.loss_scaler.loss_scale() def _set_loss_scale(self, value): self.loss_scaler._loss_scale = value loss_scale = property(_get_loss_scale, _set_loss_scale) # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups) ================================================ FILE: KoSentenceT5/apex/fp16_utils/fp16util.py ================================================ import torch import torch.nn as nn from torch.autograd import Variable from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors class tofp16(nn.Module): """ Utility module that implements:: def forward(self, input): return input.half() """ def __init__(self): super(tofp16, self).__init__() def forward(self, input): return input.half() def BN_convert_float(module): """ Utility function for network_to_half(). Retained for legacy purposes. """ if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: module.float() for child in module.children(): BN_convert_float(child) return module def network_to_half(network): """ Convert model to half precision in a batchnorm-safe way. Retained for legacy purposes. It is recommended to use FP16Model. """ return nn.Sequential(tofp16(), BN_convert_float(network.half())) def convert_module(module, dtype): """ Converts a module's immediate parameters and buffers to dtype. """ for param in module.parameters(recurse=False): if param is not None: if param.data.dtype.is_floating_point: param.data = param.data.to(dtype=dtype) if param._grad is not None and param._grad.data.dtype.is_floating_point: param._grad.data = param._grad.data.to(dtype=dtype) for buf in module.buffers(recurse=False): if buf is not None and buf.data.dtype.is_floating_point: buf.data = buf.data.to(dtype=dtype) def convert_network(network, dtype): """ Converts a network's parameters and buffers to dtype. """ for module in network.modules(): if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: continue convert_module(module, dtype) if isinstance(module, torch.nn.RNNBase) or isinstance(module, torch.nn.modules.rnn.RNNBase): module.flatten_parameters() return network class FP16Model(nn.Module): """ Convert model to half precision in a batchnorm-safe way. """ def __init__(self, network): super(FP16Model, self).__init__() self.network = convert_network(network, dtype=torch.half) def forward(self, *inputs): inputs = tuple(t.half() for t in inputs) return self.network(*inputs) def backwards_debug_hook(grad): raise RuntimeError("master_params recieved a gradient in the backward pass!") def prep_param_lists(model, flat_master=False): """ Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a performance optimization. Returns: A tuple (``model_params``, ``master_params``). ``model_params`` is a list of the model's parameters for later use with :func:`model_grads_to_master_grads` and :func:`master_params_to_model_params`. ``master_params`` is a list of FP32 master gradients. If ``flat_master=True``, ``master_params`` will be a list with one element. Example:: model_params, master_params = prep_param_lists(model) .. warning:: Currently, if ``flat_master=True``, all the model's parameters must be the same type. If the model has parameters of different types, use ``flat_master=False``, or use :class:`FP16_Optimizer`. .. _`Training Neural Networks with Mixed Precision: Real Examples`: http://on-demand.gputechconf.com/gtc/2018/video/S81012/ """ model_params = [param for param in model.parameters() if param.requires_grad] if flat_master: # Give the user some more useful error messages try: # flatten_dense_tensors returns a contiguous flat array. # http://pytorch.org/docs/master/_modules/torch/_utils.html master_params = _flatten_dense_tensors([param.data for param in model_params]).float() except: print("Error in prep_param_lists: model may contain a mixture of parameters " "of different types. Use flat_master=False, or use F16_Optimizer.") raise master_params = torch.nn.Parameter(master_params) master_params.requires_grad = True # master_params.register_hook(backwards_debug_hook) if master_params.grad is None: master_params.grad = master_params.new(*master_params.size()) return model_params, [master_params] else: master_params = [param.clone().float().detach() for param in model_params] for param in master_params: param.requires_grad = True return model_params, master_params def model_grads_to_master_grads(model_params, master_params, flat_master=False): """ Copy model gradients to master gradients. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`model_grads_to_master_grads`. """ if flat_master: # The flattening may incur one more deep copy than is necessary. master_params[0].grad.data.copy_( _flatten_dense_tensors([p.grad.data for p in model_params])) else: for model, master in zip(model_params, master_params): if model.grad is not None: if master.grad is None: master.grad = Variable(master.data.new(*master.data.size())) master.grad.data.copy_(model.grad.data) else: master.grad = None def master_params_to_model_params(model_params, master_params, flat_master=False): """ Copy master parameters to model parameters. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`master_params_to_model_params`. """ if flat_master: for model, master in zip(model_params, _unflatten_dense_tensors(master_params[0].data, model_params)): model.data.copy_(master) else: for model, master in zip(model_params, master_params): model.data.copy_(master.data) # Backward compatibility fixes def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 0 and TORCH_MINOR <= 4: clip_grad_norm = torch.nn.utils.clip_grad_norm else: clip_grad_norm = torch.nn.utils.clip_grad_norm_ ================================================ FILE: KoSentenceT5/apex/fp16_utils/loss_scaler.py ================================================ import torch # item() is a recent addition, so this helps with backward compatibility. def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] class LossScaler: """ Class that manages a static loss scale. This class is intended to interact with :class:`FP16_Optimizer`, and should not be directly manipulated by the user. Use of :class:`LossScaler` is enabled via the ``static_loss_scale`` argument to :class:`FP16_Optimizer`'s constructor. Args: scale (float, optional, default=1.0): The loss scale. """ def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) class DynamicLossScaler: """ Class that manages dynamic loss scaling. It is recommended to use :class:`DynamicLossScaler` indirectly, by supplying ``dynamic_loss_scale=True`` to the constructor of :class:`FP16_Optimizer`. However, it's important to understand how :class:`DynamicLossScaler` operates, because the default options can be changed using the the ``dynamic_loss_args`` argument to :class:`FP16_Optimizer`'s constructor. Loss scaling is designed to combat the problem of underflowing gradients encountered at long times when training fp16 networks. Dynamic loss scaling begins by attempting a very high loss scale. Ironically, this may result in OVERflowing gradients. If overflowing gradients are encountered, :class:`DynamicLossScaler` informs :class:`FP16_Optimizer` that an overflow has occurred. :class:`FP16_Optimizer` then skips the update step for this particular iteration/minibatch, and :class:`DynamicLossScaler` adjusts the loss scale to a lower value. If a certain number of iterations occur without overflowing gradients detected, :class:`DynamicLossScaler` increases the loss scale once more. In this way :class:`DynamicLossScaler` attempts to "ride the edge" of always using the highest loss scale possible without incurring overflow. Args: init_scale (float, optional, default=2**32): Initial loss scale attempted by :class:`DynamicLossScaler.` scale_factor (float, optional, default=2.0): Factor used when adjusting the loss scale. If an overflow is encountered, the loss scale is readjusted to loss scale/``scale_factor``. If ``scale_window`` consecutive iterations take place without an overflow, the loss scale is readjusted to loss_scale*``scale_factor``. scale_window (int, optional, default=1000): Number of consecutive iterations without an overflow to wait before increasing the loss scale. """ def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window # `params` is a list / generator of torch.Variable def has_overflow(self, params): for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False # `x` is a torch.Tensor def _has_inf_or_nan(x): try: # if x is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as x # (which is true for some recent version of pytorch). cpu_sum = float(x.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # cpu_sum = float(x.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False # `overflow` is boolean indicating whether the gradient overflowed def update_scale(self, overflow): if overflow: # self.cur_scale /= self.scale_factor self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) ############################################################## # Example usage below here -- assuming it's in a separate file ############################################################## """ TO-DO separate out into an example. if __name__ == "__main__": import torch from torch.autograd import Variable from dynamic_loss_scaler import DynamicLossScaler # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables. x = Variable(torch.randn(N, D_in), requires_grad=False) y = Variable(torch.randn(N, D_out), requires_grad=False) w1 = Variable(torch.randn(D_in, H), requires_grad=True) w2 = Variable(torch.randn(H, D_out), requires_grad=True) parameters = [w1, w2] learning_rate = 1e-6 optimizer = torch.optim.SGD(parameters, lr=learning_rate) loss_scaler = DynamicLossScaler() for t in range(500): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale)) print('Iter {} scaled loss: {}'.format(t, loss.data[0])) print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale)) # Run backprop optimizer.zero_grad() loss.backward() # Check for overflow has_overflow = DynamicLossScaler.has_overflow(parameters) # If no overflow, unscale grad and update as usual if not has_overflow: for param in parameters: param.grad.data.mul_(1. / loss_scaler.loss_scale) optimizer.step() # Otherwise, don't do anything -- ie, skip iteration else: print('OVERFLOW!') # Update loss scale for next iteration loss_scaler.update_scale(has_overflow) """ ================================================ FILE: KoSentenceT5/apex/mlp/__init__.py ================================================ from .mlp import * ================================================ FILE: KoSentenceT5/apex/mlp/mlp.py ================================================ from copy import copy import math import torch from torch import nn import mlp_cuda from .. import amp class MlpFunction(torch.autograd.Function): @staticmethod def forward(ctx, bias, activation, *args): output = mlp_cuda.forward(bias, activation, args) ctx.save_for_backward(*args) ctx.outputs = output ctx.bias = bias ctx.activation = activation return output[0] @staticmethod def backward(ctx, grad_o): grads = mlp_cuda.backward(ctx.bias, ctx.activation, grad_o, ctx.outputs, ctx.saved_tensors) del ctx.outputs return (None, None, *grads) mlp_function = amp.half_function(MlpFunction.apply) class MLP(torch.nn.Module): """Launch MLP in C++ Args: mlp_sizes (list of int): MLP sizes. Example: [1024,1024,1024] will create 2 MLP layers with shape 1024x1024 bias (bool): Default True: relu (bool): Default True """ def __init__(self, mlp_sizes, bias=True, activation='relu'): super(MLP, self).__init__() self.num_layers = len(mlp_sizes) - 1 self.mlp_sizes = copy(mlp_sizes) self.bias = 1 if bias else 0 if activation is 'none': self.activation = 0 elif activation is 'relu': self.activation = 1 elif activation is 'sigmoid': self.activation = 2 else: raise TypeError("activation must be relu or none.") self.weights = [] self.biases = [] for i in range(self.num_layers): w = torch.nn.Parameter(torch.empty(mlp_sizes[i+1], mlp_sizes[i])) self.weights.append(w) name = 'weight_{}'.format(i) setattr(self, name, w) if self.bias: b = torch.nn.Parameter(torch.empty(mlp_sizes[i+1])) self.biases.append(b) name = 'bias_{}'.format(i) setattr(self, name, b) self.reset_parameters() def reset_parameters(self): for weight in self.weights: dimsum = weight.size(0) + weight.size(1) std = math.sqrt(2. / float(dimsum)) nn.init.normal_(weight, 0., std) if self.bias: for bias in self.biases: std = math.sqrt(1. / float(bias.size(0))) nn.init.normal_(bias, 0., std) def forward(self, input): return mlp_function(self.bias, self.activation, input, *self.weights, *self.biases) def extra_repr(self): s = F"MLP sizes: {self.mlp_sizes}, Bias={self.bias}, activation={self.activation}" return s ================================================ FILE: KoSentenceT5/apex/multi_tensor_apply/__init__.py ================================================ from .multi_tensor_apply import MultiTensorApply multi_tensor_applier = MultiTensorApply(2048*32) ================================================ FILE: KoSentenceT5/apex/multi_tensor_apply/multi_tensor_apply.py ================================================ import torch class MultiTensorApply(object): available = False warned = False def __init__(self, chunk_size): try: import amp_C MultiTensorApply.available = True self.chunk_size = chunk_size except ImportError as err: MultiTensorApply.available = False MultiTensorApply.import_err = err def check_avail(self): if MultiTensorApply.available == False: raise RuntimeError( "Attempted to call MultiTensorApply method, but MultiTensorApply " "is not available, possibly because Apex was installed without " "--cpp_ext --cuda_ext. Original import error message:", MultiTensorApply.import_err) def __call__(self, op, noop_flag_buffer, tensor_lists, *args): self.check_avail() return op(self.chunk_size, noop_flag_buffer, tensor_lists, *args) ================================================ FILE: KoSentenceT5/apex/normalization/__init__.py ================================================ from .fused_layer_norm import FusedLayerNorm ================================================ FILE: KoSentenceT5/apex/normalization/fused_layer_norm.py ================================================ import math import torch import numbers from torch.nn.parameter import Parameter from torch.nn import init from torch.nn import functional as F import importlib global fused_layer_norm_cuda fused_layer_norm_cuda = None class FusedLayerNormAffineFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, weight, bias, normalized_shape, eps): global fused_layer_norm_cuda if fused_layer_norm_cuda is None: fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") ctx.normalized_shape = normalized_shape ctx.eps = eps input_ = input.contiguous() weight_ = weight.contiguous() bias_ = bias.contiguous() output, mean, invvar = fused_layer_norm_cuda.forward_affine( input_, ctx.normalized_shape, weight_, bias_, ctx.eps) ctx.save_for_backward(input_, weight_, bias_, mean, invvar) return output @staticmethod def backward(ctx, grad_output): input_, weight_, bias_, mean, invvar = ctx.saved_tensors grad_input = grad_weight = grad_bias = None grad_input, grad_weight, grad_bias = fused_layer_norm_cuda.backward_affine( grad_output.contiguous(), mean, invvar, input_, ctx.normalized_shape, weight_, bias_, ctx.eps) return grad_input, grad_weight, grad_bias, None, None class FusedLayerNormFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, normalized_shape, eps): global fused_layer_norm_cuda if fused_layer_norm_cuda is None: fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") ctx.normalized_shape = normalized_shape ctx.eps = eps input_ = input.contiguous() output, mean, invvar = fused_layer_norm_cuda.forward( input_, ctx.normalized_shape, ctx.eps) ctx.save_for_backward(input_, mean, invvar) return output @staticmethod def backward(ctx, grad_output): input_, mean, invvar = ctx.saved_tensors grad_input = None grad_input = fused_layer_norm_cuda.backward( grad_output.contiguous(), mean, invvar, input_, ctx.normalized_shape, ctx.eps) return grad_input, None, None def fused_layer_norm_affine(input, normalized_shape, weight, bias, eps=1e-6): return FusedLayerNormAffineFunction.apply(input, weight, bias, normalized_shape, eps) def fused_layer_norm(input, normalized_shape, eps=1e-6): return FusedLayerNormFunction.apply(input, normalized_shape, eps) class FusedLayerNorm(torch.nn.Module): r"""Applies Layer Normalization over a mini-batch of inputs as described in the paper `Layer Normalization`_ . Currently only runs on cuda() tensors. .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated separately over the last certain number dimensions which have to be of the shape specified by :attr:`normalized_shape`. :math:`\gamma` and :math:`\beta` are learnable affine transform parameters of :attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``. .. note:: Unlike Batch Normalization and Instance Normalization, which applies scalar scale and bias for each entire channel/plane with the :attr:`affine` option, Layer Normalization applies per-element scale and bias with :attr:`elementwise_affine`. This layer uses statistics computed from input data in both training and evaluation modes. Args: normalized_shape (int or list or torch.Size): input shape from an expected input of size .. math:: [* \times \text{normalized}\_\text{shape}[0] \times \text{normalized}\_\text{shape}[1] \times \ldots \times \text{normalized}\_\text{shape}[-1]] If a single integer is used, it is treated as a singleton list, and this module will normalize over the last dimension which is expected to be of that specific size. eps: a value added to the denominator for numerical stability. Default: 1e-5 elementwise_affine: a boolean value that when set to ``True``, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases). Default: ``True``. Shape: - Input: :math:`(N, *)` - Output: :math:`(N, *)` (same shape as input) Examples:: >>> input = torch.randn(20, 5, 10, 10) >>> # With Learnable Parameters >>> m = apex.normalization.FusedLayerNorm(input.size()[1:]) >>> # Without Learnable Parameters >>> m = apex.normalization.FusedLayerNorm(input.size()[1:], elementwise_affine=False) >>> # Normalize over last two dimensions >>> m = apex.normalization.FusedLayerNorm([10, 10]) >>> # Normalize over last dimension of size 10 >>> m = apex.normalization.FusedLayerNorm(10) >>> # Activating the module >>> output = m(input) .. _`Layer Normalization`: https://arxiv.org/abs/1607.06450 """ def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): super(FusedLayerNorm, self).__init__() global fused_layer_norm_cuda fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") if isinstance(normalized_shape, numbers.Integral): normalized_shape = (normalized_shape,) self.normalized_shape = torch.Size(normalized_shape) self.eps = eps self.elementwise_affine = elementwise_affine if self.elementwise_affine: self.weight = Parameter(torch.Tensor(*normalized_shape)) self.bias = Parameter(torch.Tensor(*normalized_shape)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): if self.elementwise_affine: init.ones_(self.weight) init.zeros_(self.bias) def forward(self, input): if not input.is_cuda: return F.layer_norm( input, self.normalized_shape, self.weight, self.bias, self.eps) if self.elementwise_affine: return FusedLayerNormAffineFunction.apply( input, self.weight, self.bias, self.normalized_shape,self.eps) else: return FusedLayerNormFunction.apply(input, self.normalized_shape, self.eps) def extra_repr(self): return '{normalized_shape}, eps={eps}, ' \ 'elementwise_affine={elementwise_affine}'.format(**self.__dict__) ================================================ FILE: KoSentenceT5/apex/optimizers/__init__.py ================================================ from .fused_sgd import FusedSGD from .fused_adam import FusedAdam from .fused_novograd import FusedNovoGrad from .fused_lamb import FusedLAMB from .fused_adagrad import FusedAdagrad ================================================ FILE: KoSentenceT5/apex/optimizers/fused_adagrad.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedAdagrad(torch.optim.Optimizer): """Implements Adagrad algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused Adagrad implements 2 fusions. * Fusion of the Adagrad update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedAdagrad`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedAdagrad(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedAdagrad` may be used with or without Amp. If you wish to use :class:`FusedAdagrad` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedAdagrad(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. It has been proposed in `Adaptive Subgradient Methods for Online Learning and Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-2) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-10) adagrad_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay (also known as AdamW) (default: False) .. _Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: http://jmlr.org/papers/v12/duchi11a.html """ def __init__(self, params, lr=1e-2, eps=1e-10, weight_decay=0., set_grad_none=True, adagrad_w_mode=False): defaults = dict(lr=lr, eps=eps, weight_decay=weight_decay) super(FusedAdagrad, self).__init__(params, defaults) self.adagrad_w_mode = 1 if adagrad_w_mode else 0 self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_adagrad = amp_C.multi_tensor_adagrad else: raise RuntimeError('apex.optimizers.FusedAdagrad requires cuda extensions') def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedAdagrad, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: # create lists for multi-tensor apply g_16, p_16, h_16 = [], [], [] g_32, p_32, h_32 = [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedAdagrad does not support sparse gradients') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['sum'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) h_16.append(state['sum']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) h_32.append(state['sum']) else: raise RuntimeError('FusedAdagrad only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_adagrad, self._dummy_overflow_buf, [g_16, p_16, h_16], group['lr'], group['eps'], self.adagrad_w_mode, group['weight_decay']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_adagrad, self._dummy_overflow_buf, [g_32, p_32, h_32], group['lr'], group['eps'], self.adagrad_w_mode, group['weight_decay']) return loss ================================================ FILE: KoSentenceT5/apex/optimizers/fused_adam.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused Adam implements 2 fusions. * Fusion of the Adam update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedAdam` may be used as a drop-in replacement for ``torch.optim.AdamW``, or ``torch.optim.Adam`` with ``adam_w_mode=False``:: opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedAdam` may be used with or without Amp. If you wish to use :class:`FusedAdam` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. .. warning:: A previous version of :class:`FusedAdam` allowed a number of additional arguments to ``step``. These additional arguments are now deprecated and unnecessary. Adam was been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) .. _Adam - A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, adam_w_mode=True, weight_decay=0., amsgrad=False, set_grad_none=True): if amsgrad: raise RuntimeError('FusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay) super(FusedAdam, self).__init__(params, defaults) self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_adam = amp_C.multi_tensor_adam else: raise RuntimeError('apex.optimizers.FusedAdam requires cuda extensions') def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedAdam, self).zero_grad() def step(self, closure=None, grads=None, output_params=None, scale=None, grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes. """ if any(p is not None for p in [grads, output_params, scale, grad_norms]): raise RuntimeError('FusedAdam has been updated. Simply initialize it identically to torch.optim.Adam, and call step() with no arguments.') loss = None if closure is not None: loss = closure() for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedAdam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedAdam only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_adam, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], self.adam_w_mode, bias_correction, group['weight_decay']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_adam, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], self.adam_w_mode, bias_correction, group['weight_decay']) return loss ================================================ FILE: KoSentenceT5/apex/optimizers/fused_lamb.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) use_nvlamb (boolean, optional): Apply adaptive learning rate to 0.0 weight decay parameter (default: False) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01, amsgrad=False, adam_w_mode=True, grad_averaging=True, set_grad_none=True, max_grad_norm=1.0, use_nvlamb=False): if amsgrad: raise RuntimeError('FusedLAMB does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(FusedLAMB, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm # Skip buffer self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_lamb = amp_C.multi_tensor_lamb else: raise RuntimeError('apex.optimizers.FusedLAMB requires cuda extensions') self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none self.use_nvlamb = use_nvlamb def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedLAMB, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() # create separate grad lists for fp32 and fp16 params g_all_32, g_all_16 = [], [] for group in self.param_groups: for p in group['params']: if p.grad is None: continue if p.dtype == torch.float32: g_all_32.append(p.grad.data) elif p.dtype == torch.float16: g_all_16.append(p.grad.data) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') device = self.param_groups[0]["params"][0].device g_norm_32, g_norm_16 = torch.zeros(1, device=device), torch.zeros(1, device=device) # compute grad norm for two lists if len(g_all_32) > 0: g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_32], False)[0] if len(g_all_16) > 0: g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_16], False)[0] # blend two grad norms to get global grad norm global_grad_norm = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [[g_norm_32, g_norm_16]], False)[0] max_grad_norm = self.defaults['max_grad_norm'] for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedLAMB does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm, self.use_nvlamb) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm, self.use_nvlamb) return loss ================================================ FILE: KoSentenceT5/apex/optimizers/fused_novograd.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedNovoGrad(torch.optim.Optimizer): """Implements NovoGrad algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused NovoGrad implements 2 fusions. * Fusion of the NovoGrad update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedNovoGrad`'s usage is identical to any Pytorch optimizer:: opt = apex.optimizers.FusedNovoGrad(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedNovoGrad` may be used with or without Amp. If you wish to use :class:`FusedNovoGrad` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedNovoGrad(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. It has been proposed in `Jasper: An End-to-End Convolutional Neural Acoustic Model`_. More info: https://nvidia.github.io/OpenSeq2Seq/html/optimizers.html#novograd Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) reg_inside_moment (bool, optional): whether do regularization (norm and L2) in momentum calculation. True for include, False for not include and only do it on update term. (default: False) grad_averaging (bool, optional): whether apply (1-beta1) to grad when calculating running averages of gradient. (default: True) norm_type (int, optional): which norm to calculate for each layer. 2 for L2 norm, and 0 for infinite norm. These 2 are only supported type now. (default: 2) init_zero (bool, optional): whether init norm with 0 (start averaging on 1st step) or first step norm (start averaging on 2nd step). True for init with 0. (default: False) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) .. _Jasper - An End-to-End Convolutional Neural Acoustic Model: https://arxiv.org/abs/1904.03288 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, weight_decay=0., amsgrad=False, reg_inside_moment=False, grad_averaging=True, norm_type=2, init_zero=False, set_grad_none=True): if amsgrad: raise RuntimeError('FusedNovoGrad does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, norm_type=norm_type, init_zero=init_zero) super(FusedNovoGrad, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C # Skip buffer # Creating the overflow buffer on the same device as the params tensors. self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_novograd = amp_C.multi_tensor_novograd else: raise RuntimeError('apex.optimizers.FusedNovoGrad requires cuda extensions') self.moment_mode = 0 if reg_inside_moment else 1 self.set_grad_none = set_grad_none def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedNovoGrad, self).zero_grad() def load_state_dict(self, state_dict): super(FusedNovoGrad, self).load_state_dict(state_dict) # in case exp_avg_sq is not on the same device as params, move it there for group in self.param_groups: if len(group['params']) > 0: group['exp_avg_sq'][0] = group['exp_avg_sq'][0].to(group['params'][0].device) group['exp_avg_sq'][1] = group['exp_avg_sq'][1].to(group['params'][0].device) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16 = [], [], [] g_32, p_32, m_32 = [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedNovoGrad does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) else: raise RuntimeError('FusedNovoGrad only support fp16 and fp32.') # we store per weight norm as one tensor for one group/precision combination # different from optim.Adam, we store norm here(not ^2) so we can unify calculation for norm types if 'exp_avg_sq' not in group: group['exp_avg_sq'] = [None, None] if group['init_zero']: # Creating the following parameters on the same device as the params tensors. group['exp_avg_sq'][0] = torch.cuda.FloatTensor(len(g_16), device=self.param_groups[0]["params"][0].device).contiguous().fill_(0) group['exp_avg_sq'][1] = torch.cuda.FloatTensor(len(g_32), device=self.param_groups[0]["params"][0].device).contiguous().fill_(0) else: # init with first step norm, so first blend have no effect if group['norm_type'] == 0: v_16 = [torch.max(torch.abs(g.to(torch.float32))).item() for g in g_16] v_32 = [torch.max(torch.abs(g)).item() for g in g_32] elif group['norm_type'] == 2: v_16 = [torch.sum(torch.pow(g.to(torch.float32), 2)).sqrt().item() for g in g_16] v_32 = [torch.sum(torch.pow(g, 2)).sqrt().item() for g in g_32] else: raise RuntimeError('FusedNovoGrad only support l2/inf norm now.') # Creating the following parameters on the same device as the params tensors. group['exp_avg_sq'][0] = torch.cuda.FloatTensor(v_16, device=self.param_groups[0]["params"][0].device) group['exp_avg_sq'][1] = torch.cuda.FloatTensor(v_32, device=self.param_groups[0]["params"][0].device) else: assert(len(g_16) == group['exp_avg_sq'][0].numel()) assert(len(g_32) == group['exp_avg_sq'][1].numel()) if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_novograd, self._dummy_overflow_buf, [g_16, p_16, m_16], group['exp_avg_sq'][0], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.moment_mode, group['norm_type']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_novograd, self._dummy_overflow_buf, [g_32, p_32, m_32], group['exp_avg_sq'][1], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.moment_mode, group['norm_type']) return loss ================================================ FILE: KoSentenceT5/apex/optimizers/fused_sgd.py ================================================ import torch from torch.optim.optimizer import Optimizer, required from apex.multi_tensor_apply import multi_tensor_applier class FusedSGD(Optimizer): r"""Implements stochastic gradient descent (optionally with momentum). Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused SGD implements 2 fusions. * Fusion of the SGD update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedSGD` may be used as a drop-in replacement for ``torch.optim.SGD``:: opt = apex.optimizers.FusedSGD(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedSGD` may be used with or without Amp. If you wish to use :class:`FusedSGD` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedSGD(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. Nesterov momentum is based on the formula from `On the importance of initialization and momentum in deep learning`__. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float): learning rate momentum (float, optional): momentum factor (default: 0) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) dampening (float, optional): dampening for momentum (default: 0) nesterov (bool, optional): enables Nesterov momentum (default: False) Example: >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) >>> optimizer.zero_grad() >>> loss_fn(model(input), target).backward() >>> optimizer.step() __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf .. note:: The implementation of SGD with Momentum/Nesterov subtly differs from Sutskever et. al. and implementations in some other frameworks. Considering the specific case of Momentum, the update can be written as .. math:: v = \rho * v + g \\ p = p - lr * v where p, g, v and :math:`\rho` denote the parameters, gradient, velocity, and momentum respectively. This is in contrast to Sutskever et. al. and other frameworks which employ an update of the form .. math:: v = \rho * v + lr * g \\ p = p - v The Nesterov version is analogously modified. """ def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, wd_after_momentum=False, materialize_master_grads=True, set_grad_none=False): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super(FusedSGD, self).__init__(params, defaults) self.wd_after_momentum = wd_after_momentum self.materialize_master_grads = materialize_master_grads self.most_recent_scale = 1.0 self.scale_set_by_backward = False self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_sgd = amp_C.multi_tensor_sgd else: raise RuntimeError('apex.optimizers.FusedSGD requires cuda extensions') def __setstate__(self, state): super(FusedSGD, self).__setstate__(state) for group in self.param_groups: group.setdefault('nesterov', False) def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedSGD, self).zero_grad() def get_momentums(self, params): momentums = [] first_run = True for p in params: param_state = self.state[p] # torch.optim.SGD initializes momentum in the main loop, we have # to do it here, and track whether or not we've done so, so that # momentum application can be skipped in the main kernel. if 'momentum_buffer' not in param_state: first_run = True buf = param_state['momentum_buffer'] = torch.zeros_like(p.data) momentums.append(buf) else: first_run = False momentums.append(param_state['momentum_buffer']) return momentums, first_run def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() explicit_master_params = (hasattr(self, "_amp_stash") and hasattr(self._amp_stash, "fp32_from_fp16_groups")) for gid, group in enumerate(self.param_groups): weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] # For each group, there are 3 possible combinations we need to consider: # grad_type, param_to_update_type, momentum_type, requires_fp16_model_copy # 1. fp16, fp16, fp16, No # 2. fp32, fp32, fp32, No # 3. fp16, fp32, fp32, Yes first_runs = [True, True] # I think a bit of code divergence in exchange for naming clarity is worthwhile if explicit_master_params: stash = self._amp_stash fp32_params = [p for p in stash.fp32_from_fp32_groups[gid] if p.grad is not None] fp32_grads = [p.grad for p in stash.fp32_from_fp32_groups[gid] if p.grad is not None] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) if self.materialize_master_grads: fp16_model_params = [p for i, p in enumerate( stash.fp16_groups[gid]) if stash.fp32_from_fp16_groups[gid][i].grad is not None] fp32_from_fp16_grads = [p.grad for p in stash.fp32_from_fp16_groups[gid] if p.grad is not None] fp32_from_fp16_params = [p for p in stash.fp32_from_fp16_groups[gid] if p.grad is not None] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_set = [fp32_from_fp16_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_model_params] else: fp16_model_params = [p for p in stash.fp16_groups[gid] if p.grad is not None] fp16_model_grads = [p.grad for p in stash.fp16_groups[gid] if p.grad is not None] fp32_from_fp16_params = [p for i, p in enumerate( stash.fp32_from_fp16_groups[gid]) if stash.fp16_groups[gid][i].grad is not None] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_set = [fp16_model_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_model_params] launch_sets= [fp16_set, [fp32_grads, fp32_params, fp32_momentums]] else: fp16_params = [p for p in group['params'] if (p.dtype == torch.float16 and p.grad is not None)] fp16_grads = [p.grad for p in group['params'] if (p.dtype == torch.float16 and p.grad is not None)] fp16_momentums, first_runs[0] = self.get_momentums(fp16_params) fp32_params = [p for p in group['params'] if (p.dtype == torch.float32 and p.grad is not None)] fp32_grads = [p.grad for p in group['params'] if (p.dtype == torch.float32 and p.grad is not None)] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) launch_sets = [[fp16_grads, fp16_params, fp16_momentums], [fp32_grads, fp32_params, fp32_momentums]] for s, (launch_set, first_run) in enumerate(zip(launch_sets, first_runs)): assert len(launch_set[0]) == len(launch_set[1]) assert len(launch_set[0]) == len(launch_set[2]) if len(launch_set[0]) > 0: multi_tensor_applier( self.multi_tensor_sgd, self._dummy_overflow_buf, launch_set, weight_decay, momentum, dampening, group['lr'], nesterov, first_run, self.wd_after_momentum, 1.0/self.most_recent_scale) self.most_recent_scale = 1.0 self.scale_set_by_backward = False return loss ================================================ FILE: KoSentenceT5/apex/parallel/LARC.py ================================================ import torch from torch import nn from torch.nn.parameter import Parameter class LARC(object): """ :class:`LARC` is a pytorch implementation of both the scaling and clipping variants of LARC, in which the ratio between gradient and parameter magnitudes is used to calculate an adaptive local learning rate for each individual parameter. The algorithm is designed to improve convergence of large batch training. See https://arxiv.org/abs/1708.03888 for calculation of the local learning rate. In practice it modifies the gradients of parameters as a proxy for modifying the learning rate of the parameters. This design allows it to be used as a wrapper around any torch.optim Optimizer. ``` model = ... optim = torch.optim.Adam(model.parameters(), lr=...) optim = LARC(optim) ``` It can even be used in conjunction with apex.fp16_utils.FP16_optimizer. ``` model = ... optim = torch.optim.Adam(model.parameters(), lr=...) optim = LARC(optim) optim = apex.fp16_utils.FP16_Optimizer(optim) ``` Args: optimizer: Pytorch optimizer to wrap and modify learning rate for. trust_coefficient: Trust coefficient for calculating the lr. See https://arxiv.org/abs/1708.03888 clip: Decides between clipping or scaling mode of LARC. If `clip=True` the learning rate is set to `min(optimizer_lr, local_lr)` for each parameter. If `clip=False` the learning rate is set to `local_lr*optimizer_lr`. eps: epsilon kludge to help with numerical stability while calculating adaptive_lr """ def __init__(self, optimizer, trust_coefficient=0.02, clip=True, eps=1e-8): self.optim = optimizer self.trust_coefficient = trust_coefficient self.eps = eps self.clip = clip def __getstate__(self): return self.optim.__getstate__() def __setstate__(self, state): self.optim.__setstate__(state) @property def state(self): return self.optim.state def __repr__(self): return self.optim.__repr__() @property def param_groups(self): return self.optim.param_groups @param_groups.setter def param_groups(self, value): self.optim.param_groups = value def state_dict(self): return self.optim.state_dict() def load_state_dict(self, state_dict): self.optim.load_state_dict(state_dict) def zero_grad(self): self.optim.zero_grad() def add_param_group(self, param_group): self.optim.add_param_group( param_group) def step(self): with torch.no_grad(): weight_decays = [] for group in self.optim.param_groups: # absorb weight decay control from optimizer weight_decay = group['weight_decay'] if 'weight_decay' in group else 0 weight_decays.append(weight_decay) group['weight_decay'] = 0 for p in group['params']: if p.grad is None: continue param_norm = torch.norm(p.data) grad_norm = torch.norm(p.grad.data) if param_norm != 0 and grad_norm != 0: # calculate adaptive lr + weight decay adaptive_lr = self.trust_coefficient * (param_norm) / (grad_norm + param_norm * weight_decay + self.eps) # clip learning rate for LARC if self.clip: # calculation of adaptive_lr so that when multiplied by lr it equals `min(adaptive_lr, lr)` adaptive_lr = min(adaptive_lr/group['lr'], 1) p.grad.data += weight_decay * p.data p.grad.data *= adaptive_lr self.optim.step() # return weight decay control to optimizer for i, group in enumerate(self.optim.param_groups): group['weight_decay'] = weight_decays[i] ================================================ FILE: KoSentenceT5/apex/parallel/README.md ================================================ ## Distributed Data Parallel distributed.py contains the source code for `apex.parallel.DistributedDataParallel`, a module wrapper that enables multi-process multi-GPU data parallel training optimized for NVIDIA's NCCL communication library. `apex.parallel.DistributedDataParallel` achieves high performance by overlapping communication with computation in the backward pass and bucketing smaller transfers to reduce the total number of transfers required. multiproc.py contains the source code for `apex.parallel.multiproc`, a launch utility that places one process on each of the node's available GPUs. #### [API Documentation](https://nvidia.github.io/apex/parallel.html) #### [Example/Walkthrough](https://github.com/NVIDIA/apex/tree/master/examples/distributed) #### [Imagenet example with Mixed Precision](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) #### [Simple example with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/FP16_Optimizer_simple/distributed_apex) ### Synchronized Batch Normalization `apex.parallel.SyncBatchNorm` has similar APIs as with `torch.nn.BatchNorm*N*d`. It reduces stats on the first (channel) dimension of the Tensor and accepts arbitrary spatial dimensions. #### Installation Apex provides two sync BN implementation: 1. There is the Python-only implementation, which is the default implementation when install with `python setup.py install`. It uses PyTorch primitive operations and distributed communication package from `torch.distributed`. - _Python-only implementation requires input tensor to be of same data type as layer_ 2. We also provide implementation with kernels through CUDA/C++ extension with improved performance. We are experimenting with Welford and Kahan for reduction hoping to get better accuracy. To use the kernel implementation, user need to install Apex with CUDA extension enabled `python setup.py install --cuda_ext`. - _Custom kernel implementation supports fp16 input with fp32 layer as cudnn. This is required to run imagenet example in fp16._ - _Currently kernel implementation only supports GPU._ #### HowTo 1. User could use `apex.parallel.SyncBatchNorm` by building their module with the layer explicitly. ``` import apex input_t = torch.randn(3, 5, 20).cuda() sbn = apex.parallel.SyncBatchNorm(5).cuda() output_t = sbn(input) ``` 2. User could also take a constructed `torch.nn.Model` and replace all its `torch.nn.BatchNorm*N*d` modules with `apex.parallel.SyncBatchNorm` through utility function `apex.parallel.convert_syncbn_model`. ``` # model is an instance of torch.nn.Module import apex sync_bn_model = apex.parallel.convert_syncbn_model(model) ``` ================================================ FILE: KoSentenceT5/apex/parallel/__init__.py ================================================ import torch if hasattr(torch.distributed, 'ReduceOp'): ReduceOp = torch.distributed.ReduceOp elif hasattr(torch.distributed, 'reduce_op'): ReduceOp = torch.distributed.reduce_op else: ReduceOp = torch.distributed.deprecated.reduce_op from .distributed import DistributedDataParallel, Reducer # This is tricky because I'd like SyncBatchNorm to be exposed the same way # for both the cuda-enabled and python-fallback versions, and I don't want # to suppress the error information. try: import syncbn from .optimized_sync_batchnorm import SyncBatchNorm except ImportError as err: from .sync_batchnorm import SyncBatchNorm SyncBatchNorm.syncbn_import_error = err def convert_syncbn_model(module, process_group=None, channel_last=False): ''' Recursively traverse module and its children to replace all instances of ``torch.nn.modules.batchnorm._BatchNorm`` with :class:`apex.parallel.SyncBatchNorm`. All ``torch.nn.BatchNorm*N*d`` wrap around ``torch.nn.modules.batchnorm._BatchNorm``, so this function lets you easily switch to use sync BN. Args: module (torch.nn.Module): input module Example:: >>> # model is an instance of torch.nn.Module >>> import apex >>> sync_bn_model = apex.parallel.convert_syncbn_model(model) ''' mod = module if isinstance(module, torch.nn.modules.instancenorm._InstanceNorm): return module if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): mod = SyncBatchNorm(module.num_features, module.eps, module.momentum, module.affine, module.track_running_stats, process_group, channel_last=channel_last) mod.running_mean = module.running_mean mod.running_var = module.running_var mod.num_batches_tracked = module.num_batches_tracked if module.affine: mod.weight.data = module.weight.data.clone().detach() mod.bias.data = module.bias.data.clone().detach() for name, child in module.named_children(): mod.add_module(name, convert_syncbn_model(child, process_group=process_group, channel_last=channel_last)) # TODO(jie) should I delete model explicitly? del module return mod def create_syncbn_process_group(group_size): ''' Creates process groups to be used for syncbn of a give ``group_size`` and returns process group that current GPU participates in. ``group_size`` must divide the total number of GPUs (world_size). ``group_size`` of 0 would be considered as =world_size. In this case ``None`` will be returned. ``group_size`` of 1 would be equivalent to using non-sync bn, but will still carry the overhead. Args: group_size (int): number of GPU's to collaborate for sync bn Example:: >>> # model is an instance of torch.nn.Module >>> import apex >>> group = apex.parallel.create_syncbn_process_group(group_size) ''' if group_size==0: return None world_size = torch.distributed.get_world_size() assert(world_size >= group_size) assert(world_size % group_size == 0) group=None for group_num in (range(world_size//group_size)): group_ids = range(group_num*group_size, (group_num+1)*group_size) cur_group = torch.distributed.new_group(ranks=group_ids) if (torch.distributed.get_rank()//group_size == group_num): group = cur_group #can not drop out and return here, every process must go through creation of all subgroups assert(group is not None) return group ================================================ FILE: KoSentenceT5/apex/parallel/distributed.py ================================================ import torch import torch.distributed as dist from torch.nn.modules import Module from torch.autograd import Variable from collections import OrderedDict from itertools import chain import copy import importlib from ..multi_tensor_apply import multi_tensor_applier imported_flatten_impl = False def import_flatten_impl(): global flatten_impl, unflatten_impl, imported_flatten_impl try: import apex_C flatten_impl = apex_C.flatten unflatten_impl = apex_C.unflatten except ImportError: print("Warning: apex was installed without --cpp_ext. Falling back to Python flatten and unflatten.") flatten_impl = torch._utils._flatten_dense_tensors unflatten_impl = torch._utils._unflatten_dense_tensors imported_flatten_impl = True def flatten(bucket): if not imported_flatten_impl: import_flatten_impl() return flatten_impl(bucket) def unflatten(coalesced, bucket): if not imported_flatten_impl: import_flatten_impl() return unflatten_impl(coalesced, bucket) # apply_dist_call requires that tensors in 'bucket' are all the same type. def apply_flat_dist_call(bucket, call, extra_args=None): coalesced = flatten(bucket) if extra_args is not None: call(coalesced, *extra_args) else: call(coalesced) if call is dist.all_reduce: coalesced /= dist.get_world_size() for buf, synced in zip(bucket, unflatten(coalesced, bucket)): buf.copy_(synced) def split_half_float_double(tensors): dtypes = ["torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor"] buckets = [] for i, dtype in enumerate(dtypes): bucket = [t for t in tensors if t.type() == dtype] if bucket: buckets.append(bucket) return buckets def split_by_type(tensors): buckets = OrderedDict() for tensor in tensors: tp = tensor.type() if tp not in buckets: buckets[tp] = [] buckets[tp].append(tensor) return buckets # flat_dist_call organizes 'tensors' by type. def flat_dist_call(tensors, call, extra_args=None): buckets = split_by_type(tensors) for tp in buckets: bucket = buckets[tp] apply_flat_dist_call(bucket, call, extra_args) def extract_tensors(maybe_tensor, tensor_list): if torch.is_tensor(maybe_tensor): tensor_list.append(maybe_tensor) else: try: for item in maybe_tensor: extract_tensors(item, tensor_list) except TypeError: return class Reducer(object): """ :class:`apex.parallel.Reducer` is a simple class that helps allreduce a module's parameters across processes. :class:`Reducer` is intended to give the user additional control: Unlike :class:`DistributedDataParallel`, :class:`Reducer` will not automatically allreduce parameters during ``backward()``. Instead, :class:`Reducer` waits for the user to call ``.reduce()`` manually. This enables, for example, delaying the allreduce to be carried out every several iterations instead of every single iteration. Like :class:`DistributedDataParallel`, :class:`Reducer` averages any tensors it allreduces over the number of participating processes. :class:`Reducer` is designed to work with the upstream launch utility script ``torch.distributed.launch`` with ``--nproc_per_node <= number of gpus per node``. When used with this launcher, :class:`Reducer` assumes 1:1 mapping of processes to GPUs. It also assumes that your script calls ``torch.cuda.set_device(args.rank)`` before creating the model. Args: module_or_grads_list: Either a network definition (module) being run in multi-gpu/distributed mode, or an iterable of gradients to be reduced. If a module is passed in, the Reducer constructor will sync the parameters across processes (broadcasting from rank 0) to make sure they're all initialized with the same values. If a list of gradients (that came from some module) is passed in, the user is responsible for manually syncing that module's parameters at the beginning of training. """ def __init__(self, module_or_grads_list): if isinstance(module_or_grads_list, Module): self.module = module_or_grads_list flat_dist_call([param.data for param in self.module.parameters()], dist.broadcast, (0,) ) else: self.module = None self.grads = [] extract_tensors(module_or_grads_list, self.grads) def reduce(self): if self.module: grads = [param.grad.data for param in self.module.parameters() if param.grad is not None] flat_dist_call(grads, dist.all_reduce) else: flat_dist_call(self.grads, dist.all_reduce) class DistributedDataParallel(Module): """ :class:`apex.parallel.DistributedDataParallel` is a module wrapper that enables easy multiprocess distributed data parallel training, similar to ``torch.nn.parallel.DistributedDataParallel``. Parameters are broadcast across participating processes on initialization, and gradients are allreduced and averaged over processes during ``backward()``. :class:`DistributedDataParallel` is optimized for use with NCCL. It achieves high performance by overlapping communication with computation during ``backward()`` and bucketing smaller gradient transfers to reduce the total number of transfers required. :class:`DistributedDataParallel` is designed to work with the upstream launch utility script ``torch.distributed.launch`` with ``--nproc_per_node <= number of gpus per node``. When used with this launcher, :class:`DistributedDataParallel` assumes 1:1 mapping of processes to GPUs. It also assumes that your script calls ``torch.cuda.set_device(args.rank)`` before creating the model. https://github.com/NVIDIA/apex/tree/master/examples/simple/distributed shows detailed usage. https://github.com/NVIDIA/apex/tree/master/examples/imagenet shows another example that combines :class:`DistributedDataParallel` with mixed precision training. Args: module: Network definition to be run in multi-gpu/distributed mode. message_size (int, default=1e7): Minimum number of elements in a communication bucket. delay_allreduce (bool, default=False): Delay all communication to the end of the backward pass. This disables overlapping communication with computation. allreduce_trigger_params (list, optional, default=None): If supplied, should contain a list of parameters drawn from the model. Allreduces will be kicked off whenever one of these parameters receives its gradient (as opposed to when a bucket of size message_size is full). At the end of backward(), a cleanup allreduce to catch any remaining gradients will also be performed automatically. If allreduce_trigger_params is supplied, the message_size argument will be ignored. allreduce_always_fp32 (bool, default=False): Convert any FP16 gradients to FP32 before allreducing. This can improve stability for widely scaled-out runs. gradient_average (bool, default=True): Option to toggle whether or not DDP averages the allreduced gradients over processes. For proper scaling, the default value of True is recommended. gradient_predivide_factor (float, default=1.0): Allows perfoming the average of gradients over processes partially before and partially after the allreduce. Before allreduce: ``grads.mul_(1.0/gradient_predivide_factor)``. After allreduce: ``grads.mul_(gradient_predivide_factor/world size)``. This can reduce the stress on the dynamic range of FP16 allreduces for widely scaled-out runs. .. warning:: If ``gradient_average=False``, the pre-allreduce division (``grads.mul_(1.0/gradient_predivide_factor)``) will still be applied, but the post-allreduce gradient averaging (``grads.mul_(gradient_predivide_factor/world size)``) will be omitted. """ def __init__(self, module, message_size=10000000, delay_allreduce=False, shared_param=None, allreduce_trigger_params=None, retain_allreduce_buffers=False, allreduce_always_fp32=False, num_allreduce_streams=1, allreduce_communicators=None, gradient_average=True, gradient_predivide_factor=1.0, gradient_average_split_factor=None, prof=False): super(DistributedDataParallel, self).__init__() # Backward/forward compatibility around # https://github.com/pytorch/pytorch/commit/540ef9b1fc5506369a48491af8a285a686689b36 and # https://github.com/pytorch/pytorch/commit/044d00516ccd6572c0d6ab6d54587155b02a3b86 if hasattr(dist, "get_backend"): self._backend = dist.get_backend() if hasattr(dist, "DistBackend"): self.backend_enum_holder = dist.DistBackend else: self.backend_enum_holder = dist.Backend else: self._backend = dist._backend self.backend_enum_holder = dist.dist_backend self.warn_on_half = True if self._backend == self.backend_enum_holder.GLOO else False self.prof = prof self.allreduce_different_streams = (num_allreduce_streams > 1) self.num_allreduce_streams = num_allreduce_streams self.allreduce_communicators = allreduce_communicators if self.allreduce_communicators: assert len(allreduce_communicators[0]) == num_allreduce_streams assert len(allreduce_communicators[0]) == len(allreduce_communicators[1]) assert self.allreduce_different_streams if self.allreduce_different_streams and delay_allreduce: raise ValueError("self.allreduce_different_streams may only be used if delay_allreduce=False.") if shared_param is not None: raise ValueError("shared_param is no longer supported as an option. It was misleadingly named from the start. It turns out overlapping communication with computation should work fine with shared parameters. If you still wish to delay communication to the end of the backward pass, use delay_allreduce=True|False instead.") self.world_size = float(dist.get_world_size()) self.retain_allreduce_buffers = retain_allreduce_buffers self.allreduce_always_fp32 = allreduce_always_fp32 self.gradient_average = gradient_average self.gradient_predivide_factor = gradient_predivide_factor self.custom_allreduce_triggers = False if allreduce_trigger_params is not None: if delay_allreduce: raise ValueError("Setting allreduce_trigger_params is only valid if delay_allreduce=False.") self.custom_allreduce_triggers = True self.allreduce_trigger_params = set([id(param) for param in allreduce_trigger_params]) self.delay_allreduce = delay_allreduce self.message_size = message_size self.main_stream = torch.cuda.current_stream() self.bucket_streams = [] self.bucket_events = [] self.module = module self._disable_allreduce = False if self._backend == self.backend_enum_holder.NCCL: for param in self.module.parameters(): assert param.is_cuda, "NCCL backend only supports model parameters to be on GPU." self.active_params = [] self.param_type_to_tmp_i = {"torch.cuda.HalfTensor" : 0, "torch.cuda.FloatTensor" : 1, "torch.cuda.DoubleTensor" : 2} if multi_tensor_applier.available: # TODO: I really need to centralize the C++ backed imports import amp_C self.multi_tensor_scale = amp_C.multi_tensor_scale self._overflow_buf = torch.cuda.IntTensor([0]) self.create_hooks() flat_dist_call([param.data for param in self.module.parameters()], dist.broadcast, (0,) ) def __setstate__(self, state): super(DistributedDataParallel, self).__setstate__(state) if self.allreduce_different_streams and delay_allreduce: raise ValueError("self.allreduce_different_streams may only be used if delay_allreduce=False.") if self.delay_allreduce: self.needs_refresh = True self.bucket_streams = [] self.bucket_events = [] def __getstate__(self): attrs = copy.copy(self.__dict__) if self._backend != self.backend_enum_holder.NCCL: del attrs['self.bucket_streams'] del attrs['self.bucket_events'] return attrs def enable_allreduce(self): self._disable_allreduce = False def disable_allreduce(self): self._disable_allreduce = True # Broadcast rank 0's bucket structure across all processes, and have all processes # regenerate their bucket structures to match. def sync_bucket_structure(self): # Append leftover buckets for tmp_bucket in self.tmp_buckets: if len(tmp_bucket) > 0: self.active_i_buckets.append(tmp_bucket) self.num_buckets = len(self.active_i_buckets) self.bucket_sizes = [len(bucket) for bucket in self.active_i_buckets] info_tensor = torch.cuda.IntTensor([self.num_buckets] + self.bucket_sizes + list(chain(*self.active_i_buckets))) dist.broadcast(info_tensor, 0) info = [int(entry) for entry in info_tensor] self.num_buckets = info[0] self.bucket_sizes = info[1:self.num_buckets + 1] self.buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] # Technically, active_i_buckets' work is done. But the information is still useful to # keep around. Therefore, refresh active_i_buckets based on rank 0 as well. self.active_i_buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] flattened_buckets = info[self.num_buckets + 1:] flat_i = 0 for bucket_idx in range(self.num_buckets): for bucket_loc in range(self.bucket_sizes[bucket_idx]): param_i = flattened_buckets[flat_i] self.active_i_buckets[bucket_idx][bucket_loc] = param_i self.param_id_to_bucket[id(self.active_params[param_i])] = (bucket_idx, bucket_loc) flat_i += 1 def create_hooks(self): # Fallback hook that's only called at the end of backward. # Used if you deliberately want to delay allreduces to the end, or to refresh the # bucket structure that will be used to overlap communication with computation in later # iterations. def allreduce_params(): # Bucket record refresh if not self.delay_allreduce: if self.needs_refresh: self.sync_bucket_structure() self.needs_refresh = False self.allreduce_fallback() def overlapping_backward_epilogue(): for stream, event in zip(self.bucket_streams, self.bucket_events): stream.record_event(event) torch.cuda.current_stream().wait_event(event) # Sanity checks that all the buckets were kicked off if self.next_bucket != self.num_buckets: raise RuntimeError("In epilogue, next_bucket ({}) != num_buckets ({}). ".format( self.next_bucket, self.num_buckets), "This probably indicates some buckets were not allreduced.") for actual, expected in zip(self.buckets_ready_size, self.bucket_sizes): if actual != expected: raise RuntimeError("Some param buckets were not allreduced.") self.grad_accs = [] for param in self.module.parameters(): if param.requires_grad: def wrapper(param): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): if self.prof: torch.cuda.nvtx.range_push("allreduce_hook") if not self._disable_allreduce: if self.delay_allreduce or self.needs_refresh: # TODO: How do we want to handle multiple backward passes between # each forward, e.g., backward passes with retain_graph=True? # needs_refresh and callback_queued are both vulnerable states. if not self.delay_allreduce and self.needs_refresh: # Use the backward pass to build the bucket structure on the fly. active_i = self.param_id_to_active_i[id(param)] # Float, half, and double tensors are grouped into buckets separately. current_type = self.param_type_to_tmp_i[param.type()] self.tmp_buckets[current_type].append(active_i) ship_tmp_bucket = False if self.custom_allreduce_triggers: if id(param) in self.allreduce_trigger_params: ship_tmp_bucket = True else: self.tmp_numels[current_type] += param.numel() if self.tmp_numels[current_type] >= self.message_size: ship_tmp_bucket = True # To consider: If custom_allreduce_triggers are in use, ship all # tmp_buckets, not just tmp_buckets[current_type]. if ship_tmp_bucket: self.active_i_buckets.append(self.tmp_buckets[current_type]) self.tmp_buckets[current_type] = [] self.tmp_numels[current_type] = 0 if not self.callback_queued: Variable._execution_engine.queue_callback(allreduce_params) self.callback_queued = True else: if not self.callback_queued: Variable._execution_engine.queue_callback(overlapping_backward_epilogue) self.callback_queued = True self.comm_ready_buckets(param) if self.prof: torch.cuda.nvtx.range_pop() grad_acc.register_hook(allreduce_hook) self.grad_accs.append(grad_acc) wrapper(param) def _stream_this_bucket(self, bucket_idx): if self.allreduce_different_streams: return self.bucket_streams[bucket_idx%self.num_allreduce_streams] else: return self.bucket_streams[0] def _event_this_bucket(self, bucket_idx): if self.allreduce_different_streams: return self.bucket_events[bucket_idx%self.num_allreduce_streams] else: return self.bucket_events[0] def allreduce_bucket(self, bucket, bucket_idx, force_default_stream): tensor = flatten(bucket) if force_default_stream: bucket_stream = self.main_stream else: bucket_stream = self._stream_this_bucket(bucket_idx) bucket_event = self._event_this_bucket(bucket_idx) torch.cuda.current_stream().record_event(bucket_event) bucket_stream.wait_event(bucket_event) with torch.cuda.stream(bucket_stream): # self.main_stream.wait_stream(torch.cuda.current_stream()) # torch.cuda.synchronize() tensor_to_allreduce = tensor if self.allreduce_always_fp32: tensor_to_allreduce = tensor.float() if self.gradient_predivide_factor != 1.0: tensor_to_allreduce.mul_(1./self.gradient_predivide_factor) if self.allreduce_different_streams and not force_default_stream: dist.all_reduce(tensor_to_allreduce, group=self.bucket_pgs[bucket_idx%self.num_allreduce_streams]) else: dist.all_reduce(tensor_to_allreduce) if self.gradient_average: tensor_to_allreduce.mul_(self.gradient_predivide_factor/self.world_size) if self.allreduce_always_fp32 and tensor is not tensor_to_allreduce: tensor.copy_(tensor_to_allreduce) if not self.retain_allreduce_buffers: if multi_tensor_applier.available: multi_tensor_applier( self.multi_tensor_scale, self._overflow_buf, [unflatten(tensor, bucket), bucket], 1.0) else: for buf, synced in zip(bucket, unflatten(tensor, bucket)): buf.copy_(synced) # I think we actually do need this here. After allreduce_bucket returns, tensor will # eventually go out of scope and die, at which point it could otherwise be freed for # further reuse by the main stream while the allreduce/div/unflatten are underway in bucket_stream. tensor.record_stream(bucket_stream) return tensor def allreduce_maybe_retain(self, bucket, bucket_idx, force_default_stream=False): allreduced = self.allreduce_bucket(bucket, bucket_idx, force_default_stream) if self.retain_allreduce_buffers: if self.allreduce_buffers[bucket_idx] is not None: raise RuntimeError("The backward pass is attempting to replace an already-filled " "allreduce buffer. This is almost certainly an error.") self.allreduce_buffers[bucket_idx] = allreduced for view, grad in zip(unflatten(allreduced, bucket), bucket): grad.data = view # for buf, synced in zip(bucket, unflatten(allreduced, bucket)): # buf.copy_(synced) def allreduce_fallback(self): for stream, event in zip(self.bucket_streams, self.bucket_events): stream.record_event(event) torch.cuda.current_stream().wait_event(event) if self.retain_allreduce_buffers: grads = [param.grad for param in self.module.parameters() if param.grad is not None] else: grads = [param.grad.data for param in self.module.parameters() if param.grad is not None] split_buckets = split_half_float_double(grads) # If retain_allreduce_buffers is True and delay_allreduce is False, # this will only be done during the first backward pass, ignored by the # training script, and overwritten in the next forward pass. So it's harmless. if self.retain_allreduce_buffers: self.allreduce_buffers = [None for _ in range(len(split_buckets))] for i, bucket in enumerate(split_buckets): allreduced = self.allreduce_maybe_retain(bucket, i, force_default_stream=True) def comm_ready_buckets(self, param): # Need to do this in every hook for compatibility with Ruberry's streaming backward PR. # self.reduction_stream.wait_stream(torch.cuda.current_stream()) if self.prof: torch.cuda.nvtx.range_push("comm_ready_buckets") bucket_idx, bucket_loc = self.param_id_to_bucket[id(param)] if self.buckets[bucket_idx][bucket_loc] is not None: raise RuntimeError("The backward pass is attempting to replace an already-filled " "bucket slot. This is almost certainly an error.") if self.retain_allreduce_buffers: self.buckets[bucket_idx][bucket_loc] = param.grad else: self.buckets[bucket_idx][bucket_loc] = param.grad.data self.buckets_ready_size[bucket_idx] += 1 if self.buckets_ready_size[bucket_idx] == self.bucket_sizes[bucket_idx]: if bucket_idx == self.next_bucket: self.allreduce_maybe_retain(self.buckets[bucket_idx], bucket_idx) self.next_bucket += 1 # Reversing upstream's logic here, because we constructed our buckets based on # the order things were received during backward. if len(self.ready_buckets_not_reduced) > 0: sorted_todo = sorted(self.ready_buckets_not_reduced) for i in sorted_todo: # Nothing can be reduced now if i > self.next_bucket: break elif i == self.next_bucket: self.allreduce_maybe_retain(self.buckets[i], i) self.ready_buckets_not_reduced.remove(i) self.next_bucket += 1 else: raise ValueError("i should always be >= next_bucket") else: self.ready_buckets_not_reduced.add(bucket_idx) if self.prof: torch.cuda.nvtx.range_pop() def forward(self, *inputs, **kwargs): result = self.module(*inputs, **kwargs) if self.prof: torch.cuda.nvtx.range_push("forward pass DDP logic") if not self._disable_allreduce: if not self.delay_allreduce: param_list = [param for param in self.module.parameters() if param.requires_grad] # Conditions under which to refresh self.record # Forward has the authority to set needs_refresh to True, but only allreduce_params # in backward has the authority to set needs_refresh to False. # Parentheses are not necessary for correct order of operations, but make the intent clearer. if ((not self.active_params) or (len(param_list) != len(self.active_params)) or any([param1 is not param2 for param1, param2 in zip(param_list, self.active_params)])): self.needs_refresh = True if self.needs_refresh: self.active_i_buckets = [] self.buckets = [] self.tmp_buckets = [[], [], []] # [running half, float, double buckets] self.tmp_numels = [0, 0, 0] self.bucket_sizes = [] self.param_id_to_active_i = {id(param) : i for i, param in enumerate(param_list)} self.param_id_to_bucket = {} self.bucket_pgs = [] self.bucket_streams = [] self.bucket_events = [] else: # self.buckets = [[None for _ in range(self.bucket_sizes[i])] # for i in range(self.num_buckets)] if not self.buckets: self.buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] else: assert len(self.buckets) == self.num_buckets, "len(buckets) = {}, expected {}".format( len(self.buckets), self.num_buckets) for b, bucket in enumerate(self.buckets): assert len(bucket) == self.bucket_sizes[b], "len(buckets[{}]) = {}, expected {})".format( b, len(buckets[b]), self.bucket_sizes[b]) for i in range(len(bucket)): bucket[i] = None if self.allreduce_communicators: self.bucket_pgs = self.allreduce_communicators[0] self.bucket_streams = self.allreduce_communicators[1] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False) for _ in range(self.num_allreduce_streams)] else: if self.allreduce_different_streams: if not self.bucket_pgs: self.bucket_pgs = [dist.new_group() for _ in range(self.num_allreduce_streams)] for i, bg in enumerate(self.bucket_pgs): print("rank {} created group {} with backend {}".format( dist.get_rank(), i, dist.get_backend(bg))) if self.allreduce_different_streams: if not self.bucket_streams: self.bucket_streams = [torch.cuda.Stream() for _ in range(self.num_allreduce_streams)] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False) for _ in range(self.num_allreduce_streams)] else: if not self.bucket_streams: self.bucket_streams = [torch.cuda.Stream()] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False)] self.buckets_ready_size = [0 for i in range(self.num_buckets)] if(self.retain_allreduce_buffers): self.allreduce_buffers = [None for _ in range(self.num_buckets)] self.next_bucket = 0 self.ready_buckets_not_reduced = set() self.active_params = param_list self.callback_queued = False if self.prof: torch.cuda.nvtx.range_pop() return result ================================================ FILE: KoSentenceT5/apex/parallel/multiproc.py ================================================ import torch import sys import subprocess def docstring_hack(): """ Multiproc file which will launch a set of processes locally for multi-gpu usage: python -m apex.parallel.multiproc main.py ... """ pass argslist = list(sys.argv)[1:] world_size = torch.cuda.device_count() if '--world-size' in argslist: world_size = int(argslist[argslist.index('--world-size')+1]) else: argslist.append('--world-size') argslist.append(str(world_size)) workers = [] for i in range(world_size): if '--rank' in argslist: argslist[argslist.index('--rank')+1] = str(i) else: argslist.append('--rank') argslist.append(str(i)) stdout = None if i == 0 else open("GPU_"+str(i)+".log", "w") print(argslist) p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout) workers.append(p) for p in workers: p.wait() ================================================ FILE: KoSentenceT5/apex/parallel/optimized_sync_batchnorm.py ================================================ import torch from torch.nn.modules.batchnorm import _BatchNorm from torch.nn import functional as F import syncbn from .optimized_sync_batchnorm_kernel import SyncBatchnormFunction class SyncBatchNorm(_BatchNorm): """ synchronized batch normalization module extented from `torch.nn.BatchNormNd` with the added stats reduction across multiple processes. :class:`apex.parallel.SyncBatchNorm` is designed to work with `DistributedDataParallel`. When running in training mode, the layer reduces stats across all processes to increase the effective batchsize for normalization layer. This is useful in applications where batch size is small on a given process that would diminish converged accuracy of the model. The model uses collective communication package from `torch.distributed`. When running in evaluation mode, the layer falls back to `torch.nn.functional.batch_norm` Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` process_group: pass in a process group within which the stats of the mini-batch is being synchronized. ``None`` for using default process group channel_last: a boolean value that when set to ``True``, this module take the last dimension of the input tensor to be the channel dimension. Default: False Examples:: >>> # channel first tensor >>> sbn = apex.parallel.SyncBatchNorm(100).cuda() >>> inp = torch.randn(10, 100, 14, 14).cuda() >>> out = sbn(inp) >>> inp = torch.randn(3, 100, 20).cuda() >>> out = sbn(inp) >>> # channel last tensor >>> sbn = apex.parallel.SyncBatchNorm(100, channel_last=True).cuda() >>> inp = torch.randn(10, 14, 14, 100).cuda() """ def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, process_group=None, channel_last=False, fuse_relu=False): super(SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats) self.process_group = process_group self.channel_last = channel_last self.fuse_relu = fuse_relu def _specify_process_group(self, process_group): self.process_group = process_group def _specify_channel_last(self, channel_last): self.channel_last = channel_last def forward(self, input, z = None): # if input.dim() == 2, we switch to channel_last for efficient memory accessing channel_last = self.channel_last if input.dim() != 2 else True if not self.training and self.track_running_stats and not channel_last and not self.fuse_relu and z == None: # fall back to pytorch implementation for inference return F.batch_norm(input, self.running_mean, self.running_var, self.weight, self.bias, False, 0.0, self.eps) else: exponential_average_factor = 0.0 if self.training and self.track_running_stats: self.num_batches_tracked += 1 if self.momentum is None: exponential_average_factor = 1.0 / float(self.num_batches_tracked) else: exponential_average_factor = self.momentum return SyncBatchnormFunction.apply(input, z, self.weight, self.bias, self.running_mean, self.running_var, self.eps, self.training or not self.track_running_stats, exponential_average_factor, self.process_group, channel_last, self.fuse_relu) ================================================ FILE: KoSentenceT5/apex/parallel/optimized_sync_batchnorm_kernel.py ================================================ import torch from torch.autograd.function import Function import syncbn from apex.parallel import ReduceOp class SyncBatchnormFunction(Function): @staticmethod def forward(ctx, input, z, weight, bias, running_mean, running_variance, eps, track_running_stats = True, momentum = 1.0, process_group = None, channel_last = False, fuse_relu = False): input = input.contiguous() world_size = 0 mean = None var_biased = None inv_std = None var = None out = None count = None if track_running_stats: if channel_last: count = int(input.numel()/input.size(-1)) mean, var_biased = syncbn.welford_mean_var_c_last(input) num_channels = input.size(-1) else: count = int(input.numel()/input.size(1)) mean, var_biased = syncbn.welford_mean_var(input) num_channels = input.size(1) if torch.distributed.is_initialized(): if not process_group: process_group = torch.distributed.group.WORLD device = mean.device world_size = torch.distributed.get_world_size(process_group) count_t = torch.empty(1, dtype=mean.dtype, device=mean.device).fill_(count) combined = torch.cat([mean.view(-1), var_biased.view(-1), count_t], dim=0) combined_list = [torch.empty_like(combined) for k in range(world_size)] torch.distributed.all_gather(combined_list, combined, process_group) combined = torch.stack(combined_list, dim=0) mean_all, invstd_all, count_all = torch.split(combined, num_channels, dim=1) count_all = count_all.view(-1) mean, var, inv_std = syncbn.welford_parallel(mean_all, invstd_all, count_all.to(torch.int32), eps) else: device = mean.device count_all = torch.cuda.IntTensor([count], device=device) inv_std = 1.0 / torch.sqrt(var_biased + eps) var = var_biased * (count) / (count-1) if count == 1 and world_size < 2: raise ValueError('Expected more than 1 value per channel when training, got input size{}'.format(input.size())) r_m_inc = mean if running_mean.dtype != torch.float16 else mean.half() r_v_inc = var if running_variance.dtype != torch.float16 else var.half() running_mean.data = running_mean.data * (1-momentum) + momentum*r_m_inc running_variance.data = running_variance.data * (1-momentum) + momentum*r_v_inc else: mean = running_mean.data inv_std = 1.0 / torch.sqrt(running_variance.data + eps) ctx.save_for_backward(input, weight, mean, inv_std, z, bias, count_all.to(torch.int32)) ctx.process_group = process_group ctx.channel_last = channel_last ctx.world_size = world_size ctx.fuse_relu = fuse_relu if channel_last: out = syncbn.batchnorm_forward_c_last(input, z, mean, inv_std, weight, bias, fuse_relu) else: out = syncbn.batchnorm_forward(input, mean, inv_std, weight, bias) return out @staticmethod def backward(ctx, grad_output): grad_output = grad_output.contiguous() # mini batch mean & var are calculated by forward path. # mu = 1./N*np.sum(h, axis = 0) # var = 1./N*np.sum((h-mu)**2, axis = 0) saved_input, weight, mean, inv_std, z, bias, count = ctx.saved_tensors process_group = ctx.process_group channel_last = ctx.channel_last world_size = ctx.world_size fuse_relu = ctx.fuse_relu grad_input = grad_z = grad_weight = grad_bias = None if fuse_relu: grad_output = syncbn.relu_bw_c_last(grad_output, saved_input, z, mean, inv_std, weight, bias) if isinstance(z, torch.Tensor) and ctx.needs_input_grad[1]: grad_z = grad_output.clone() # TODO: update kernel to not pre_divide by item_num if channel_last: sum_dy, sum_dy_xmu, grad_weight, grad_bias = syncbn.reduce_bn_c_last(grad_output, saved_input, mean, inv_std, weight) else: sum_dy, sum_dy_xmu, grad_weight, grad_bias = syncbn.reduce_bn(grad_output, saved_input, mean, inv_std, weight) # calculate grad_input if ctx.needs_input_grad[0]: if torch.distributed.is_initialized(): num_channels = sum_dy.shape[0] combined = torch.cat([sum_dy, sum_dy_xmu], dim=0) torch.distributed.all_reduce( combined, torch.distributed.ReduceOp.SUM, process_group, async_op=False) sum_dy, sum_dy_xmu = torch.split(combined, num_channels) if channel_last: grad_input = syncbn.batchnorm_backward_c_last(grad_output, saved_input, mean, inv_std, weight, sum_dy, sum_dy_xmu, count) else: grad_input = syncbn.batchnorm_backward(grad_output, saved_input, mean, inv_std, weight, sum_dy, sum_dy_xmu, count) if weight is None or not ctx.needs_input_grad[2]: grad_weight = None if weight is None or not ctx.needs_input_grad[3]: grad_bias = None return grad_input, grad_z, grad_weight, grad_bias, None, None, None, None, None, None, None, None ================================================ FILE: KoSentenceT5/apex/parallel/sync_batchnorm.py ================================================ import torch from torch.nn.modules.batchnorm import _BatchNorm from torch.nn import functional as F from .sync_batchnorm_kernel import SyncBatchnormFunction from apex.parallel import ReduceOp class SyncBatchNorm(_BatchNorm): """ synchronized batch normalization module extented from ``torch.nn.BatchNormNd`` with the added stats reduction across multiple processes. :class:`apex.parallel.SyncBatchNorm` is designed to work with ``DistributedDataParallel``. When running in training mode, the layer reduces stats across all processes to increase the effective batchsize for normalization layer. This is useful in applications where batch size is small on a given process that would diminish converged accuracy of the model. The model uses collective communication package from ``torch.distributed``. When running in evaluation mode, the layer falls back to ``torch.nn.functional.batch_norm``. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Example:: >>> sbn = apex.parallel.SyncBatchNorm(100).cuda() >>> inp = torch.randn(10, 100, 14, 14).cuda() >>> out = sbn(inp) >>> inp = torch.randn(3, 100, 20).cuda() >>> out = sbn(inp) """ warned = False def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, process_group=None, channel_last=False): if channel_last == True: raise AttributeError("channel_last is not supported by primitive SyncBatchNorm implementation. Try install apex with `--cuda_ext` if channel_last is desired.") if not SyncBatchNorm.warned: if hasattr(self, "syncbn_import_error"): print("Warning: using Python fallback for SyncBatchNorm, possibly because apex was installed without --cuda_ext. The exception raised when attempting to import the cuda backend was: ", self.syncbn_import_error) else: print("Warning: using Python fallback for SyncBatchNorm") SyncBatchNorm.warned = True super(SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats) self.process_group = process_group def _specify_process_group(self, process_group): self.process_group = process_group def forward(self, input): torch.cuda.nvtx.range_push("sync_bn_fw_with_mean_var") mean = None var = None cast = None out = None # casting to handle mismatch input type to layer type if self.running_mean is not None: if self.running_mean.dtype != input.dtype: input = input.to(self.running_mean.dtype) cast = input.dtype elif self.weight is not None: if self.weight.dtype != input.dtype: input = input.to(self.weight.dtype) cast = input.dtype if not self.training and self.track_running_stats: # fall back to pytorch implementation for inference torch.cuda.nvtx.range_pop() out = F.batch_norm(input, self.running_mean, self.running_var, self.weight, self.bias, False, 0.0, self.eps) else: process_group = self.process_group world_size = 1 if not self.process_group: process_group = torch.distributed.group.WORLD self.num_batches_tracked += 1 with torch.no_grad(): channel_first_input = input.transpose(0, 1).contiguous() squashed_input_tensor_view = channel_first_input.view( channel_first_input.size(0), -1) # total number of data points for each variance entry. Used to calculate unbiased variance estimate m = None local_m = float(squashed_input_tensor_view.size()[1]) local_mean = torch.mean(squashed_input_tensor_view, 1) local_sqr_mean = torch.pow( squashed_input_tensor_view, 2).mean(1) if torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size(process_group) torch.distributed.all_reduce( local_mean, ReduceOp.SUM, process_group) mean = local_mean / world_size torch.distributed.all_reduce( local_sqr_mean, ReduceOp.SUM, process_group) sqr_mean = local_sqr_mean / world_size m = local_m * world_size else: m = local_m mean = local_mean sqr_mean = local_sqr_mean # var(x) = E (( x - mean_x ) ** 2) # = 1 / N * sum ( x - mean_x ) ** 2 # = 1 / N * sum (x**2) - mean_x**2 var = sqr_mean - mean.pow(2) if self.running_mean is not None: self.running_mean = self.momentum * mean + \ (1 - self.momentum) * self.running_mean if self.running_var is not None: # as noted by the paper, we used unbiased variance estimate of the mini-batch # Var[x] = m / (m-1) * Eb (sample_variance) self.running_var = m / \ (m-1) * self.momentum * var + \ (1 - self.momentum) * self.running_var torch.cuda.nvtx.range_pop() out = SyncBatchnormFunction.apply(input, self.weight, self.bias, mean, var, self.eps, process_group, world_size) return out.to(cast) ================================================ FILE: KoSentenceT5/apex/parallel/sync_batchnorm_kernel.py ================================================ import torch from torch.autograd.function import Function from apex.parallel import ReduceOp class SyncBatchnormFunction(Function): @staticmethod def forward(ctx, input, weight, bias, running_mean, running_variance, eps, process_group, world_size): torch.cuda.nvtx.range_push("sync_BN_fw") # transpose it to channel last to support broadcasting for input with different rank c_last_input = input.transpose(1, -1).contiguous().clone() ctx.save_for_backward(c_last_input, weight, bias, running_mean, running_variance) ctx.eps = eps ctx.process_group = process_group ctx.world_size = world_size c_last_input = (c_last_input - running_mean) / \ torch.sqrt(running_variance + eps) if weight is not None: c_last_input = c_last_input * weight if bias is not None: c_last_input = c_last_input + bias torch.cuda.nvtx.range_pop() return c_last_input.transpose(1, -1).contiguous().clone() @staticmethod def backward(ctx, grad_output): torch.cuda.nvtx.range_push("sync_BN_bw") # mini batch mean & var are calculated by forward path. # mu = 1./N*np.sum(h, axis = 0) # var = 1./N*np.sum((h-mu)**2, axis = 0) c_last_input, weight, bias, running_mean, running_variance = ctx.saved_tensors eps = ctx.eps process_group = ctx.process_group world_size = ctx.world_size grad_input = grad_weight = grad_bias = None num_features = running_mean.size()[0] # transpose it to channel last to support broadcasting for input with different rank torch.cuda.nvtx.range_push("carilli field") c_last_grad = grad_output.transpose(1, -1).contiguous() # squash non-channel dimension so we can easily calculate mean c_grad = c_last_grad.view(-1, num_features).contiguous() torch.cuda.nvtx.range_pop() # calculate grad_input if ctx.needs_input_grad[0]: # dh = gamma * (var + eps)**(-1. / 2.) * (dy - np.mean(dy, axis=0) # - (h - mu) * (var + eps)**(-1.0) * np.mean(dy * (h - mu), axis=0)) mean_dy = c_grad.mean(0) mean_dy_xmu = (c_last_grad * (c_last_input - running_mean)).view(-1, num_features).mean(0) if torch.distributed.is_initialized(): torch.distributed.all_reduce( mean_dy, ReduceOp.SUM, process_group) mean_dy = mean_dy / world_size torch.distributed.all_reduce( mean_dy_xmu, ReduceOp.SUM, process_group) mean_dy_xmu = mean_dy_xmu / world_size c_last_grad_input = (c_last_grad - mean_dy - (c_last_input - running_mean) / ( running_variance + eps) * mean_dy_xmu) / torch.sqrt(running_variance + eps) if weight is not None: c_last_grad_input.mul_(weight) grad_input = c_last_grad_input.transpose(1, -1).contiguous() # calculate grad_weight grad_weight = None if weight is not None and ctx.needs_input_grad[1]: # dgamma = np.sum((h - mu) * (var + eps)**(-1. / 2.) * dy, axis=0) grad_weight = ((c_last_input - running_mean) / torch.sqrt( running_variance + eps) * c_last_grad).view(-1, num_features).sum(0) # calculate grad_bias grad_bias = None if bias is not None and ctx.needs_input_grad[2]: # dbeta = np.sum(dy, axis=0) grad_bias = c_grad.sum(0) torch.cuda.nvtx.range_pop() return grad_input, grad_weight, grad_bias, None, None, None, None, None ================================================ FILE: KoSentenceT5/apex/pyprof/FAQs.md ================================================ 1. How do I intercept the Adam optimizer in APEX ? ```python from apex import pyprof import fused_adam_cuda pyprof.nvtx.wrap(fused_adam_cuda, 'adam') ``` 2. If you are using JIT and/or AMP, the correct initialization sequence is 1. Let any JIT to finish. 2. Initlialize pyprof `pyprof.nvtx.init()`. 3. Initialize AMP. 3. How do I profile with `torch.distributed.launch` ? ```python nvprof -f -o net%p.sql \ --profile-from-start off \ --profile-child-processes \ python -m torch.distributed.launch net.py ``` ================================================ FILE: KoSentenceT5/apex/pyprof/README.md ================================================ ## PyProf - PyTorch Profiling tool ### What does this tool do? Analyzing the performance of deep neural networks is hard. Getting kernels out of [NvProf]([https://developer.nvidia.com/nvidia-visual-profiler](https://developer.nvidia.com/nvidia-visual-profiler)) or [NSight Compute]([https://developer.nvidia.com/nsight-compute](https://developer.nvidia.com/nsight-compute)) provides some generic kernel name and its execution time, but not detailed information regarding the following: - Which layer launched it: e.g. the association of `ComputeOffsetsKernel` with a concrete PyTorch layer or API is not obvious. - What the tensor dimensions and precision were: without knowing the tensor dimensions and precision, it's impossible to reason about whether the actual (silicon) kernel time is close to maximum performance of such a kernel on the GPU. Knowing the tensor dimensions and precision, we can figure out the FLOPs and bandwidth required by a layer, and then determine how close to maximum performance the kernel is for that operation. - Forward-backward correlation: currently it's very hard to determine what the forward pass step was that resulted in the particular weight and data gradients (wgrad, dgrad), which makes it difficult to determine the tensor dimensions required by these backprop steps to assess their performance. - Did the kernel use [Tensor Cores]([https://www.youtube.com/watch?v=yyR0ZoCeBO8](https://www.youtube.com/watch?v=yyR0ZoCeBO8))? - Which line in the user's code resulted in launching this particular kernel (program trace)? PyProf addresses all of the issues above by: 1. Instrumenting PyTorch operations to capture the tensor dimensions and precision using [NVTX](https://devblogs.nvidia.com/cuda-pro-tip-generate-custom-application-profile-timelines-nvtx). This information is recorded at profile capture time, e.g. using [NvProf](https://developer.nvidia.com/nvidia-visual-profiler). 2. Querying the record produced by the profiler to correlate the kernel name and duration with PyTorch API/layer name, tensor dimensions, tensor precision, as well as calculating FLOPs and bandwidth for common operations. In addition, extra information from the profile is added for use by CUDA professionals, such as CUDA launch parameters (block/grid dimensions). Regarding FLOP and bandwidth implementations, these are usually quite straightforward. For example, for matrices AMxK and BKxN, the FLOP count for a matrix multiplication is 2 * M * N * K, and bandwidth is M * K + N * K + M * N. Note that these numbers are based on the algorithm, not the actual performance of the specific kernel. For more details, see NVIDIA's [Deep Learning Performance Guide](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html). Armed with such information, the user can determine various issues to help them tune the network. For instance, according to the [Tensor Core Performance Guide]([https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html)), the M, N and K dimensions that result in Tensor Core usage need to be divisible by 8. In fact, PyProf comes with a flag that lets the user obtain information regarding whether Tensor Cores were used by the kernel. Other useful information might include knowing that a particular kernel did not exploit much thread parallelism, as determined by the grid/block dimensions. Since many PyTorch kernels are open-source (or even custom written by the user, as in [CUDA Extensions]([https://pytorch.org/tutorials/advanced/cpp_extension.html](https://pytorch.org/tutorials/advanced/cpp_extension.html))), this provides the user with information that helps root cause performance issues and prioritize optimization work. ### How to get started? 1. Add the following lines to your PyTorch network: ```python import torch.cuda.profiler as profiler from apex import pyprof pyprof.nvtx.init() ``` Run the training/inference loop with the [PyTorch's NVTX context manager](https://pytorch.org/docs/stable/_modules/torch/autograd/profiler.html#emit_nvtx) `with torch.autograd.profiler.emit_nvtx()`. Optionally, you can use `profiler.start()` and `profiler.stop()` to pick an iteration (say after warm-up) for which you would like to capture data. Here's an example: ```python iters = 500 iter_to_capture = 100 # Define network, loss function, optimizer etc. # PyTorch NVTX context manager with torch.autograd.profiler.emit_nvtx(): for iter in range(iters): if iter == iter_to_capture: profiler.start() output = net(images) loss = criterion(output, labels) loss.backward() optimizer.step() if iter == iter_to_capture: profiler.stop() ``` 2. Run NVprof to generate a SQL (NVVP) file. This file can be opened with NVVP, as usual. ```sh # If you used profiler.start() and profiler.stop() in net.py nvprof -f -o net.sql --profile-from-start off -- python net.py # Profile everything nvprof -f -o net.sql -- python net.py ``` **Note:** if you're experiencing issues with hardware counters and you get a message such as `**_ERR_NVGPUCTRPERM The user running does not have permission to access NVIDIA GPU Performance Counters on the target device_**`, please follow the steps described in [Hardware Counters](#hardware-counters). 3. Run parser on the SQL file. The output is an ASCII file. Each line is a python dictionary which contains information about the kernel name, duration, parameters etc. This file can be used as input to other custom scripts as well. ```sh python -m apex.pyprof.parse net.sql > net.dict ``` 4. Run the profiler. The input is the python dictionary created above. The tool can produce a CSV output, a columnated output (similar to `column -t` for terminal readability) and a space separated output (for post processing by AWK for instance). The tool produces 20 columns of information for every GPU kernel but you can select a subset of columns using the `-c` flag. Note that a few columns might have the value "na" implying either its a work in progress or the tool was unable to extract that information. Assuming the directory is `prof`, here are a few examples of how to use `prof.py`. ```sh # Print usage and help. Lists all available output columns. python -m apex.pyprof.prof -h # Columnated output of width 150 with some default columns. python -m apex.pyprof.prof -w 150 net.dict # CSV output. python -m apex.pyprof.prof --csv net.dict # Space seperated output. python -m apex.pyprof.prof net.dict # Columnated output of width 130 with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof -w 130 -c idx,dir,kernel,params,sil net.dict # CSV output with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof --csv -c idx,dir,kernel,params,sil net.dict # Space separated output with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof -c idx,dir,kernel,params,sil net.dict # Input redirection. python -m apex.pyprof.prof < net.dict ``` 5. Profile-guided optimization If kernels that do matrix multiplication/GEMM or convolution use half precision (fp16) data but do not use Tensor Cores (the TC column in the profile analysis output doesn't show a "1"), one can follow some basic steps to increase the likelihood that a Tensor Core-compatible kernel will be chosen. For example, for GEMMs, M, N and K should be divisible by 8, and for convolutions, the number of input and output channels shuold be divisible by 8. For more information, see detailed Tensor Core guides such as: - Blog Post: [Tips for Optimizing GPU Performance Using Tensor Cores](https://devblogs.nvidia.com/optimizing-gpu-performance-tensor-cores/) - GTC Talk: [Tensor Core Deep Learning Performance Guide](https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9926-tensor-core-performance-the-ultimate-guide.pdf) For both Tensor Core and non-Tensor Core Deep Learning performance optimization tips, see NVIDIA's [Deep Learning Performance Guide](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html). ### TODOs 1. The support for conv transpose is currently missing. 2. PyProf currently works only with NvProf, but Nsight Compute support will be added in the future. ### Example 1. Run `nvprof` on the LeNet model in `examples/lenet.py`. This will output a SQL file called `net.sql`. ```sh nvprof -f -o net.sql --profile-from-start off -- python examples/lenet.py ``` **Note**: DO NOT add --analysis-metrics since that will change which table nvprof writes the kernels to (`CUPTI_ACTIVITY_KIND_KERNEL` instead of the usual `CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL`). Support for running with metrics may be added in the future. If you don't care about a full correlation analysis and you'd just like to view the timeline with detailed NVTX annotations, you can do so, e.g. in the NVIDIA Visual Profiler (NVVP). For example, you can call `nvvp net.sql` to view the annotated timeline. 2. Run the `parse.py` script on `net.sql` to extract kernel and runtime information and save it as `net.dict`. ```sh python -m apex.pyprof.parse net.sql > net.dict ``` This will produce a text file, which can be parsed by any external tool, but it can also be directly read one line at a time by Python by calling `eval` on the line being read. **Note: you do not need to process this output manually.** Here the output is just shown as an example of modularity - you can process the raw data yourself, or let the next step enrich the information further and dump a CSV. The output of this step will look as follows. Note that the dictionary has a lot more keys than the ones shown in the example. ``` >>> with open('torchvision.resnet50.adam.64.dict') as f: ... for line in f: ... d = eval(line) ... print(d['kShortName'], d['op'], d['kDuration'], d['block'], d['grid'], d['device'], d['stream'], d['trace']) ... nchwToNhwc3To4Kernel ['conv2d'] 376324 (256, 1, 1) (1568, 1, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] generic4Channel_kernel ['conv2d'] 10720 (512, 1, 1) (19, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] first_layer_fwd_kernel ['conv2d'] 411204 (128, 1, 1) (2, 7, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] nhwcToNchwKernel ['conv2d'] 342371 (256, 1, 1) (392, 2, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] elementwise_kernel ['__iadd__'] 2816 (128, 1, 1) (1, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:196'] batch_norm_collect_statistics_kernel ['batch_norm', 'batch_norm'] 929513 (512, 1, 1) (64, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:196'] ``` 3. Run the `prof.py` script on `net.dict` to summarize the results into a CSV file, or to display the pretty-printed results on the screen. This step processes the raw output from step 2 to generate a nice output, but it also adds a lot of extra useful information inferred from the previous step, such as: - FLOPs - bandwidth (bytes in and out of GPU DRAM) - tensor core usage ```sh python -m apex.pyprof.prof --csv net.dict > results.csv ``` You can choose which columns you'd like to display. Here's a list from calling `python -m apex.pyprof.prof -h`: ``` idx: Index seq: PyTorch Sequence Id altseq: PyTorch Alternate Sequence Id tid: Thread Id layer: User annotated NVTX string (can be nested) trace: Function Call Trace dir: Direction sub: Sub Sequence Id mod: Module op: Operation kernel: Kernel Name params: Parameters sil: Silicon Time (in ns) tc: Tensor Core Usage device: GPU Device Id stream: Stream Id grid: Grid Dimensions block: Block Dimensions flops: Floating point ops (FMA = 2 FLOPs) bytes: Number of bytes in and out of DRAM ``` Let's have a look at the pretty-printed output: ``` python -m apex.pyprof.prof -w 100 -c kernel,op,sil,tc,flops,bytes,device,stream,block,grid torchvision.resnet50.adam.64.dict Kernel Op Sil(ns) TC FLOPs Bytes Dev Str Block Grid elementwise_kernel relu 381028 - 51380224 205520896 0 7 512,1,1 100352,1,1 volta_fp16_s884cudn conv2d 160002 1 1644167168 51388416 0 7 256,1,1 784,1,1 elementwise_kernel relu 96545 - 12845056 51380224 0 7 512,1,1 25088,1,1 volta_fp16_s884cudn conv2d 346083 1 6576668672 128483328 0 7 256,1,1 784,2,1 ``` Not using the pretty-print width (`-w`) option and adding `--csv` results in a CSV output instead: ``` python -m apex.pyprof.prof --csv -c kernel,mod,op,dir,sil,tc,flops,bytes,device,stream,block,grid torchvision.resnet50.adam.64.dict "Kernel","Module","Op","Direction","Sil(ns)","TC","FLOPs","Bytes","Device","Stream","Block","Grid" "nchwToNhwc3To4Kernel","torch.nn.functional","conv2d","fprop","376324","-","0","0","0","7","256,1,1","1568,1,64" "generic4Channel_kernel","torch.nn.functional","conv2d","fprop","10720","-","0","0","0","7","512,1,1","19,1,1" "first_layer_fwd_kernel","torch.nn.functional","conv2d","fprop","411204","-","0","0","0","7","128,1,1","2,7,64" "nhwcToNchwKernel","torch.nn.functional","conv2d","fprop","342371","-","0","0","0","7","256,1,1","392,2,64" "elementwise_kernel","Tensor","__iadd__","fprop","2816","-","1.0","8","0","7","128,1,1","1,1,1" "batch_norm_collect_statistics_kernel","torch.nn.functional","batch_norm","fprop","929513","-","411041792","411041792","0","7","512,1,1","64,1,1" "batch_norm_transform_input_kernel","torch.nn.functional","batch_norm","fprop","377539","-","411041792","411041792","0","7","512,1,1","64,64,1" "elementwise_kernel","torch.nn.functional","relu","fprop","381028","-","51380224","205520896","0","7","512,1,1","100352,1,1" "MaxPoolForward","torch.nn.functional","max_pool2d","fprop","406531","-","0","0","0","7","256,1,1","50176,1,1" "cudnn::gemm::computeOffsetsKernel","torch.nn.functional","conv2d","fprop","2464","-","0","0","0","7","128,1,1","25,1,1" ``` ### Hardware Counters Profiling GPU workloads may require access to [hardware performance counters]([https://en.wikipedia.org/wiki/Hardware_performance_counter](https://en.wikipedia.org/wiki/Hardware_performance_counter)). Due to a [fix](https://nvidia.custhelp.com/app/answers/detail/a_id/4738) in recent NVIDIA drivers addressing [CVE‑2018‑6260](https://nvd.nist.gov/vuln/detail/CVE-2018-6260), the hardware counters are disabled by default, and require elevated privileges to be enabled again. If you're using a recent driver, you may see the following message when trying to run nvprof: ```**_ERR_NVGPUCTRPERM The user running does not have permission to access NVIDIA GPU Performance Counters on the target device._**``` For details, see [here](https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters). _Permanent solution_ Follow the steps [here]([https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters](https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters)). The current steps for Linux are: ``` sudo systemctl isolate multi-user sudo modprobe -r nvidia_uvm nvidia_drm nvidia_modeset nvidia-vgpu-vfio nvidia sudo modprobe nvidia NVreg_RestrictProfilingToAdminUsers=0 sudo systemctl isolate graphical ``` The above steps should result in a permanent change. _Temporary solution_ When running on bare metal, you can run nvprof with `sudo`. If you're running in a Docker image, you can temporarily elevate your privileges with one of the following (oldest to newest syntax):
nvidia-docker run --privileged
docker run --runtime nvidia --privileged
docker run --gpus all --privileged
================================================ FILE: KoSentenceT5/apex/pyprof/__init__.py ================================================ import warnings from . import nvtx, prof ================================================ FILE: KoSentenceT5/apex/pyprof/examples/.gitignore ================================================ __pycache__ *.sql *.dict *.csv ================================================ FILE: KoSentenceT5/apex/pyprof/examples/apex/README.md ================================================ This directory has examples of how to use `pyprof` with APEX extensions e.g. `fused_adam_cuda` and `fused_layer_norm_cuda`. ================================================ FILE: KoSentenceT5/apex/pyprof/examples/apex/fused_adam.py ================================================ import torch import fused_adam_cuda from apex.optimizers import FusedAdam, FP16_Optimizer from apex import pyprof pyprof.nvtx.init() pyprof.nvtx.wrap(fused_adam_cuda, 'adam') model = torch.nn.Linear(10, 20).cuda().half() criterion = torch.nn.CrossEntropyLoss().cuda() optimizer = FusedAdam(model.parameters()) optimizer = FP16_Optimizer(optimizer) x = torch.ones(32, 10).cuda().half() target = torch.empty(32, dtype=torch.long).random_(20).cuda() y = model(x) loss = criterion(y, target) optimizer.zero_grad() loss.backward() optimizer.step() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/apex/fused_layer_norm.py ================================================ import torch import fused_layer_norm_cuda from apex.normalization import FusedLayerNorm from apex import pyprof pyprof.nvtx.init() pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'backward') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward_affine') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'backward_affine') input = torch.randn(20, 5, 10, 10).cuda() # With Learnable Parameters m = FusedLayerNorm(input.size()[1:]).cuda() output = m(input) # Without Learnable Parameters m = FusedLayerNorm(input.size()[1:], elementwise_affine=False).cuda() output = m(input) # Normalize over last two dimensions m = FusedLayerNorm([10, 10]).cuda() output = m(input) # Normalize over last dimension of size 10 m = FusedLayerNorm(10).cuda() output = m(input) ================================================ FILE: KoSentenceT5/apex/pyprof/examples/apex/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSentenceT5/apex/pyprof/examples/custom_func_module/README.md ================================================ This directory has examples which show how to intercept (monkey patch) custom functions and modules with `pyprof`. No changes are required in `pyprof/parse`, however, users can add support for bytes and flops calculation for custom functions and modules in `pyprof/prof` by extending the `OperatorLayerBase` class. ================================================ FILE: KoSentenceT5/apex/pyprof/examples/custom_func_module/custom_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof #Initialize pyprof pyprof.nvtx.init() class Foo(torch.autograd.Function): @staticmethod def forward(ctx, in1, in2): out = in1 + in2 #This could be a custom C/C++ function. return out @staticmethod def backward(ctx, grad): in1_grad = grad #This could be a custom C/C++ function. in2_grad = grad #This could be a custom C/C++ function. return in1_grad, in2_grad #Hook the forward and backward functions to pyprof pyprof.nvtx.wrap(Foo, 'forward') pyprof.nvtx.wrap(Foo, 'backward') foo = Foo.apply x = torch.ones(4,4).cuda() y = torch.ones(4,4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x,y) profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/custom_func_module/custom_module.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof pyprof.nvtx.init() class Foo(torch.nn.Module): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) def forward(self, input): return self.n*input + self.m #Hook the forward function to pyprof pyprof.nvtx.wrap(Foo, 'forward') foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x) profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/custom_func_module/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSentenceT5/apex/pyprof/examples/imagenet/imagenet.py ================================================ #!/usr/bin/env python3 """ Example to run pyprof with imagenet models. """ import sys import torch import torch.nn as nn import torchvision.models as models import torch.cuda.profiler as profiler import argparse from apex import pyprof from apex.optimizers import FusedAdam def parseArgs(): parser = argparse.ArgumentParser(prog=sys.argv[0], description="Run popular imagenet models.") parser.add_argument("-m", type=str, default="resnet50", choices=["alexnet", "densenet121", "densenet161", "densenet169", "densenet201", "googlenet", "mnasnet0_5", "mnasnet0_75", "mnasnet1_0", "mnasnet1_3", "mobilenet_v2", "resnet18", "resnet34", "resnet50", "resnet101", "resnet152", "resnext50_32x4d", "resnext101_32x8d", "wide_resnet50_2", "wide_resnet101_2", "shufflenet_v2_x0_5", "shufflenet_v2_x1_0", "shufflenet_v2_x1_5", "shufflenet_v2_x2_0", "squeezenet1_0", "squeezenet1_1", "vgg11", "vgg11_bn", "vgg13", "vgg13_bn", "vgg16", "vgg16_bn", "vgg19", "vgg19_bn", "inception_v3"], help="Model.") parser.add_argument("-b", type=int, default=32, help="Batch size.") parser.add_argument("-o", type=str, default="adam", choices=["adam", "sgd"], help="Optimizer.") args = parser.parse_args() return args d = { "alexnet": {'H': 224, 'W': 224, 'opts': {}}, "densenet121": {'H': 224, 'W': 224, 'opts': {}}, "densenet161": {'H': 224, 'W': 224, 'opts': {}}, "densenet169": {'H': 224, 'W': 224, 'opts': {}}, "densenet201": {'H': 224, 'W': 224, 'opts': {}}, "googlenet": {'H': 224, 'W': 224, 'opts': {'aux_logits': False}}, "mnasnet0_5": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet0_75": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet1_0": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet1_3": {'H': 224, 'W': 224, 'opts': {}}, "mobilenet_v2": {'H': 224, 'W': 224, 'opts': {}}, "resnet18": {'H': 224, 'W': 224, 'opts': {}}, "resnet34": {'H': 224, 'W': 224, 'opts': {}}, "resnet50": {'H': 224, 'W': 224, 'opts': {}}, "resnet101": {'H': 224, 'W': 224, 'opts': {}}, "resnet152": {'H': 224, 'W': 224, 'opts': {}}, "resnext50_32x4d": {'H': 224, 'W': 224, 'opts': {}}, "resnext101_32x8d": {'H': 224, 'W': 224, 'opts': {}}, "wide_resnet50_2": {'H': 224, 'W': 224, 'opts': {}}, "wide_resnet101_2": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x0_5": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x1_0": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x1_5": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x2_0": {'H': 224, 'W': 224, 'opts': {}}, "squeezenet1_0": {'H': 224, 'W': 224, 'opts': {}}, "squeezenet1_1": {'H': 224, 'W': 224, 'opts': {}}, "vgg11": {'H': 224, 'W': 224, 'opts': {}}, "vgg11_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg13": {'H': 224, 'W': 224, 'opts': {}}, "vgg13_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg16": {'H': 224, 'W': 224, 'opts': {}}, "vgg16_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg19": {'H': 224, 'W': 224, 'opts': {}}, "vgg19_bn": {'H': 224, 'W': 224, 'opts': {}}, "inception_v3": {'H': 299, 'W': 299, 'opts': {'aux_logits': False}}, } def main(): args = parseArgs() pyprof.nvtx.init() # pyprof.nvtx.wrap(fused_adam_cuda, 'adam') N = args.b C = 3 H = d[args.m]['H'] W = d[args.m]['W'] opts = d[args.m]['opts'] classes = 1000 net = getattr(models, args.m) net = net(**opts).cuda().half() net.train() x = torch.rand(N, C, H, W).cuda().half() target = torch.empty(N, dtype=torch.long).random_(classes).cuda() criterion = nn.CrossEntropyLoss().cuda() if (args.o == "sgd"): optimizer = torch.optim.SGD(net.parameters(), lr = 0.01, momentum=0.9) elif (args.o == "adam"): optimizer = FusedAdam(net.parameters()) else: assert False #Warm up without profiler for i in range(2): output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() with torch.autograd.profiler.emit_nvtx(): profiler.start() output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() profiler.stop() if __name__ == "__main__": main() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/imagenet/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python -m apex.pyprof.parse" prof="python -m apex.pyprof.prof" for net in "resnet50" do for optim in adam sgd do for batch in 32 64 do base="torchvision".$net.$optim.$batch sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql --profile-from-start off python imagenet.py -m ${net} -o $optim -b $batch" nvprof -fo $sql --profile-from-start off python imagenet.py -m ${net} -o $optim -b $batch #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict # \rm $sql $dict done done done ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/README.md ================================================ *As of this writing, these examples do not work because of changes being proposed in PyTorch.* There are two ways to use PyTorch JIT - Scripting - Tracing In addition, we can JIT a - Stand alone function - Class / class method This directory has an example for each of the 4 cases. Intercepting (monkey patching) JITted code has a few extra steps, which are explained through comments. ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/jit_script_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof #The following creates an object "foo" of type ScriptModule #The new object has a function called "forward" @torch.jit.script def foo(x, y): return torch.sigmoid(x) + y #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "foo" foo.__name__ = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(foo, 'forward') x = torch.zeros(4,4).cuda() y = torch.ones(4,4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x, y) profiler.stop() print(z) ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/jit_script_method.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof class Foo(torch.jit.ScriptModule): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) @torch.jit.script_method def forward(self, input): return self.n*input + self.m #Initialize pyprof after the JIT step pyprof.nvtx.init() #Hook up the forward function to pyprof pyprof.nvtx.wrap(Foo, 'forward') foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x) profiler.stop() print(z) ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/jit_trace_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof def foo(x, y): return torch.sigmoid(x) + y x = torch.zeros(4,4).cuda() y = torch.ones(4,4).cuda() #JIT the function using tracing #This returns an object of type ScriptModule with a forward method. traced_foo = torch.jit.trace(foo, (x,y)) #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "traced_foo" traced_foo.__dict__['__name__'] = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(traced_foo, 'forward') with torch.autograd.profiler.emit_nvtx(): profiler.start() z = traced_foo(x, y) profiler.stop() print(z) ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/jit_trace_method.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof class Foo(torch.nn.Module): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) def forward(self, input): return self.n*input + self.m foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() #JIT the class using tracing traced_foo = torch.jit.trace(foo, x) #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "traced_foo" traced_foo.__dict__['__name__'] = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(traced_foo, 'forward') with torch.autograd.profiler.emit_nvtx(): profiler.start() z = traced_foo(x) profiler.stop() print(z) ================================================ FILE: KoSentenceT5/apex/pyprof/examples/jit/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSentenceT5/apex/pyprof/examples/lenet.py ================================================ #!/usr/bin/env python3 import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.profiler as profiler import torch.optim as optim from apex import pyprof pyprof.nvtx.init() class LeNet5(nn.Module): def __init__(self): super(LeNet5, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features with torch.autograd.profiler.emit_nvtx(): net = LeNet5().cuda() input = torch.randn(1, 1, 32, 32).cuda() out = net(input) target = torch.randn(10) # a dummy target, for example target = target.view(1, -1).cuda() # make it the same shape as output criterion = nn.MSELoss() # create your optimizer optimizer = optim.SGD(net.parameters(), lr=0.01) # in your training loop: optimizer.zero_grad() # zero the gradient buffers profiler.start() output = net(input) loss = criterion(output, target) loss.backward() optimizer.step() # Does the update profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/operators.py ================================================ #!/usr/bin/env python3 """ This file checks all Python operators. """ import sys import torch import torch.cuda.profiler as profiler import operator import inspect #Import and initialize pyprof from apex import pyprof pyprof.nvtx.init() X = 1024 Y = 1024 fa = torch.rand(X, Y).cuda() fb = torch.rand(X, Y).cuda() fc = torch.rand(X, Y).cuda() ia = torch.randint(0, 100, (X, Y)).cuda() ib = torch.randint(0, 100, (X, Y)).cuda() sa = torch.ones(1,1).cuda() sb = torch.ones(1,1).cuda() ba = fa.byte() unaryOps = ["abs", "__abs__", "neg", "__neg__",] invertOps = ["inv", "invert", "__inv__", "__invert__",] #imlemented only for byte tensors #pos, __pos__ is not implemented for tensors binaryOps = [] binaryOps += [ "lt", "__lt__", "le", "__le__", "eq", "__eq__", "ne", "__ne__", "ge", "__ge__", "gt", "__gt__" ] binaryOps += [ "add", "__add__", "sub", "__sub__", "mul", "__mul__", "floordiv", "__floordiv__", "truediv", "__truediv__", "pow", "__pow__", "mod", "__mod__"] binaryOps += [ "and_", "__and__", "or_", "__or__", "xor", "__xor__", "lshift", "__lshift__", "rshift", "__rshift__"] inplaceOps = [] inplaceOps += ["iadd", "__iadd__", "isub", "__isub__", "imul", "__imul__", "ifloordiv", "__ifloordiv__", "itruediv", "__itruediv__", "imod", "__imod__",] #ipow, __ipow__ is not implemented in pytorch inplaceOps += [ "iand", "__iand__", "ior", "__ior__", "ixor", "__ixor__", "ilshift", "__ilshift__", "irshift", "__irshift__",] matmulOps = [ "matmul", "__matmul__" ] inplacematmulOps = [ "imatmul", "__imatmul__" ] reverseIntBinaryOps = ["__radd__", "__rsub__", "__rmul__", "__rfloordiv__", "__rpow__",] reverseFloatBinaryOps = ["__radd__", "__rsub__", "__rmul__", "__rdiv__", "__rtruediv__", "__rfloordiv__", "__rpow__",] ''' TODO .concat(a, b) .__concat__(a, b) .contains(a, b) .__contains__(a, b) .countOf(a, b) .delitem(a, b) .__delitem__(a, b) .getitem(a, b) .__getitem__(a, b) .indexOf(a, b) .setitem(a, b, c) .__setitem__(a, b, c) .length_hint(obj, default=0) .iconcat(a, b) .__iconcat__(a, b) .index(a) .__index__(a) ''' #Context manager with torch.autograd.profiler.emit_nvtx(): #Start profiler profiler.start() for op in unaryOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ia) for op in invertOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ba) for op in binaryOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ia, ib) c = f(ia, 2) for op in inplaceOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) ia = f(ia, ib) ia = f(ia, 2) for op in matmulOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(fa, fb) for op in inplacematmulOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) fa = f(fa, fb) for op in reverseIntBinaryOps: assert hasattr(torch.Tensor, op) f = getattr(torch.Tensor, op) ia = f(ia, ib) for op in reverseFloatBinaryOps: assert hasattr(torch.Tensor, op) f = getattr(torch.Tensor, op) fa = f(fa, fb) ''' #c = fa[3] #c = fa[3][3] #c = torch.min(fa, 3) c = torch.sum(fa) c = torch.max(fa) c = -fa #fc[2][2] = fa[2][2] c = a_scalar and b_scalar c = a_scalar or b_scalar c = not a_scalar c = a is b c = a is not b ''' #Stop profiler profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/simple.py ================================================ #!/usr/bin/env python3 """ This simple file provides an example of how to - import the pyprof library and initialize it - use the emit_nvtx context manager - start and stop the profiler Only kernels within profiler.start and profiler.stop calls are profiled. To profile $ nvprof -f -o simple.sql --profile-from-start off ./simple.py """ import sys import torch import torch.cuda.profiler as profiler #Import and initialize pyprof from apex import pyprof pyprof.nvtx.init() a = torch.randn(5, 5).cuda() b = torch.randn(5, 5).cuda() #Context manager with torch.autograd.profiler.emit_nvtx(): #Start profiler profiler.start() c = a + b c = torch.mul(a,b) c = torch.matmul(a,b) c = torch.argmax(a, dim=1) c = torch.nn.functional.pad(a, (1,1)) #Stop profiler profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/user_annotation/README.md ================================================ Nvidia NVTX range markers (https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) are a useful tool to capture and observe events and code ranges etc. Using PyTorch APIs e.g, `torch.cuda.nvtx.range_push("xxx")` and `torch.cuda.nvtx.range_pop()` users can easily add their own NVTX range markers. These markers can then be observed in the Nvidia Visual Profiler (NVVP). While inserting NVTX markers (strings), if the users follow a specific string pattern `"layer:your_string_here"` e.g. `"layer:conv1"` or `"layer:encoder_layer_3_self_attention`, then `pyprof` will display the strings `conv1` and `encoder_layer_3_self_attention` next to the associated kernels in the output of `prof.py` when used with the `-c layer` option. NVTX range markers can be nested and if users follow the above string pattern, the output of `prof.py` will show all the markers associated with a kernel. The file `resnet.py` (a simplified version of the torchvision model) shows an example of how users can add (nested) NVTX markers with information which can greatly aid in understanding and analysis of networks. Note that the pattern `"layer:your_string_here"` was chosen to aid information extraction by `pyprof`. The tool will work seamlessly even if there are other markers or no markers at all. ### To run ```sh nvprof -fo resnet.sql --profile-from-start off python resnet.py parse.py resnet.sql > resnet.dict prof.py --csv -c idx,layer,dir,mod,op,kernel,params,sil resnet.dict ``` The file `resnet.sql` can also be opened with NVVP as usual. ================================================ FILE: KoSentenceT5/apex/pyprof/examples/user_annotation/resnet.py ================================================ #!/usr/bin/env python3 """ An example showing use of nested NVTX markers. """ import torch import torch.nn as nn import torch.cuda.profiler as profiler import torch.cuda.nvtx as nvtx from apex import pyprof pyprof.nvtx.init() def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(nn.Module): expansion = 4 count = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = int(planes * (base_width / 64.)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.id = Bottleneck.count Bottleneck.count += 1 def forward(self, x): identity = x nvtx.range_push("layer:Bottleneck_{}".format(self.id)) nvtx.range_push("layer:Conv1") out = self.conv1(x) nvtx.range_pop() nvtx.range_push("layer:BN1") out = self.bn1(out) nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_push("layer:Conv2") out = self.conv2(out) nvtx.range_pop() nvtx.range_push("layer:BN2") out = self.bn2(out) nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_push("layer:Conv3") out = self.conv3(out) nvtx.range_pop() nvtx.range_push("layer:BN3") out = self.bn3(out) nvtx.range_pop() if self.downsample is not None: nvtx.range_push("layer:Downsample") identity = self.downsample(x) nvtx.range_pop() nvtx.range_push("layer:Residual") out += identity nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_pop() return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, groups=1, width_per_group=64, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def forward(self, x): nvtx.range_push("layer:conv1_x") x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) nvtx.range_pop() nvtx.range_push("layer:conv2_x") x = self.layer1(x) nvtx.range_pop() nvtx.range_push("layer:conv3_x") x = self.layer2(x) nvtx.range_pop() nvtx.range_push("layer:conv4_x") x = self.layer3(x) nvtx.range_pop() nvtx.range_push("layer:conv5_x") x = self.layer4(x) nvtx.range_pop() x = self.avgpool(x) x = torch.flatten(x, 1) nvtx.range_push("layer:FC") x = self.fc(x) nvtx.range_pop() return x def resnet50(): return ResNet(Bottleneck, [3, 4, 6, 3]) #Create model net = resnet50().cuda().half() net.train() #Create optimizer criterion = nn.CrossEntropyLoss().cuda() optimizer = torch.optim.SGD(net.parameters(), lr = 0.01, momentum=0.9) #Create synthetic input and label x = torch.rand(32, 3, 224, 224).cuda().half() target = torch.empty(32, dtype=torch.long).random_(1000).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() profiler.stop() ================================================ FILE: KoSentenceT5/apex/pyprof/examples/user_annotation/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo --profile-from-start off $sql python $f" nvprof -fo $sql --profile-from-start off python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict #$prof -w 130 $dict $prof --csv -c idx,layer,dir,mod,op,kernel,params,sil $dict \rm $sql $dict done ================================================ FILE: KoSentenceT5/apex/pyprof/nvtx/__init__.py ================================================ from .nvmarker import init from .nvmarker import add_wrapper as wrap ================================================ FILE: KoSentenceT5/apex/pyprof/nvtx/nvmarker.py ================================================ """ This file intercepts (monkey patches) the following functions and adds NVTX markers. torch.* torch.Tensor.* torch.nn.functional.* torch.nn.*.forward The NVTX markers (one or more) contain the following information call trace (a list of file_name:line_number) extra_repr() from torch.nn modules module/class name function name inputs (args and kwargs) scalar: name, type and value tensor: name, shape and datatype numpy: name, shape and datatype list/tuple: a sequence of scalars or tensors or numpy arrays """ import torch import torch.cuda.nvtx as nvtx import numpy import inspect as ins import traceback import math def isfunc(mod, f): assert hasattr(mod, f) attr = getattr(mod, f) #Ignore functions like _add if (len(f) >= 2): if f[0] == "_" and f[1] != "_": return False #Ignore functions from this list ignore = ['__all__', '__array__', '__array_priority__', '__array_wrap__', '__bool__', '__builtins__', '__cached__', '__class__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__file__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__index__', '__init__', '__init_subclass__', '__iter__', '__len__', '__loader__', '__module__', '__name__', '__new__', '__nonzero__', '__package__', '__path__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__spec__', '__str__', '__subclasshook__', '__version__', '__weakref__'] #Add functions to this list if they cause recursion ignore += ['size', 'tolist', 'dim', 'is_storage', 'item'] if f in ignore: return False return ins.ismethod(attr) or ins.isfunction(attr) or ins.ismethoddescriptor(attr) or ins.isbuiltin(attr) def traceMarker(stack): d = {} cadena = [] for i in range(len(stack)-1): fi = stack[i] t = "{}:{}".format(fi.filename, fi.lineno) cadena.append(t) d['traceMarker'] = cadena return str(d) def modMarker(mod, fn_name, args): """ Returns the stringified extra_repr() of a module. """ assert(fn_name == 'forward') assert(len(args) > 0) d = {} d['mod'] = mod.__name__ d['strRepr'] = args[0].extra_repr() return str(d) def add_wrapper(mod, fn_name): assert isfunc(mod, fn_name) # Get a pointer to the original function func = getattr(mod, fn_name) # Check if the mod has a string representation # and is not a Script or Traced module (used by JIT) s = hasattr(mod, "extra_repr") and (type(mod) is not torch.jit.ScriptModule) and (type(mod) is not torch.jit.TopLevelTracedModule) def wrapper_func(*args, **kwargs): # Extract the stacktrace stack = traceback.extract_stack() # Push trace marker nvtx.range_push(traceMarker(stack)) # Push module marker if s: m = modMarker(mod, fn_name, args) nvtx.range_push(m) # Create and push argument marker cadena = argMarker(mod, fn_name, args, kwargs) nvtx.range_push(cadena) # Call the original function result = func(*args, **kwargs) # Pop argumet marker nvtx.range_pop() # Pop module marker if s: nvtx.range_pop() # Pop trace marker nvtx.range_pop() return result setattr(mod, fn_name, wrapper_func) def argMarker(mod, op, args, kwargs): #For this function args is a tuple and kwargs is a dict def tensor(arg, name=""): a = {} a['name'] = name a['type'] = "tensor" a['shape'] = tuple(arg.size()) a['dtype'] = str(arg.dtype).split(".")[-1] cadena['args'].append(a) def ndarray(arg, name=""): a = {} a['name'] = name a['type'] = "ndarray" a['shape'] = arg.shape a['dtype'] = str(arg.dtype).split(".")[-1] cadena['args'].append(a) def seq(arg, name=""): assert issequence(arg) a = {} a['name'] = name if isinstance(arg, list): a['type'] = "list" a['value'] = arg else: a['type'] = "tuple" # The arg could be torch.Size, which is a subclass of tuple # Therefore, explicitly convert to tuple a['value'] = tuple(arg) cadena['args'].append(a) def scalar(arg, name=""): a = {} a['name'] = name a['type'] = type(arg).__name__ #handle the case when the argument is +/- inf or nan if arg == float('inf'): a['value'] = "inf" elif arg == float('-inf'): a['value'] = "-inf" elif isinstance(arg, float) and math.isnan(arg): a['value'] = "nan" else: a['value'] = arg cadena['args'].append(a) def isscalar(arg): return (type(arg) is int) or (type(arg) is float) or (type(arg) is bool) or (arg is None) or (type(arg) is str) def issequence(arg): return isinstance(arg, list) or isinstance(arg, tuple) def foo(args, name): #args should be an iterable sequence e.g. list or tuple for arg in args: if isinstance(arg, torch.Tensor): if arg.dim() == 0: scalar(arg.item(), name) else: tensor(arg, name) elif isinstance(arg, numpy.ndarray): ndarray(arg, name) elif (isscalar(arg)): scalar(arg, name) elif issequence(arg): if (len(arg) == 0) or isscalar(arg[0]): #An empty sequence or a sequence of scalars seq(arg, name) else: # A sequence of tensors or numpy arrays foo(arg, name) ''' else: print("The following arg is none of Tensor, numpy array, scalar but a %s" % (str(type(arg)))) print("Mod: %s" % str(mod.__name__)) print("Op: %s" % str(op)) print(dir(arg)) ''' cadena = {} cadena['mod'] = mod.__name__ cadena['op'] = op cadena['args'] = [] foo(args, "") for k,v in kwargs.items(): foo((v,), k) return str(cadena) def patchClass(cls): for f in dir(cls): if isfunc(cls, f): add_wrapper(cls, f) def init(): string = "\n\nPyprof has been moved to its own dedicated repository and will " + \ "soon be removed from Apex. Please visit\n" + \ "https://github.com/NVIDIA/PyProf\n" + \ "for the latest version.\n\n" # print regardless of warning state print(string) print("Initializing NVTX monkey patches") for cls in [torch, torch.Tensor, torch.nn.functional,]: patchClass(cls) for cls in [torch.nn.RNN, torch.nn.RNNCell, torch.nn.LSTM, torch.nn.LSTMCell, torch.nn.GRU, torch.nn.GRUCell]: if isfunc(cls, 'forward'): add_wrapper(cls, 'forward') print("Done with NVTX monkey patching") ================================================ FILE: KoSentenceT5/apex/pyprof/parse/__init__.py ================================================ ================================================ FILE: KoSentenceT5/apex/pyprof/parse/__main__.py ================================================ import warnings try: from .parse import main except ImportError as e: warnings.warn("Did you make sure to install PyProf dependencies by using the --pyprof flag during Apex installation?)") raise e if __name__ == '__main__': main() ================================================ FILE: KoSentenceT5/apex/pyprof/parse/db.py ================================================ import sys, sqlite3 class DB(object): """ This class provides functions for DB operations with exception handling. """ def __init__(self, dbFile): try: conn = sqlite3.connect(dbFile) conn.row_factory = sqlite3.Row c = conn.cursor() except: print("Error opening {}".format(dbFile)) sys.exit(1) self.conn = conn self.c = c def select(self, cmd): try: self.c.execute(cmd) #rows = self.c.fetchall() rows = [dict(row) for row in self.c.fetchall()] except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) #print(rows) return rows def insert(self, cmd, data): try: self.c.execute(cmd, data) except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) def execute(self, cmd): try: self.c.execute(cmd) except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) def commit(self): self.conn.commit() def close(self): self.c.close() self.conn.close() ================================================ FILE: KoSentenceT5/apex/pyprof/parse/kernel.py ================================================ import cxxfilt, struct, binascii #Helper functions def demangle(name): """ Demangle a C++ string """ return cxxfilt.demangle(name) def encode_object_id(pid, tid): """ Given process id (pid) and thread id (tid), return the object id. object id = pid (little endian 4 bytes) + tid (little endian 8 bytes) """ objId = struct.pack(' start, "This assertion can fail for very large profiles. It usually fails when start = end = 0." self.kStartTime = start self.kEndTime = end self.kDuration = end - start assert (start > Kernel.profStart) self.device = int(info['deviceId']) self.stream = int(info['streamId']) self.grid = (info['gridX'], info['gridY'], info['gridZ']) self.block = (info['blockX'], info['blockY'], info['blockZ']) self.timeOffset = Kernel.profStart def setKernelName(self, name): cadena = demangle(name) self.kLongName = cadena self.kShortName = getShortName(cadena) def setRunTimeInfo(self, info): start, end, pid, tid = info self.rStartTime = start self.rEndTime = end self.rDuration = end - start self.pid = pid self.tid = tid self.objId = encode_object_id(pid, tid) def setMarkerInfo(self, info): self.layerMarkers, self.traceMarkers, self.reprMarkers, self.pyprofMarkers, self.seqMarkers, self.otherMarkers, self.altMarkers, self.seqId, self.altSeqId, self.layer = info self.subSeqId = 0 def setDirection(self): """ Set direction (fprop, bprop) based on PyTorch sequence markers. It is a heuristic and not a foolproof method. """ if any("Backward, seq = " in x for x in self.seqMarkers) or \ any("backward, seq = " in x for x in self.seqMarkers) or \ any("Backward0, seq = " in x for x in self.seqMarkers): self.dir = "bprop" else: self.dir = "fprop" def setOp(self): """ Detect and set the class/module (mod) and operation (op) of the kernel e.g. torch.nn.functional / linear, torch / sigmoid. The lookup sequence we use is NVTX markers inserted by pyprof NVTX markers inserted by PyTorch in bprop NVTX markers inserted by PyTorch in fprop It is a heuristic and not a foolproof method. """ def sanitize(name): name = name.replace("torch","") \ .replace("autograd","") \ .replace("_backward","") \ .replace("::","") \ .replace("jit","") \ .replace("(anonymous namespace)","") head, sep, tail = name.partition("Backward") return head #Check pyprof markers for m in self.pyprofMarkers: assert ("mod" in m) and ("op" in m) and ("args" in m) t = eval(m) self.op.append(t['op']) self.mod.append(t['mod']) if len(self.op): return #Check bprop kernel markers for m in self.seqMarkers: if ("backward, seq = " in m) or ("Backward, seq = " in m): op = m.split(",")[0] op = sanitize(op) self.op.append(op) self.mod.append('na') if len(self.op): return #Check markers with "seq = " for m in self.seqMarkers: if ", seq = " in m: op = m.split(",")[0] self.op.append(op) self.mod.append('na') if len(self.op): return #If nothing else if len(self.otherMarkers): self.op.append(self.otherMarkers[0]) self.mod.append('na') def print(self): """ Print kernel information. This is used by prof.py. """ a = lambda: None a.kShortName = self.kShortName a.kDuration = self.kDuration #a.layerMarkers = self.layerMarkers a.layer = self.layer a.trace = self.traceMarkers a.reprMarkers = self.reprMarkers a.marker = self.pyprofMarkers a.seqMarker = self.seqMarkers a.seqId = self.seqId a.subSeqId = self.subSeqId a.altSeqId = self.altSeqId a.dir = self.dir a.mod = self.mod a.op = self.op a.tid = self.tid a.device = self.device a.stream = self.stream a.grid = self.grid a.block = self.block a.kLongName = self.kLongName print(a.__dict__) ================================================ FILE: KoSentenceT5/apex/pyprof/parse/nvvp.py ================================================ import sys class NVVP(object): """ This class gets kernel information from the SQL (nvvp) database. """ driverT = "CUPTI_ACTIVITY_KIND_DRIVER" runtimeT = "CUPTI_ACTIVITY_KIND_RUNTIME" kernelT = "CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL" markerT = "CUPTI_ACTIVITY_KIND_MARKER" stringT = "StringTable" def __init__(self, db): self.db = db self.markerId = 0 def getProfileStart(self): """ Get the profile start time """ profStart = sys.maxsize for table in [self.driverT, self.runtimeT, self.kernelT, self.markerT]: colname = "timestamp" if table is self.markerT else "start" cmd = "select {} from {} ORDER BY {} ASC LIMIT 1".format(colname, table, colname) result = self.db.select(cmd) assert(len(result) <= 1) if (len(result) == 1): assert(colname in result[0]) t = result[0][colname] if (t < profStart): profStart = t assert(profStart < sys.maxsize) return profStart def getString(self, id_): """ Get the string associated with an id. """ cmd = "select value from {} where _id_ = {}".format(self.stringT, id_) result = self.db.select(cmd) assert (len(result) == 1) return result[0]['value'] def createMarkerTable(self): """ Create a temporary table and index it to speed up repeated SQL quesries. The table is an INNER JOIN of CUPTI_ACTIVITY_KIND_MARKER with itself. """ cmd = 'CREATE TEMPORARY TABLE marker AS SELECT \ a._id_ as id, \ a.timestamp AS startTime, \ b.timestamp AS endTime, \ HEX(a.objectId) AS objectId, \ a.name AS name \ FROM {} AS a INNER JOIN {} AS b ON \ a.id = b.id and \ a.flags = 2 and b.flags = 4'.format(self.markerT, self.markerT) self.db.execute(cmd) self.db.execute('CREATE INDEX start_index ON marker (startTime)') self.db.execute('CREATE INDEX end_index ON marker (endTime)') self.db.execute('CREATE INDEX id_index ON marker (id)') def getCPUInfo(self, corrId): """ Given the correlation id, get CPU start, end, thread id, process id. The information can be in the runtime table or the driver table. """ #First look in the runtime table cmd = "select start,end,processId,threadId from {} where correlationId={}".format(self.runtimeT, corrId); result = self.db.select(cmd) assert (len(result) <= 1) if (len(result) == 0): #Look in the driver table cmd = "select start,end,processId,threadId from {} where correlationId={}".format(self.driverT, corrId); result = self.db.select(cmd) assert (len(result) == 1) info = result[0] start = info['start'] end = info['end'] pid = info['processId'] tid = info['threadId'] tid = tid & 0xffffffff #convert to unsigned assert (end > start) return [start, end, pid, tid] def getKernelInfo(self): """ Get GPU kernel info """ cmd = "select name,correlationId,start,end,deviceId,streamId,gridX,gridY,gridZ,blockX,blockY,blockZ from {}".format(self.kernelT) result = self.db.select(cmd) return result def getMarkerInfo(self, objId, startTime, endTime): """ This function first finds all NVTX markers encapsulating a runtime / driver kernel launch. It then splits the markers into many lists. layerMarkers : User added NVTX markers traceMarkers : Call trace markers (inserted by pyprof) reprMarkers : Markers containing the extra_repr() of a module (inserted by pyprof) pyprofMarkers: Markers containing args and kwargs (tensor shape, datatype etc.) seqMarkers : Markers containing PyTorch internal sequence markers (inserted by PyTorch) altSeqMarkers: Markers inserted by PyTorch between two kernel launches. Needs better explanation. otherMarkers : Markers not in either of the above categories. We extract seqId from the seq and altSeq markers. The seqId is used in bprop. We also extract information from the layerMarkers. """ layerMarkers = [] traceMarkers = [] reprMarkers = [] pyprofMarkers = [] seqMarkers = [] otherMarkers = [] altSeqMarkers = [] bprop = False #Helper functions def delete(objId, sTime): """ Delete rows from the temporary SQL table which are no longer required. This speeds up future queries. """ margin = 0 cmd = 'DELETE FROM marker WHERE objectId = "{}" AND endTime < {}'.format(objId, sTime - margin) #cmd = 'DELETE FROM marker WHERE endTime < {}'.format(sTime - margin) self.db.execute(cmd) def getLayerName(mlist): """ Get layer names from layer marker list. """ layers = [] assert(type(mlist) == list) for m in mlist: assert("layer:" in m) l = m.split(":")[1] layers.append(l) return layers def getSeqId(mlist): """ Get sequence ids from seq / alt seq marker list. """ ids = [] assert(type(mlist) == list) for m in mlist: assert(", seq = " in m) seq = int(m.split("=")[1]) ids.append(seq) #Remove duplicates ids = list(set(ids)) ids.sort() return ids def seqcompare(elem): """ Sorting function for sequence markers """ assert (", seq = " in elem) #sort by sequence id and then the string l = elem.split(" = ") return l[1] + l[0] def prune(mlist): """ Remove markers with the same seqId and if the strings are similar. This function works on a sorted sequence. """ assert (type(mlist) == list) assert (len(mlist)) a = mlist[0:1] for i in range(1,len(mlist)): m = mlist[i] pm = mlist[i-1] name,seq = m.split(",") pname,pseq = pm.split(",") similar = (name in pname) or (pname in name) if (seq == pseq) and similar: continue else: a.append(m) return a def filterTrace(mlist): """ Filter trace markers to remove certain file names. """ assert (type(mlist) == list) if len(mlist) == 0: return mlist mlist = mlist[-1] #The last stack trace will be a super set. mlist = eval(mlist) mlist = mlist['traceMarker'] assert (type(mlist) == list) mlist = list(filter(lambda x : "/torch/nn/modules/" not in x, mlist)) mlist = list(filter(lambda x : "/torch/nn/functional.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/tensor.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/autograd/__init__.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/_jit_internal.py" not in x, mlist)) mlist = list(filter(lambda x : "/pyprof/nvtx/nvmarker.py" not in x, mlist)) mlist = list(filter(lambda x : "/apex/optimizers/" not in x, mlist)) mlist = list(filter(lambda x : "/torch/_utils.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/optim/" not in x, mlist)) return mlist #Find all encapsulating markers cmd = 'SELECT id,name from marker where \ objectId = "{}" and \ startTime < {} and \ endTime > {} \ ORDER BY startTime ASC'.format(objId, startTime, endTime) result = self.db.select(cmd) #Bin markers into different lists for r in result: m = self.getString(r['name']) #Hack: If its a known gradient checkpointing marker, ignore it. if m.find("CheckpointFunctionBackward") >= 0: continue if ("_backward, seq =" in m) or ("Backward, seq =" in m) or ("Backward0, seq =" in m): bprop = True if ("mod" in m) and ("op" in m) and ("args" in m) and ("type" in m): pyprofMarkers.append(m) elif ("layer:" in m): layerMarkers.append(m) elif ("traceMarker" in m): traceMarkers.append(m) elif ("strRepr" in m): reprMarkers.append(m) elif (", seq = " in m): seqMarkers.append(m) else: otherMarkers.append(m) #Remove duplicates, sort and prune seqMarkers if (len(seqMarkers)): seqMarkers = list(set(seqMarkers)) seqMarkers.sort(key=seqcompare) seqMarkers = prune(seqMarkers) #Remove duplicates from otherMarkers otherMarkers = list(set(otherMarkers)) #Get markers with seq id (inserted by PyTorch) from the previous kernel to the present kernel #Only for fprop kernels if (len(result) and not bprop): loId = self.markerId hiId = result[-1]['id'] self.markerId = hiId #Get markers between loId and hiId cmd = 'SELECT id,name from marker where objectId = "{}" and id > {} and id < {} ORDER BY startTime ASC'.format(objId, loId, hiId) result1 = self.db.select(cmd) for r in result1: m = self.getString(r['name']) #Get only markers with seq id if (", seq=" in m): altSeqMarkers.append(m) #Remove duplicates, sort and prune altSeqMarkers if (len(altSeqMarkers)): altSeqMarkers = list(set(altSeqMarkers)) altSeqMarkers.sort(key=seqcompare) altSeqMarkers = prune(altSeqMarkers) delete(objId, startTime) return layerMarkers, filterTrace(traceMarkers), reprMarkers, pyprofMarkers, seqMarkers, otherMarkers, altSeqMarkers, getSeqId(seqMarkers), getSeqId(altSeqMarkers), getLayerName(layerMarkers) ================================================ FILE: KoSentenceT5/apex/pyprof/parse/parse.py ================================================ #!/usr/bin/env python3 """ Parse the SQL db and print a dictionary for every kernel. """ import sys import argparse from tqdm import tqdm from .db import DB from .kernel import Kernel from .nvvp import NVVP def parseArgs(): parser = argparse.ArgumentParser(prog=sys.argv[0], description="Parse SQL (nvvp) db.") parser.add_argument("file", type=str, default=None, help="SQL db (nvvp) file.") args = parser.parse_args() return args def main(): args = parseArgs() db = DB(args.file) nvvp = NVVP(db) kInfo = nvvp.getKernelInfo() if len(kInfo) == 0: print("Found 0 kernels. Exiting.", file=sys.stderr) db.close() sys.exit(0) else: print("Found {} kernels. Getting info for each kernel.".format(len(kInfo)), file=sys.stderr) nvvp.createMarkerTable() prevSeqId = -1 prevSubSeqId = -1 prevOp = "na" Kernel.profStart = nvvp.getProfileStart() for i in tqdm(range(len(kInfo)), ascii=True): info = kInfo[i] k = Kernel() #Set kernel info k.setKernelInfo(info) #Get, set kernel name name = nvvp.getString(k.kNameId) k.setKernelName(name) #Get runtime info info = nvvp.getCPUInfo(k.corrId) k.setRunTimeInfo(info) #Get and set marker and seqid info info = nvvp.getMarkerInfo(k.objId, k.rStartTime, k.rEndTime) k.setMarkerInfo(info) #If the seqId contains both 0 and non zero integers, remove 0. if any(seq != 0 for seq in k.seqId) and (0 in k.seqId): k.seqId.remove(0) #Set direction (it uses seq id) k.setDirection() #Set op k.setOp() #The following code is based on heuristics. #TODO: Refactor. #Assign subSeqId, adjust seqId and altSeqId #seqId can be 0. #A kernel can have multiple seqIds both in fprop and bprop. #In bprop, seqIds might not decrease monotonically. I have observed a few blips. if len(k.seqId): assert (k.dir in ["fprop", "bprop"]) if (k.dir == "fprop"): #Check if there is a sequence id larger than the previous inc = (k.seqId[-1] > prevSeqId) if inc: currSeqId = [x for x in k.seqId if x > prevSeqId][0] else: currSeqId = prevSeqId else: currSeqId = k.seqId[0] #if ((currSeqId == prevSeqId) and (k.op == prevOp)): if ((currSeqId == prevSeqId) and (k.op == prevOp)) or ((k.op[0] == "forward") and (k.op == prevOp) and (k.mod[0] in ["LSTMCell", "GRUCell", "RNNCell"])): #The second condition is to trap cases when pytorch does not use cudnn for a LSTMCell. k.subSeqId = prevSubSeqId + 1 prevSeqId = currSeqId prevSubSeqId = k.subSeqId prevOp = k.op #Keep currSeqId in k.seqId, move everything else to k.altSeqId for s in k.seqId: if s != currSeqId: k.seqId.remove(s) k.altSeqId.append(s) for s in k.altSeqId: if s == currSeqId: k.altSeqId.remove(s) k.altSeqId = list(set(k.altSeqId)) if (len(k.altSeqId)): (k.altSeqId).sort() k.print() db.close() if __name__ == '__main__': main() ================================================ FILE: KoSentenceT5/apex/pyprof/prof/__init__.py ================================================ from . import data, prof ================================================ FILE: KoSentenceT5/apex/pyprof/prof/__main__.py ================================================ import warnings try: from .prof import main except ImportError as e: warnings.warn("Did you make sure to install PyProf dependencies by using the --pyprof flag during Apex installation?") raise e if __name__ == '__main__': main() ================================================ FILE: KoSentenceT5/apex/pyprof/prof/activation.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Activation(OperatorLayerBase): """ This class handles the various activation functions. """ ops = ["celu", "elu", "elu_", "hardshrink", "hardtanh", "hardtanh_", "leaky_relu", "leaky_relu_", "logsigmoid", "prelu", "relu", "relu_", "relu6", "rrelu", "rrelu_", "selu", "sigmoid", "softplus", "softshrink", "softsign", "tanh", "tanhshrink", "threshold", "threshold_"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch.nn.functional", "torch", "Tensor"]) #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) >= 1) arg = args[0] assert (arg['type'] == "tensor") self.i = arg self.dir = d.dir def params(self): p = OrderedDict([('T', self.i['shape']),('type', self.i['dtype'])]) return p def flops(self): direction = self.dir tensor = self.i['shape'] t = self.i['dtype'] # TODO: revise elems = Utility.numElems(tensor) return elems def bytes(self): direction = self.dir tensor = self.i['shape'] t = self.i['dtype'] elems = Utility.numElems(tensor) elems = elems * (2 if direction == "fprop" else 3) return elems * Utility.typeToBytes(t) def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/base.py ================================================ from abc import ABC, abstractmethod class OperatorLayerBase(ABC): """ Base class for all layers and operators. Every derived class should have the following functions. """ @abstractmethod def tc(self): """ Tensor core usage by the kernel. Return "1" (yes), "0" (no, but possible), "-" (not applicable) """ pass @abstractmethod def params(self): """ Kernel parameters to be printed. """ pass @abstractmethod def flops(self): """ Note that 1 FMA = 2 flops. """ pass @abstractmethod def bytes(self): pass @abstractmethod def mod(self): """ Name of the module/class e.g. torch.nn.functional. """ pass @abstractmethod def op(self): """ Name of the operator e.g. sigmoid. """ pass ================================================ FILE: KoSentenceT5/apex/pyprof/prof/blas.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase import numpy as np TC_GEMMS = ["884gemm", "1688gemm"] class Addmm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor",]) assert (op in ["addmm", "addmm_",]) #Get alpha and beta alpha = 1 beta = 1 if any(x['name'] == 'alpha' for x in args): alpha = list(filter(lambda x : x['name'] == "alpha", args))[0] alpha = alpha['value'] if any(x['name'] == 'beta' for x in args): beta = list(filter(lambda x : x['name'] == "beta", args))[0] beta = beta['value'] self.alpha = alpha self.beta = beta #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) == 3) C,A,B = args m,k1 = A['shape'] k2,n = B['shape'] assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] t3 = C['dtype'] assert(t1 == t2 == t3) self.A = A self.B = B self.C = C self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name return def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): return self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ def params(self): p = OrderedDict([('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p class Bmm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") and (op == "bmm") #Filter out named params (kwargs) args = list(filter(lambda x : x['name'] == "", args)) assert (len(args) == 2) A,B = args b1,m,k1 = A['shape'] b2,k2,n = B['shape'] assert (b1 == b2) assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) self.A = A self.B = B self.b = b1 self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def params(self): #p = OrderedDict([('A', A['shape']), ('B', B['shape']), ('type', t1)]) p = OrderedDict([('B',self.b), ('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p def flops(self): return self.b * self.m * self.n * self.k * 2 def bytes(self): b, m, n, k = self.b, self.m, self.n, self.k return Utility.typeToBytes(self.type) * b * (m*n + m*k + n*k) def op(self): return self.op_ def mod(self): return self.mod_ class Matmul(OperatorLayerBase): NON_GEMM = ["kernelPointwiseApply2", "reduce_1Block_kernel", "elementwise_kernel"] NON_TC = NON_GEMM + ["dot_kernel"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.name = d.name self.sub = d.sub assert ((mod == "torch") and (op == "matmul")) or ((mod == "Tensor") and (op == "__matmul__")) assert (len(args) == 2) assert any([x in d.name for x in Matmul.NON_TC + ["gemm", "gemv"]]) A,B = args t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) A = A['shape'] B = B['shape'] self.A = A self.B = B self.type = t1 # batch, MNK if (len(A) == 1) and (len(B) == 1): #dot product assert (A[0] == B[0]) self.b = (1,) self.m = 1 self.n = 1 self.k = A[0] elif (len(A) == 2) and (len(B) == 2): #gemm m,k1 = A k2,n = B assert(k1 == k2) self.b = (1,) self.m = m self.n = n self.k = k1 elif (len(A) == 1) and (len(B) == 2): #vector matrix k1 = A[0] k2,n = B assert(k1 == k2) self.b = (1,) self.m = 1 self.n = n self.k = k1 elif (len(A) == 2) and (len(B) == 1): #gemv m,k1 = A k2 = B[0] assert (k1 == k2) self.b = (1,) self.m = m self.n = 1 self.k = k1 elif (len(A) == 1) and (len(B) > 2): assert (A[0] == B[-2]) self.b = B[0:-2] self.m = 1 self.n = B[-1] self.k = B[-2] elif (len(B) == 1) and (len(A) > 2): assert (B[0] == A[-1]) self.b = A[0:-2] self.m = A[-2] self.n = 1 self.k = A[-1] else: assert (len(A) >= 2) assert (len(B) >= 2) assert (A[-1] == B[-2]) self.m = A[-2] self.n = B[-1] self.k = A[-1] aa = np.empty(A[0:-2]) bb = np.empty(B[0:-2]) self.b = np.broadcast(aa, bb).shape def params(self): return OrderedDict([('A', self.A), ('B', self.B), ('type', self.type)]) def tc(self): if self.name in Matmul.NON_TC: return "-" else: for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): # TODO: check bytes for non-GEMM cases if self.name in Matmul.NON_GEMM: return 2 * Utility.typeToBytes(self.type) * Utility.numElems(self.A) #could be B as well else: m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): # TODO: calculate actual FLOPs. At least we're not saying it's GEMM FLOPs for now. if self.name in Matmul.NON_GEMM: return 0 else: return Utility.numElems(self.b) * self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ class Mm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") and (op == "mm") assert (len(args) == 2) A,B = args m,k1 = A['shape'] k2,n = B['shape'] assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) self.A = A self.B = B self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name return def params(self): p = OrderedDict([('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): return self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/conv.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Conv(OperatorLayerBase): """ # N = batch size # C,H,W = input channels, height, width # K,P,Q = output channels, height, width # R,S = filter height, width # g = groups """ #todo: refine winograd and FFT convAuxList = ["nchwToNhwc", "nhwcToNchw", "OffsetsKernel",] winoAuxList = ["generateWinogradTilesKernel", "winogradWgradData", "winogradWgradOutput", "winogradWgradDelta"] fftAuxList = ["compute_gemm_pointers", "flip_filter", "fft2d_r2c_", "fft2d_c2r_", "fft1d_r2c", "fft1d_c2r"] miscAuxList = ["scaleTensor_kernel",] convList = ["_s884cudnn_", "_s1688cudnn_", "_scudnn_", "2d_grouped_direct_kernel", "cudnn::detail::implicit_convolve_sgemm", "cudnn::detail::dgrad2d_alg1_1", "cudnn::detail::wgrad_alg0_engine", "cudnn::detail::dgrad_engine", "dgrad_1x1_stride_2x2", "spatialDepthwiseConvolutionUpdateOutput"] winoList = ["winograd3x3Kernel", "_sgemm_"] fftList = ["fermiPlusCgemmLDS128_batched", "_gcgemm_",] miscList = [] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.dir = d.dir self.name = d.name self.sub = d.sub assert (mod == "torch.nn.functional") assert (op in ["conv1d", "conv2d"]) length = len(args) assert (length >= 2) and (length <= 7) i,w = args[0], args[1] assert (i['type'] == "tensor") assert (w['type'] == "tensor") #ignore bias if (length >= 4) and (args[3]['name'] == ""): s = args[3] elif any(x['name'] == 'stride' for x in args): s = list(filter(lambda x : x['name'] == 'stride', args))[0] else: s = {'name': 'stride', 'type': 'int', 'value': 1} if (length >= 5) and (args[4]['name'] == ""): p = args[4] elif any(x['name'] == 'padding' for x in args): p = list(filter(lambda x : x['name'] == 'padding', args))[0] else: p = {'name': 'padding', 'type': 'int', 'value': 0} if (length >= 6) and (args[5]['name'] == ""): d = args[5] elif any(x['name'] == 'dilation' for x in args): d = list(filter(lambda x : x['name'] == 'dilation', args))[0] else: d = {'name': 'dilation', 'type': 'int', 'value': 1} if (length == 7) and (args[6]['name'] == ""): g = args[6] elif any(x['name'] == 'groups' for x in args): g = list(filter(lambda x : x['name'] == 'groups', args))[0] else: g = {'name': 'groups', 'type': 'int', 'value': 1} if op == "conv1d": assert (len(i['shape']) == 3) assert (len(w['shape']) == 3) assert (i['dtype'] == w['dtype']) N, C1, W = i['shape'] K, C2, S = w['shape'] assert (C1 == C2) p = p['value'] if Utility.isscalar(p['type']) else p['value'][0] s = s['value'] if Utility.isscalar(s['type']) else s['value'][0] d = d['value'] if Utility.isscalar(d['type']) else d['value'][0] g = g['value'] assert (g == 1) H = 1 R = 1 P = 1 + (H - (((R-1))+1)) Q = 1 + (W + 2*p - (((S-1)*d)+1))/s P = int(P) Q = int(Q) if (H == 1): assert (P == 1) if (W == 1): assert (Q == 1) self.N = N self.C = C1 self.H = H self.W = W self.K = K self.P = P self.Q = Q self.R = R self.S = S self.ph = 0 self.pw = p self.U = 1 self.V = s self.dh = 1 self.dw = d self.g = g self.type = i['dtype'] elif op == "conv2d": assert (len(i['shape']) == 4) assert (len(w['shape']) == 4) assert (i['dtype'] == w['dtype']) N, C1, H, W = i['shape'] K, C2, R, S = w['shape'] if Utility.isscalar(p['type']): ph = pw = p['value'] else: assert (p['type'] == "tuple") ph, pw = p['value'] if Utility.isscalar(s['type']): sh = sw = s['value'] else: assert (s['type'] == "tuple") sh, sw = s['value'] if Utility.isscalar(d['type']): dh = dw = d['value'] else: assert (d['type'] == "tuple") dh, dw = d['value'] g = g['value'] assert (g >= 1) assert (C1 == C2*g) P = 1 + (H + 2*ph - (((R-1)*dh)+1))/sh Q = 1 + (W + 2*pw - (((S-1)*dw)+1))/sw P = int(P) Q = int(Q) if (H == 1): assert (P == 1) if (W == 1): assert (Q == 1) self.N = N self.C = C1 self.H = H self.W = W self.K = K self.P = P self.Q = Q self.R = R self.S = S self.ph = ph self.pw = pw self.U = sh self.V = sw self.dh = dh self.dw = dw self.g = g self.type = i['dtype'] else: assert False def params(self): p = OrderedDict([('N',self.N), ('C',self.C), ('H',self.H), ('W',self.W), ('K',self.K), ('P',self.P), ('Q',self.Q), ('R',self.R), ('S',self.S), ('ph',self.ph), ('pw',self.pw), ('U',self.U), ('V',self.V), ('dh',self.dh), ('dw',self.dw), ('g',self.g), ('type',self.type)]) return p def conv_bytes_flops(self, N, C, H, W, K, P, Q, R, S, g, t): f = 2*N*K*P*Q*C*R*S/g #for fprop elems = N*C*H*W + K*C*R*S/g + N*K*P*Q b = elems * Utility.typeToBytes(t) return b,f def bytes_flops(self): N,C,H,W,K,P,Q,R,S,ph,pw,U,V,dh,dw,g,t = self.params().values() if any(x in self.name for x in Conv.convAuxList+Conv.winoAuxList+Conv.fftAuxList+Conv.miscAuxList): bytes, flops = [0, 0] elif any(x in self.name for x in Conv.convList+Conv.winoList+Conv.fftList+Conv.miscList): if g == 1: bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) else: if "2d_grouped_direct_kernel" in self.name: #only 1 kernel is called bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) elif "spatialDepthwiseConvolutionUpdateOutput" in self.name: #one kernel for separable conv bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) else: #a kernel per group is called bytes, flops = self.conv_bytes_flops(N,C/g,H,W,K/g,P,Q,R,S,1,t) elif ("calc_bias_diff" in self.name): #bias gradient elems = N*K*P*Q flops = elems bytes = 2 * elems * Utility.typeToBytes(t) #params = OrderedDict([('N',N), ('K',K), ('P',P), ('Q',Q), ('type', t)]) else: bytes, flops = [0, 0] return bytes, flops def bytes(self): b,_ = self.bytes_flops() return b def flops(self): _,f = self.bytes_flops() return f def tc(self): for s in ["884cudnn", "1688cudnn"]: if s in self.name: return 1 return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/convert.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Convert(OperatorLayerBase): """ Class to handle convert operations. """ ops = ["byte", "char", "double", "float", "half", "int", "long", "short", "to"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op in Convert.ops) assert (len(args) == 1) #The argument could be a tensor or scalar t = args[0] if t['type'] == "tensor": shape = t['shape'] stype = t['dtype'] else: shape = (1,) stype = t['type'] if self.op_ == "to": op = stype self.shape = shape self.stype = stype self.dtype = op def params(self): p = OrderedDict([('T', self.shape), ('stype', self.stype), ('dtype', self.dtype)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def elems(self): return Utility.numElems(self.shape) def flops(self): return 0 def bytes(self): b = self.elems() * (Utility.typeToBytes(self.stype) + Utility.typeToBytes(self.dtype)) return b ================================================ FILE: KoSentenceT5/apex/pyprof/prof/data.py ================================================ from .utility import Utility class Data(object): """ Class to store all the data for every kernel e.g. name, bytes, flops, device, stream etc. """ def __init__(self, kernel): #Available from NVprof self.tid = kernel['tid'] self.device = kernel['device'] self.stream = kernel['stream'] self.grid = str(kernel['grid']).replace(" ","").replace("(","").replace(")","") self.block = str(kernel['block']).replace(" ","").replace("(","").replace(")","") self.name = kernel['kShortName'].replace(" ","_") self.lName = kernel['kLongName'] self.sil = kernel['kDuration'] #units ns self.index = None #Markers self.argMarker = kernel['marker'] self.modMarker = kernel['reprMarkers'] self.seqMarker = kernel['seqMarker'] self.layer = kernel['layer'] self.trace = kernel['trace'] self.seqId = kernel['seqId'] self.altSeqId = kernel['altSeqId'] self.dir = kernel['dir'] self.sub = kernel['subSeqId'] self.mod = "na" self.op = "na" self.params = {"na":"na"} self.tc = "na" self.flops = 0 self.bytes = 0 def setParams(self, params): #Remove space from params qaz = "" for key,value in params.items(): if "type" not in key: qaz += "{}={},".format(key,value) else: if type(value) is str: qaz += "{},".format(Utility.typeToString(value)) else: qaz += "{}".format(value) self.params = qaz.replace(" ", "") ================================================ FILE: KoSentenceT5/apex/pyprof/prof/dropout.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Dropout(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "dropout") #assert (len(args) == 1) self.shape = args[0]['shape'] self.type = args[0]['dtype'] self.dir = d.dir return def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def elems(self): return Utility.numElems(self.shape) def bytes(self): #Ignoring the cost of writing and reading the mask return Utility.typeToBytes(self.type) * self.elems() * 2 def flops(self): # Note: This is approximate and depends on the RNG return 5*self.elems() ================================================ FILE: KoSentenceT5/apex/pyprof/prof/embedding.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Embedding(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "embedding") self.ishape = args[0]['shape'] self.itype = args[0]['dtype'] self.eshape = args[1]['shape'] self.etype = args[1]['dtype'] assert (len(self.eshape) == 2) self.dir = d.dir self.sub = d.sub return def params(self): p = OrderedDict([('I', self.ishape), ('itype', self.itype), ('E', self.eshape), ('etype', self.etype)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def bytes(self): ishape = self.ishape itype = self.itype eshape = self.eshape etype = self.etype ielems = Utility.numElems(ishape) b = 0 if self.dir == "fprop": #indices b += ielems * Utility.typeToBytes(itype) #read and write the embedding matrix b += ielems * eshape[1] * 2 * Utility.typeToBytes(etype) else: #3 times the size of the incoming gradient b = ielems * eshape[1] * 3 * Utility.typeToBytes(etype) if self.sub > 0: b = 0 return b def flops(self): # Note: not implemented yet return 0 ================================================ FILE: KoSentenceT5/apex/pyprof/prof/index_slice_join_mutate.py ================================================ from collections import OrderedDict from .utility import Utility import numpy as np from .base import OperatorLayerBase class Cat(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") assert (op == "cat") assert (len(args) >= 2) t = args[0]['dtype'] shapes = [] for arg in args: if arg['type'] == "tensor": assert (arg['dtype'] == t) shapes.append(arg['shape']) self.type = t self.shapes = shapes def params(self): p = OrderedDict([('T', self.shapes), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): b = 0 for s in self.shapes: b += Utility.numElems(s) return 2 * b * Utility.typeToBytes(self.type) class Reshape(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "reshape") #Temporarily commenting three lines #assert (len(args) == 2) #t,s = args #assert s['type'] == "tuple" t = args[0] assert t['type'] == "tensor" self.type = t['dtype'] self.shape = t['shape'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return 0 class Gather(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") or (mod == "torch") assert (op == "gather") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 3) #Get input if (args[0]['name'] == ""): arg = args[0] else: arg = list(filter(lambda x : x['name'] == "input", args))[0] assert (arg['type'] == "tensor") self.shape = arg['shape'] self.type = arg['dtype'] def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return 2 * Utility.numElems(self.shape) * Utility.typeToBytes(self.type) class MaskedScatter(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "masked_scatter_") assert (len(args) == 3) dst, mask, src = args assert (dst['type'] == mask['type'] == src['type'] == "tensor") assert (mask['dtype'] == "uint8") assert (dst['dtype'] == src['dtype']) assert (dst['shape'] == mask['shape']) self.shape = dst['shape'] self.type = dst['dtype'] self.seqId = d.seqId def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): elems = Utility.numElems(self.shape) #src and dst b = 2 * elems * Utility.typeToBytes(self.type) #mask (uint8) b += elems if (self.seqId > 0): b = 0 return b class Nonzero(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "nonzero") assert (len(args) == 1) arg = args[0] self.shape = arg['shape'] self.type = arg['dtype'] self.seqId = d.seqId def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): elems = Utility.numElems(self.shape) dim = len(self.shape) #input tensor b = elems * Utility.typeToBytes(self.type) #in the worst case, the output is a (elems x dim) tensor of type "long" b += elems * dim * Utility.typeToBytes("int64") if self.seqId > 0: return 0 else: return b class IndexSelect(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") or (mod == "torch") assert (op == "index_select") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 3) #Get input, dim and index if (args[0]['name'] == ""): t = args[0] else: t = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): d = args[1] else: d = list(filter(lambda x : x['name'] == "dim", args))[0] if (args[2]['name'] == ""): i = args[2] else: i = list(filter(lambda x : x['name'] == "index", args))[0] assert (t['type'] == i['type'] == "tensor") assert (d['type'] == "int") assert (i['dtype'] == "int64") assert (len(i['shape']) == 1) shape = t['shape'] dim = d['value'] indices = i['shape'][0] assert (dim < len(shape)) self.shape = shape self.dim = dim self.indices = indices self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape),('D', self.dim),('I', self.indices),('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def bytes(self): #determine the shape of the output tensor shape = list(self.shape) shape[self.dim] = self.indices b = 0 #time to read the input and write the output elems = Utility.numElems(shape) b += 2 * elems * Utility.typeToBytes(self.type) #time to read the indices b += self.indices * Utility.typeToBytes("int64") return b class MaskedSelect(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.sub = d.sub assert (mod == "Tensor") or (mod == "torch") assert (op == "masked_select") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 2) #Get input and mask if (args[0]['name'] == ""): t = args[0] else: t = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): m = args[1] else: m = list(filter(lambda x : x['name'] == "mask", args))[0] assert (m['dtype'] == "uint8") tensor = t['shape'] mask = m['shape'] #check for broadcast condition if (tensor != mask): array1 = np.empty(list(tensor)) array2 = np.empty(list(mask)) try: out = np.broadcast(array1, array2).shape except: assert False self.tshape = tensor self.mshape = mask self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.tshape),('M', self.mshape),('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): tensor = self.tshape mask = self.mshape t = self.type #in the worst case, #output elements = #input elements b = 2 * Utility.numElems(tensor) * Utility.typeToBytes(t) #mask tensor (assuming uint8) b += Utility.numElems(mask) return b def flops(self): return 0 ================================================ FILE: KoSentenceT5/apex/pyprof/prof/linear.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Linear(OperatorLayerBase): ''' Notes: If the bias occurs before the GEMM, then its 1 write (bias expansion). If the bias occurs after, then its 1 read and 1 write. bias in bprop is a reduction and hence is 1 read. ''' gemmKernels = ["gemm", "gemv", "dot_kernel", "splitKreduce_kernel", "reduce_1Block_kernel"] biasKernels = ["kernelReduceContigDim", "kernelReduceNoncontigDim_shared", "elementwise_kernel", "reduce_kernel"] def setXWBMNK(self, args): x = None w = None b = None if (len(args) == 2): x,w = args elif (len(args) == 3): x,w,b = args assert (x['type'] == w['type'] == "tensor") if (b['type'] == "tensor"): assert(len(b['shape']) == 1) elif (b['type'] == "NoneType"): assert b['value'] is None b = None else: assert False else: assert False assert(len(w['shape']) == 2) k1 = x['shape'][-1] n,k2 = w['shape'] assert(k1 == k2) if b is not None: assert(b['shape'][0] == n) t1 = x['dtype'] t2 = w['dtype'] assert(t1 == t2) # X, W, B self.x = x['shape'] self.w = w['shape'] self.b = b['shape'] if b is not None else None self.type = t1 # M, N, K #n = Utility.numElems(x[0:-1]) n = self.x[0:-1] k = self.x[-1] m,k1 = self.w assert (k == k1) self.m = m self.n = n self.k = k def tc(self): if self.op() == "linear": return 1 if "884gemm" in self.name else 0 else: return "-" def __init__(self, d): self.name = d.name self.dir = d.dir self.sub = d.sub marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "torch.nn.functional") assert (op == "linear") self.setXWBMNK(args) if any(x in d.name for x in Linear.gemmKernels): self.op_ = "linear" else: assert (d.name in Linear.biasKernels) self.op_ = "bias" ''' elif (("kernelPointwiseApply2" in d.name) or ("kernelReduceContigDim" in d.name) or ("kernelReduceNoncontigDim_shared" in d.name)): #bias expansion was before the gemm self.op_ = "bias" elif ("elementwise_kernel" in d.name): #Bias addition happens later with a broadcast tensor self.op_ = "bias" assert (len(d.argMarker) == 2) marker = eval(d.argMarker[1]) mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "Tensor") assert (op == "__iadd__") assert (len(args) == 2) mn = args[0]['shape'] b = args[1]['shape'] assert (len(b) == 1) assert (mn == (self.n + (self.m,))) assert (b == self.b) else: assert False ''' def params(self): #p = OrderedDict([('X', self.x), ('W', self.w), ('B', self.b), ('type', self.type)]) m, n, k, x, w, t = self.m, self.n, self.k, self.x, self.w, self.type if len(n) == 1: n = n[0] if self.op_ == "linear": if self.dir == "fprop": p = OrderedDict([('M', m), ('N', n), ('K', k), ('type', t)]) elif self.dir == "bprop": if self.sub == 0: #dgrad (most likely) p = OrderedDict([('M', k), ('N', n), ('K', m), ('type', t)]) elif self.sub == 1: #wgrad (most likely) p = OrderedDict([('M', k), ('N', m), ('K', n), ('type', t)]) else: #This happens when there are additional kernels for reduction p = OrderedDict([('X', x), ('W', w), ('type', t)]) else: assert False elif self.op_ == "bias": p = OrderedDict([('M', m), ('N', n), ('type', t)]) else: assert False return p def op(self): return self.op_ def bytesFlops(self): m = self.m n = Utility.numElems(self.n) k = self.k if self.op_ == "linear": if self.dir == "fprop": f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) elif self.dir == "bprop": if self.sub == 0: #dgrad (most likely) f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) elif self.sub == 1: #wgrad (most likely) f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) else: #This happens when there are additional kernels for reduction f = 0 b = 0 else: assert False elif self.op_ == "bias": f = m * n b = 2 * m * n * Utility.typeToBytes(self.type) else: assert False return b,f def bytes(self): b, f = self.bytesFlops() return b def flops(self): b, f = self.bytesFlops() return f def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/loss.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase #TODO: Add support for additional loss functions. class MSELoss(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "mse_loss") assert (len(args) == 3) #Get input, target and reduction if (args[0]['name'] == ""): x = args[0] else: x = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): y = args[1] else: y = list(filter(lambda x : x['name'] == "target", args))[0] if (args[2]['name'] == ""): r = args[2] else: r = list(filter(lambda x : x['name'] == "reduction", args))[0] assert (x['type'] == y['type'] == "tensor") assert (x['shape'] == y['shape']) assert (x['dtype'] == y['dtype']) assert (r['type'] == "str") assert (r['value'] in ["none", "mean", "sum"]) self.shape = x['shape'] self.type = x['dtype'] self.red = r['value'] self.dir = d.dir def params(self): p = OrderedDict([('T', self.shape), ('type', self.type), ('red', self.red)]) return p def elems(self): red = self.red e = Utility.numElems(self.shape) if self.dir == "fprop": if red == "none": e *= 3 else: e *= 2 else: if red == "none": e *= 4 else: e *= 3 return e def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): return self.elems() * 2 + 1 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/misc.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Foo(OperatorLayerBase): """ An object of Foo is instantiated when we detect an unsupported operator. """ def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args shapes = [] types = [] for arg in args: if arg['type'] == "tensor": shapes.append(arg['shape']) types.append(arg['dtype']) self.shape = shapes self.type = types def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def bytes(self): return 0 class Copy(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "copy_") assert (len(args) == 2) dst, src = args assert (src['type'] == dst['type']) assert (src['shape'] == dst['shape']) self.shape = src['shape'] self.stype = src['dtype'] self.dtype = dst['dtype'] def params(self): #The data type might be different p = OrderedDict([('T', self.shape), ('stype', self.stype), ('dtype', self.dtype)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def elems(self): return Utility.numElems(self.shape) def bytes(self): return self.elems() * (Utility.typeToBytes(self.stype) + Utility.typeToBytes(self.dtype)) class Clone(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "clone") assert (len(args) == 1) t = args[0] self.shape = t['shape'] self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def bytes(self): return 2 * self.elems() * Utility.typeToBytes(self.type) class Contiguous(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "contiguous") assert (len(args) == 1) t = args[0] self.shape = t['shape'] self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def bytes(self): return 2 * Utility.numElems(self.shape) * Utility.typeToBytes(self.type) def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ class Any(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "any") assert (len(args) == 1) #could be 2 as well, the second argument is a bool t = args[0] self.shape = t['shape'] self.type = t['dtype'] self.sub = d.sub return def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def flops(self): return 0 def bytes(self): return Utility.numElems(self.shape) * Utility.typeToBytes(self.type) ================================================ FILE: KoSentenceT5/apex/pyprof/prof/normalization.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class BatchNorm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (op == "batch_norm") assert (len(args) == 8) i = args[0] assert (i['type'] == "tensor") self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def flops(self): # Variance algo-dependent, but this is a reasonable value. return self.elems() * 8 def bytes(self): e = self.elems() if self.dir == "fprop": e *= 4 else: e *= 5 return e * Utility.typeToBytes(self.type) ================================================ FILE: KoSentenceT5/apex/pyprof/prof/optim.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase #TODO: Add support for other optimizers. class Adam(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert(op == "adam") assert (len(args) == 12) or (len(args) == 14) w, hw, m, v, g = args[0:5] assert (w['shape'] == m['shape'] == v['shape'] == g['shape']) assert (hw['shape'] == w['shape']) or (hw['shape'] == (0,)) #hw could be null assert (w['type'] == m['type'] == v['type'] == g['type'] == hw['type'] == "tensor") assert (w['dtype'] == m['dtype'] == v['dtype'] == "float32") self.w = w self.g = g def params(self): p = OrderedDict([('T',self.w['shape']), ('wtype',self.w['dtype']), ('gtype',self.g['dtype'])]) return p def flops(self): return 0 def bytes(self): wshape = self.w['shape'] wtype = self.w['dtype'] gtype = self.g['dtype'] b = 0 elems = Utility.numElems(wshape) #Get time to stream read/write w, m, v b += 6 * elems * Utility.typeToBytes(wtype) #Get time to read "g" b += elems * Utility.typeToBytes(gtype) if wtype != gtype: #mixed precision #Get time to write "hw b += elems * Utility.typeToBytes(gtype) return b def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/output.py ================================================ import errno, os, sys class Output(): """ This class handles printing of a columed output and a CSV. """ # The table below is organized as # user_option: [output_header, attribute_in_Data_class, type, min_width_in_columed_output] table = { "idx": ["Idx", "index", int, 7], "seq": ["SeqId", "seqId", str, 7], "altseq": ["AltSeqId", "altSeqId", str, 7], "tid": ["TId", "tid", int, 12], "layer": ["Layer", "layer", str, 10], "trace": ["Trace", "trace", str, 25], "dir": ["Direction", "dir", str, 5], "sub": ["Sub", "sub", int, 3], "mod": ["Module", "mod", str, 15], "op": ["Op", "op", str, 15], "kernel": ["Kernel", "name", str, 0], "params": ["Params", "params", str, 0], "sil": ["Sil(ns)", "sil", int, 10], "tc": ["TC", "tc", str, 2], "device": ["Device", "device", int, 3], "stream": ["Stream", "stream", int, 3], "grid": ["Grid", "grid", str, 12], "block": ["Block", "block", str, 12], "flops": ["FLOPs", "flops", int, 12], "bytes": ["Bytes", "bytes", int, 12] } def __init__(self, args): self.cols = args.c self.csv = args.csv self.col = True if (args.w > 0) else False self.width = args.w w = 0 for col in self.cols: assert col in Output.table.keys() w += Output.table[col][3] if ((self.col) and (w > self.width)): print("Minimum width required to print {} = {}. Exiting.".format(",".join(self.cols), w)) sys.exit(1) remainder = self.width - w if ("kernel" in self.cols) and ("params" in self.cols): Output.table["kernel"][3] = int(remainder/2) Output.table["params"][3] = int(remainder/2) elif ("kernel" in self.cols): Output.table["kernel"][3] = remainder elif ("params" in self.cols): Output.table["params"][3] = remainder #header format cadena = "" for col in self.cols: _,_,t,w = Output.table[col] cadena += "%-{}.{}s ".format(w,w) self.hFormat = cadena #data format cadena = "" for col in self.cols: _,_,t,w = Output.table[col] if (t == str): cadena += "%-{}.{}s ".format(w,w) elif (t == int): cadena += "%{}d ".format(w) self.dFormat = cadena def foo(self, cadena, pformat): if self.csv: cadena = ",".join(map(lambda x : '"' + str(x) + '"', cadena)) elif self.col: cadena = pformat % cadena else: cadena = " ".join(map(str,cadena)) try: print(cadena) except IOError as e: #gracefully handle pipes if e.errno == errno.EPIPE: # Python flushes standard streams on exit; redirect remaining output # to devnull to avoid another BrokenPipeError at shutdown devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) sys.exit(0) else: sys.exit(-1) def header(self): cadena = () for col in self.cols: h = Output.table[col][0] cadena = cadena + (h,) self.foo(cadena, self.hFormat) def data(self, a): if a.dir == "": direc = "na" else: direc = a.dir if a.op == "": op = "na" else: op = a.op if a.mod == "": mod = "na" else: mod = a.mod cadena = () for col in self.cols: attr = Output.table[col][1] val = getattr(a, attr) if col == "layer": assert(type(val) == list) val = ":".join(val) val = "-" if val == "" else val if col == "trace": assert(type(val) == list) if self.col and len(val): val = val[-1] val = val.split("/")[-1] else: val = ",".join(val) val = "-" if val == "" else val if col in ["seq", "altseq"]: assert(type(val) == list) val = ",".join(map(str,val)) val = "-" if val == "" else val cadena = cadena + (val,) self.foo(cadena, self.dFormat) ================================================ FILE: KoSentenceT5/apex/pyprof/prof/pointwise.py ================================================ import numpy as np from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Pointwise(OperatorLayerBase): ops = [] ops += ["__abs__", "__neg__", "__invert__"] ops += ["__add__", "__sub__", "__mul__", "__floordiv__", "__truediv__", "__pow__", "__mod__"] ops += ["__radd__", "__rsub__", "__rmul__", "__rdiv__", "__rtruediv__", "__rfloordiv__", "__rpow__"] ops += ["__iadd__", "__isub__", "__imul__", "__itruediv__",] ops += ["__lt__", "__gt__", "__ge__", "__le__", "__eq__", "__ne__",] ops += ["lt", "lt_", "gt", "gt_", "ge", "ge_", "le", "le_", "eq", "eq_", "ne", "ne_",] ops += ["__and__", "__or__", "__xor__", "__lshift__", "__rshift__"] ops += ["__iand__", "__ior__", "__ixor__", "__ilshift__", "__irshift__"] ops += ["abs", "abs_", "neg", "neg_"] ops += ["add", "add_", "div", "div_", "mul", "mul_", "reciprocal", "reciprocal_", "remainder", "remainder_", "sub", "sub_",] ops += ["addcdiv", "addcdiv_", "addcmul", "addcmul_"] ops += ["exp", "exp_", "exp1m", "exp1m_", "log", "log_", "log10", "log10_", "log1p", "log1p_", "log2", "log2_", "pow", "pow_", "rsqrt", "rsqrt_", "sqrt", "sqrt_",] ops += ["ceil", "ceil_", "clamp", "clamp_", "floor", "floor_", "fmod", "fmod_", "frac", "frac_", "round", "round_", "sign", "sign_", "trunc", "trunc_"] ops += ["acos", "acos_", "asin", "asin_", "atan", "atan_", "atan2", "atan2_", "cos", "cos_", "cosh", "cosh_", "sin", "sin_", "sinh", "sinh_", "tan", "tan_", "sigmoid", "sigmoid_", "tanh", "tanh_"] ops += ["digamma", "erf", "erf_", "erfc", "erfc_", "erfinv", "erfinv_", "lerp", "lerp_", "mvlgamma",] @staticmethod def foo(d): return d['name'],d['type'],d['shape'],d['dtype'] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.dir = d.dir assert (d.dir in ["fprop", "bprop"]) assert (op in Pointwise.ops) #Filter out all named parameters (kwargs). #This might require revisiting in future. args = list(filter(lambda x : x['name'] == "", args)) #Filter out non tensors args = list(filter(lambda x : x['type'] == "tensor", args)) if (len(args) == 0): self.shape = [(1,)] self.type = "float32" #FIX elif (len(args) == 1): in0 = args[0] _,t0,s0,dt0 = Pointwise.foo(in0) assert (t0 == "tensor") self.shape = [s0,] self.type = dt0 elif (len(args) == 2): in0,in1 = args _,t0,s0,dt0 = Pointwise.foo(in0) _,t1,s1,dt1 = Pointwise.foo(in1) assert (t0 == t1 == "tensor") assert (dt0 == dt1) self.shape = [s0,s1] self.type = dt0 elif (len(args) == 3): in0,in1,in2 = args _,t0,s0,dt0 = Pointwise.foo(in0) _,t1,s1,dt1 = Pointwise.foo(in1) _,t2,s2,dt2 = Pointwise.foo(in2) assert (t0 == t1 == t2 == "tensor") assert (dt0 == dt1 == dt2) self.shape = [s0,s1,s2] self.type = dt0 else: assert False return def params(self): p = OrderedDict([('T',self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): tensor = self.shape t = self.type if (len(tensor) == 1): elems = 2 * Utility.numElems(tensor[0]) elif (len(tensor) == 2): if (tensor[0] == tensor[1]): # same shape elems = Utility.numElems(tensor[0]) if self.dir == "fprop": elems *= 3 else: if (self.op_ in ["add", "__add__", "sub", "__sub__", "__isub__"]): elems *= 2 elif (self.op_ in ["__mul__", "__rmul__", "div", "__truediv__"]): elems *= 3 else: assert False else: #check for broadcast conditions array1 = np.empty(list(tensor[0])) array2 = np.empty(list(tensor[1])) try: out = np.broadcast(array1, array2).shape except: assert False elems = Utility.numElems(tensor[0]) elems += Utility.numElems(tensor[1]) elems += Utility.numElems(out) #TODO bprop elif (len(tensor) == 3): if (tensor[0] == tensor[1] == tensor[2]): #same shape elems = Utility.numElems(tensor[0]) elems *= 4 else: assert False else: assert False return elems def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): # Note: some cases may still be missing. f = 0 if self.op_ in ["__abs__", "__neg__", "__add__", "__sub__", "__mul__", "__radd__", "__rmul__", "__iadd__", "__isub__", "__imul__", "__itruediv__", "abs", "abs_", "neg", "neg_", "add", "add_", "div", "div_", "mul", "mul_", "sub", "sub_", "exp", "exp_", "sign", "sign_", "trunc", "trunc_", "sin", "sin_", "cos", "cos_", "sinh", "sinh_", "cosh", "cosh_", "sqrt", "sqrt_", "rsqrt", "rsqrt_", "__lt__", "__gt__", "__ge__", "__le__", "__eq__", "__ne__", "lt", "lt_", "gt", "gt_", "ge", "ge_", "le", "le_", "eq", "eq_", "ne", "ne_", "ceil", "ceil_", "clamp", "clamp_", "floor", "floor_", "round", "sign", "sign_", "trunc", "trunc_"]: # We're counting only one operand, not two (2 operands, 1 op) f = self.elems() / 2 elif self.op_ in ["fmod", "fmod_"]: f = self.elems() elif self.op_ in ["tanh", "tanh_", "sigmoid", "sigmoid_", "log", "log_", "log2", "log2_", "log10", "log10_"]: f = self.elems() * 2 elif self.op_ in ["asin", "asin_", "acos", "acos_", "atan", "atan_"]: # no intrinsic, hence slow execution # surprisingly, asin/acos and atan were all the same (via nvprof measurement) f = self.elems() * 10 return f ================================================ FILE: KoSentenceT5/apex/pyprof/prof/pooling.py ================================================ from .collections import OrderedDict from .utility import Utility # Work in progress. #poolFuncs = ["max_pool2d_with_indices_forward", "max_pool2d_with_indices"] class MaxPool2d(object): def parse(marker): def convert2Tuple(arg): assert (arg['type'] in ["int", "tuple"]) if arg['type'] == "int": return (arg['value'], arg['value']) else: return arg['value'] mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "torch.nn.functional") assert (op == "max_pool2d") assert (len(args) >= 2) #input assert (args[0]['name'] == "") inp = args[0] assert (inp['type'] == "tensor") i = inp['shape'] t = inp['dtype'] assert (len(i) == 4) #nchw tensor #kernel if (args[1]['name'] == ""): k = args[1] else: k = list(filter(lambda x : x['name'] == "kernel_size", args))[0] k = convert2Tuple(k) #stride s = k #default value if ((len(args) >= 3) and args[2] == ""): s = args[2] s = convert2Tuple(s) elif any(x['name'] == "stride" for x in args): s = list(filter(lambda x : x['name'] == "stride", args))[0] s = convert2Tuple(s) #padding p = (0,0) if ((len(args) >= 4) and args[3] == ""): p = args[3] p = convert2Tuple(p) elif any(x['name'] == "padding" for x in args): p = list(filter(lambda x : x['name'] == "padding", args))[0] p = convert2Tuple(p) params = OrderedDict([('T', i), ('K', k), ('s',s), ('p',p), ('type', t)]) return params ================================================ FILE: KoSentenceT5/apex/pyprof/prof/prof.py ================================================ #!/usr/bin/env python3 """ This script reads the output (Python dictionary) created by parse.py. For every kernel (line) in the input it determines module / class name e.g. torch.nn.functional operator name e.g. linear kernel parameters e.g. GEMM M, N, K, datatype bytes flops tensor core usage direction (fprop, bprop) and other things. Please see the tool usage. """ from .usage import parseArgs from .output import Output from .utility import Utility from .pointwise import Pointwise from .convert import Convert from .blas import * from .embedding import Embedding from .reduction import * from .dropout import Dropout from .softmax import * #from pooling import * # work in progress from .linear import Linear from .optim import Adam from .misc import * from .conv import Conv from .activation import Activation from .index_slice_join_mutate import Cat, Reshape, MaskedScatter, Gather, Nonzero, IndexSelect, MaskedSelect from .recurrentCell import RNNCell from .normalization import BatchNorm from .randomSample import RandPerm from .loss import MSELoss from .data import Data def findFpropKernel(seq): #Find the last fprop kernel with the same seqId #First look at seqId and then at altSeqId for idx in reversed(range(len(kernels))): k = kernels[idx] if (seq in k['seqId']) and (k['dir'] == "fprop"): return idx for idx in reversed(range(len(kernels))): k = kernels[idx] if (seq in k['altSeqId']) and (k['dir'] == "fprop"): return idx return -1 #print("Error: seqId {} not found.".format(seq), file=sys.stderr) #assert False def foo(mod, op, d): if (op[0] == "linear"): xx = Linear(d) # rnncell, lstmcell, grucell elif (mod[0] in["LSTMCell", "GRUCell"]) and (op[0] == "forward"): xx = RNNCell(d) elif op[0] in ["conv1d", "conv2d",]: xx = Conv(d) elif (op[0] in Pointwise.ops): xx = Pointwise(d) elif (op[0] in Convert.ops): xx = Convert(d) elif op[0] in ["__matmul__", "matmul"]: xx = Matmul(d) elif op[0] == "embedding": xx = Embedding(d) #reduction elif op[0] == "sum": xx = Sum(d) elif op[0] == "mean": xx = Mean(d) elif op[0] == "norm": xx = Norm(d) elif op[0] == "dropout": xx = Dropout(d) #Index, Slice, Join, Mutate elif (op[0] == "cat"): xx = Cat(d) elif (op[0] == "reshape"): xx = Reshape(d) elif (op[0] == "masked_scatter_"): xx = MaskedScatter(d) elif (op[0] == "gather"): xx = Gather(d) elif (op[0] == "nonzero"): xx = Nonzero(d) elif (op[0] == "index_select"): xx = IndexSelect(d) elif (op[0] == "masked_select"): xx = MaskedSelect(d) #blas elif op[0] in ["addmm", "addmm_"]: xx = Addmm(d) elif op[0] == "mm": xx = Mm(d) elif op[0] == "bmm": xx = Bmm(d) #softmax elif op[0] == "softmax": xx = Softmax(d) elif op[0] == "log_softmax": xx = LogSoftmax(d) #loss elif op[0] == "mse_loss": xx = MSELoss(d) #optimizers elif op[0] == "adam": xx = Adam(d) #normalization elif op[0] == "batch_norm": xx = BatchNorm(d) #random elif op[0] == "randperm": xx = RandPerm(d) #misc elif op[0] == "copy_": xx = Copy(d) elif op[0] == "clone": xx = Clone(d) elif op[0] == "contiguous": xx = Contiguous(d) elif op[0] == "any": xx = Any(d) elif (op[0] in Activation.ops): xx = Activation(d) elif op[0] == "to": xx = Convert(d) else: xx = Foo(d) return xx def main(): #Read cmd line arguments cmdArgs = parseArgs() output = Output(cmdArgs) output.header() idx = -1 #Read in all the kernel info for line in cmdArgs.file: idx += 1 kernel = eval(line) assert(kernel) kernels.append(kernel) k = kernel d = Data(k) mod = k['mod'] op = k['op'] flops = 0 params = {"na":"na"} tc = "na" bytes = 0 if (d.dir == "bprop"): d.seqMarker = k['seqMarker'] seq = k['seqId'] if len(seq) > 1: pass seq = k['seqId'][:1] assert (len(seq) == 1), seq #assert (seq[0] != 0) assert (len(d.seqMarker) > 0) #If there is no useful marker associated, use the #sequence number to find the kernel from fprop if len(d.argMarker) == 0: index = findFpropKernel(seq[0]) if index >= 0: d.argMarker = kernels[index]['marker'] d.modMarker = kernels[index]['reprMarkers'] mod = kernels[index]['mod'] op = kernels[index]['op'] d.layer = kernels[index]['layer'] d.trace = kernels[index]['trace'] # Check if marker has our annotations if len(d.argMarker) and Utility.hasNVTX(d.argMarker[0]): xx = foo(mod, op, d) bytes = xx.bytes() flops = xx.flops() op = xx.op() params = xx.params() tc = xx.tc() if type(op) is list: if len(op): op = op[0] else: op = "" if type(mod) is list: if len(mod): mod = mod[0] else: mod = "" d.index = idx+1 # The following 8 come from operator class functions. d.setParams(params) d.tc = tc d.flops = flops d.bytes = bytes d.mod = mod d.op = op output.data(d) kernels = [] if __name__ == '__main__': main() ================================================ FILE: KoSentenceT5/apex/pyprof/prof/randomSample.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class RandPerm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") assert (op == "randperm") assert (len(args) == 1) n = args[0] assert n['type'] == "int" self.n = n['value'] def params(self): p = OrderedDict([('N', self.n)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return self.n * Utility.typeToBytes("int64") def flops(self): # Depends on RNG but this is probably a reasonable assumption. return self.n * 3 ================================================ FILE: KoSentenceT5/apex/pyprof/prof/recurrentCell.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase def hasTileSize(name): if ("sgemm" in name) or ("884gemm" in name) or ("hgemm" in name): return True else: return False def ctaTile(name): name = name.split("_") name = list(filter(lambda x : "x" in x, name)) name = list(filter(lambda x : "slice" not in x, name)) assert(len(name) == 1) name = name[0].split("x") assert(len(name) == 2) name = list(map(int, name)) return name[0], name[1] class RNNCell(OperatorLayerBase): """ This class supports RNNCell, LSTMCell and GRUCell. """ def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.name = d.name self.dir = d.dir self.sub = d.sub self.grid = d.grid assert (op == "forward") assert (mod in ["LSTMCell", "GRUCell", "RNNCell"]) assert (len(args) in [2,3]) x,h = args[0],args[1] b1,ii = x['shape'] b2,hh = h['shape'] assert b1 == b2 assert x['dtype'] == h['dtype'] t = x['dtype'] self.cell = mod self.inp = ii self.hid = hh self.b = b1 self.type = t self.multiple = 1 if self.cell == "LSTMCell": self.multiple = 4 elif self.cell == "GRUCell": self.multiple = 3 self.gemm = None self.m = None self.n = None self.k = None self.elems = 0 self.bar() def params(self): if self.gemm is None: p = OrderedDict([('cell', self.cell), ('X', self.inp), ('H', self.hid), ('B', self.b), ('type', self.type)]) else: assert self.m is not None assert self.n is not None assert self.k is not None p = OrderedDict([('gemm', self.gemm), ('M', self.m), ('N', self.n), ('K', self.k), ('type', self.type)]) return p def tc(self): if "gemm" in self.name: return 1 if "884gemm" in self.name else 0 else: return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): if self.gemm is not None: m, n, k, t = self.m, self.n, self.k, self.type b = (m*k + k*n + m*n) * Utility.typeToBytes(t) elif self.elems != 0: b = self.elems * Utility.typeToBytes(self.type) else: b = 0 return b def flops(self): if self.gemm is not None: m, n, k = self.m, self.n, self.k f = 2*m*n*k elif self.elems != 0: f = 0 #TODO else: f = 0 return f def bar(self): cell = self.cell X = self.inp H = self.hid B = self.b t = self.type subseqId = self.sub direc = self.dir name = self.name grid = self.grid multiple = self.multiple if direc == "fprop": subseqId = subseqId % 3 if subseqId == 0: #layer gemm self.gemm = "layer" self.m = multiple*H self.n = B self.k = X elif subseqId == 1: #recurrent gemm self.gemm = "recur" self.m = multiple*H self.n = B self.k = H else: layerGemmElems = multiple*H*B recurGemmElems = multiple*H*B cElems = H*B hElems = H*B totElems = layerGemmElems + recurGemmElems + 2*cElems + hElems self.elems = totElems else: if ("gemm" in name) and hasTileSize(name): #gemm #Get cta tile size tileX, tileY = ctaTile(name) #Get grid dimensions grid = grid.split(",") gridX,gridY,gridZ = map(lambda x : int(x), grid) gemmM = tileX * gridX gemmN = tileY * gridY if name[-3:] == "_nn": # dgrad if (gemmM == H): # recurrent dgrad #Ideally gemmN = B, but we have a limited set of tile sizes. gemmN = B gemmK = multiple*H self.gemm = "recur" self.m = gemmM self.n = gemmN self.k = gemmK elif (gemmM == X): # layer dgrad #assert(gemmN % B == 0) gemmK = multiple*H self.gemm = "layer" self.m = gemmM self.n = gemmN self.k = gemmK else: pass elif name[-3:] == "_nt": #wgrad if (gemmM == H): #recurrent wgrad assert (gemmN == multiple*H) gemmK = B self.gemm = "recur" self.m = gemmM self.n = gemmN self.k = gemmK elif (gemmM == X): #layer wgrad assert (gemmN == multiple*H) gemmK = B self.gemm = "layer" self.m = gemmM self.n = gemmN self.k = gemmK else: pass else: pass else: pass return ================================================ FILE: KoSentenceT5/apex/pyprof/prof/reduction.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Mean(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "mean") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) i = args[0] self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir self.sub = d.sub def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def bytes(self): if self.sub == 0: return self.elems() * Utility.typeToBytes(self.type) else: return 0 def flops(self): if self.sub == 0: return self.elems() + 1 else: return 0 class Sum(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "sum") assert (len(args) >= 1) #Get input if (args[0]['name'] == ""): i = args[0] else: i = list(filter(lambda x : x['name'] == "input", args))[0] self.shape = i['shape'] self.type = i['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: This is incorrect, need to calculate actual flops (say via nvprof) return self.elems() def bytes(self): return self.elems() * Utility.typeToBytes(self.type) class Norm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "norm") #assert (len(args) == 1) i = args[0] self.shape = i['shape'] self.type = i['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): # square and add plus sqrt return 2 * self.elems() + 1 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSentenceT5/apex/pyprof/prof/softmax.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Softmax(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "softmax") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) self.shape = args[0]['shape'] self.type = args[0]['dtype'] self.dir = d.dir return def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: exp, sum-reduce, divide #flops = elems * 3 return 0 def bytes(self): b = self.elems() * Utility.typeToBytes(self.type) b *= 3 if self.dir == "fprop" else 5 #verify return b class LogSoftmax(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "log_softmax") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) #Get input if (args[0]['name'] == ""): i = args[0] else: i = list(filter(lambda x : x['name'] == "input", args))[0] t = i['dtype'] self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir return def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: exp, sum-reduce, divide, log #flops = elems * 4 return 0 def bytes(self): b = self.elems() * Utility.typeToBytes(self.type) b *= 3 if self.dir == "fprop" else 5 #verify return b ================================================ FILE: KoSentenceT5/apex/pyprof/prof/usage.py ================================================ import sys import argparse def parseArgs(): """ Print usage and parse arguments. """ def check_cols(value): valid = ["idx", "seq", "altseq", "tid", "layer", "trace", "dir", "sub", "mod", "op", "kernel", "params", "sil", "tc", "device", "stream", "grid", "block", "flops", "bytes"] cols = value.split(",") for col in cols: if col not in valid: raise argparse.ArgumentTypeError("{} is not a valid column name. Valid column names are {}.".format(col, ",".join(valid))) return cols def openFile(f): try: d = open(f, "r") return d except IOError: print("Error opening file {}. Exiting.".format(f), file=sys.stderr) sys.exit(1) parser = argparse.ArgumentParser(prog=sys.argv[0], description="PyTorch Profiler", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("file", nargs='?', type=str, default=None, help="Output of parse.py (Python dictionary).") parser.add_argument("-c", type=check_cols, default="idx,dir,sub,mod,op,kernel,params,sil", help='''Comma seperated names of columns to print. idx: Index seq: PyTorch Sequence Id altseq: PyTorch Alternate Sequence Id tid: Thread Id layer: User annotated NVTX string (can be nested) trace: Function Call Trace dir: Direction sub: Sub Sequence Id mod: Module op: Operattion kernel: Kernel Name params: Parameters sil: Silicon Time (in ns) tc: Tensor Core Usage device: GPU Device Id stream: Stream Id grid: Grid Dimensions block: Block Dimensions flops: Floating point ops (FMA = 2 FLOPs) bytes: Number of bytes in and out of DRAM e.g. -c idx,kernel,sil''') group = parser.add_mutually_exclusive_group() group.add_argument("--csv", action="store_true", default=False, help="Print a CSV output.") group.add_argument("-w", type=int, default=0, help="Width of columnated output.") args = parser.parse_args() if args.file is None: args.file = sys.stdin else: args.file = openFile(args.file) return args ================================================ FILE: KoSentenceT5/apex/pyprof/prof/utility.py ================================================ from functools import reduce class Utility(object): @staticmethod def numElems(shape): assert (type(shape) == tuple) return reduce(lambda x,y: x*y, shape, 1) @staticmethod def typeToBytes(t): if (t in ["uint8", "int8", "byte", "char", "bool"]): return 1 elif (t in ["float16", "half", "int16", "short"]): return 2 elif (t in ["float32", "float", "int32", "int"]): return 4 elif (t in ["int64", "long", "float64", "double"]): return 8 assert False @staticmethod def typeToString(t): if (t in ["uint8", "byte", "char",]): return "uint8" elif (t in ["int8",]): return "int8" elif (t in ["int16", "short",]): return "int16" elif (t in ["float16", "half"]): return "fp16" elif (t in ["float32", "float"]): return "fp32" elif (t in ["int32", "int",]): return "int32" elif (t in ["int64", "long"]): return "int64" elif (t in ["float64", "double",]): return "fp64" elif (t in ["bool",]): return "bool" assert False @staticmethod def hasNVTX(marker): if type(marker) is str: try: marker = eval(marker) except: return False if type(marker) is dict: keys = marker.keys() return ("mod" in keys) and ("op" in keys) and ("args" in keys) else: return False @staticmethod def isscalar(t): return (t in ["float", "int"]) ================================================ FILE: KoSentenceT5/apex/reparameterization/README.md ================================================ Under construction... ================================================ FILE: KoSentenceT5/apex/reparameterization/__init__.py ================================================ from .weight_norm import WeightNorm from .reparameterization import Reparameterization def apply_weight_norm(module, name='', dim=0, hook_child=True): r""" Applies weight normalization to a parameter in the given module. If no parameter is provided, applies weight normalization to all parameters in model (except 1-d vectors and scalars). .. math:: \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|} Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by `name` (e.g. "weight") with two parameters: one specifying the magnitude (e.g. "weight_g") and one specifying the direction (e.g. "weight_v"). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every :meth:`~Module.forward` call. By default, with `dim=0`, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use `dim=None`. See https://arxiv.org/abs/1602.07868 Args: module (nn.Module): containing module name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute the norm hook_child (boolean, optional): adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. Default: True Returns: The original module with the weight norm hook Example:: >>> m = apply_weight_norm(nn.Linear(20, 40), name='weight') Linear (20 -> 40) >>> m.weight_g.size() torch.Size([40, 1]) >>> m.weight_v.size() torch.Size([40, 20]) """ return apply_reparameterization(module, reparameterization=WeightNorm, hook_child=hook_child, name=name, dim=dim) def remove_weight_norm(module, name='', remove_all=False): """ Removes the weight normalization reparameterization of a parameter from a module. If no parameter is supplied then all weight norm parameterizations are removed. Args: module (nn.Module): containing module name (str, optional): name of weight parameter Example: >>> m = apply_weight_norm(nn.Linear(20, 40)) >>> remove_weight_norm(m) """ return remove_reparameterization(module, reparameterization=WeightNorm, name=name, remove_all=remove_all) def apply_reparameterization(module, reparameterization=None, name='', dim=0, hook_child=True): """ Applies a given weight reparameterization (such as weight normalization) to a parameter in the given module. If no parameter is given, applies the reparameterization to all parameters in model (except 1-d vectors and scalars). Args: module (nn.Module): containing module reparameterization (Reparameterization): reparamaterization class to apply name (str, optional): name of weight parameter dim (int, optional): dimension over which to perform reparameterization op hook_child (boolean, optional): adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. Default: True Returns: The original module with the reparameterization hook Example:: >>> m = apply_reparameterization(nn.Linear(20, 40), WeightNorm) Linear (20 -> 40) """ assert reparameterization is not None if name != '': Reparameterization.apply(module, name, dim, reparameterization, hook_child) else: names = list(module.state_dict().keys()) for name in names: apply_reparameterization(module, reparameterization, name, dim, hook_child) return module def remove_reparameterization(module, reparameterization=Reparameterization, name='', remove_all=False): """ Removes the given reparameterization of a parameter from a module. If no parameter is supplied then all reparameterizations are removed. Args: module (nn.Module): containing module reparameterization (Reparameterization): reparamaterization class to apply name (str, optional): name of weight parameter remove_all (bool, optional): if True, remove all reparamaterizations of given type. Default: False Example: >>> m = apply_reparameterization(nn.Linear(20, 40),WeightNorm) >>> remove_reparameterization(m) """ if name != '' or remove_all: to_remove = [] for k, hook in module._forward_pre_hooks.items(): if isinstance(hook, reparameterization) and (hook.name == name or remove_all): hook.remove(module) to_remove.append(k) if len(to_remove) > 0: for k in to_remove: del module._forward_pre_hooks[k] return module if not remove_all: raise ValueError("reparameterization of '{}' not found in {}" .format(name, module)) else: modules = [module]+[x for x in module.modules()] for m in modules: remove_reparameterization(m, reparameterization=reparameterization, remove_all=True) return module ================================================ FILE: KoSentenceT5/apex/reparameterization/reparameterization.py ================================================ import torch from torch.nn.parameter import Parameter import sys class Reparameterization(object): """ Class interface for performing weight reparameterizations Arguments: name (str): name of weight parameter dim (int): dimension over which to compute the norm module (nn.Module): parent module to which param `name` is registered to retain_forward (bool, optional): if False deletes weight on call to module.backward. Used to avoid memory leaks with DataParallel Default: True Attributes: reparameterization_names (list, str): contains names of all parameters needed to compute reparameterization. backward_hook_key (int): torch.utils.hooks.RemovableHandle.id for hook used in module backward pass. """ def __init__(self, name, dim, module, retain_forward=True): self.name = name self.dim = dim self.evaluated = False self.retain_forward = retain_forward self.reparameterization_names = [] self.backward_hook_key = None self.module = module def compute_weight(self, module=None, name=None): """ Computes reparameterized weight value to assign value to module attribute with name `name`. See WeightNorm class for example. Arguments: module (nn.Module): module with weight we'd like to reparameterize Returns: w (Tensor): Tensor object containing value of reparameterized weight """ raise NotImplementedError def reparameterize(self, name, weight, dim): """ Creates Parameters to be used for reparameterization and creates names that for attributes for the module these Parameters will correspond to. The parameters will be registered according to the names provided. See WeightNorm class for example. Arguments: module (nn.Module): module with weight we'd like to reparameterize name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute parameterization Returns: names (list, str): names of Parameters to be used for reparameterization params (list, Parameter): Parameters to be used for reparameterization """ raise NotImplementedError @staticmethod def apply(module, name, dim, reparameterization=None, hook_child=True): """ Applies reparametrization to module's `name` parameter and modifies instance attributes as appropriate. `hook_child` adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. """ if reparameterization is None: reparameterization = Reparameterization module2use, name2use = Reparameterization.get_module_and_name(module, name) # does not work on sparse if name2use is None or isinstance(module2use, (torch.nn.Embedding, torch.nn.EmbeddingBag)): return if hook_child: fn = reparameterization(name2use, dim, module2use) else: fn = reparameterization(name, dim, module) weight = getattr(module2use, name2use) if weight.dim() <= 1: return # remove weight from parameter list del module2use._parameters[name2use] # add parameters of reparameterization of parameter to module names, params = fn.reparameterize(name2use, weight, dim) for n, p in zip(names, params): module2use.register_parameter(n, p) # add parameters to reparameterization so they can be removed later fn.reparameterization_names = names setattr(module2use, name2use, None) hook_module = module2use if not hook_child: hook_module = module # recompute weight before every forward() hook_module.register_forward_pre_hook(fn) # remove weight during backward handle = hook_module.register_backward_hook(fn.backward_hook) # get hook key so we can delete it later fn.backward_hook_key = handle.id return fn @staticmethod def get_module_and_name(module, name): """ recursively fetches (possible) child module and name of weight to be reparameterized """ name2use = None module2use = None names = name.split('.') if len(names) == 1 and names[0] != '': name2use = names[0] module2use = module elif len(names) > 1: module2use = module name2use = names[0] for i in range(len(names)-1): module2use = getattr(module2use, name2use) name2use = names[i+1] return module2use, name2use def get_params(self, module): """gets params of reparameterization based on known attribute names""" return [getattr(module, n) for n in self.reparameterization_names] def remove(self, module): """removes reparameterization and backward hook (does not remove forward hook)""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) for p in self.get_params(module2use): p.requires_grad = False weight = self.compute_weight(module2use, name2use) delattr(module2use, name2use) for n in self.reparameterization_names: del module2use._parameters[n] module2use.register_parameter(name2use, Parameter(weight.data)) del module._backward_hooks[self.backward_hook_key] def __call__(self, module, inputs): """callable hook for forward pass""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) _w = getattr(module2use, name2use) if not self.evaluated or _w is None: setattr(module2use, name2use, self.compute_weight(module2use, name2use)) self.evaluated = True def backward_hook(self, module, grad_input, grad_output): """callable hook for backward pass""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) wn = getattr(module2use, name2use) self.evaluated = False ================================================ FILE: KoSentenceT5/apex/reparameterization/weight_norm.py ================================================ import torch from torch.nn.parameter import Parameter from ..fp16_utils import Fused_Weight_Norm import time from .reparameterization import Reparameterization def _norm(p, dim): """Computes the norm over all dimensions except dim""" if dim is None: return p.norm() elif dim == 0: output_size = (p.size(0),) + (1,) * (p.dim() - 1) return p.contiguous().view(p.size(0), -1).norm(dim=1).view(*output_size) elif dim == p.dim() - 1: output_size = (1,) * (p.dim() - 1) + (p.size(-1),) return p.contiguous().view(-1, p.size(-1)).norm(dim=0).view(*output_size) return _norm(p.transpose(0, dim), 0).transpose(0, dim) HALF_TYPES = (torch.cuda.HalfTensor, torch.HalfTensor) class WeightNorm(Reparameterization): r""" Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by `name` (e.g. "weight") with two parameters: one specifying the magnitude (e.g. "weight_g") and one specifying the direction (e.g. "weight_v"). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every :meth:`~Module.forward` call. .. math:: \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|} By default, with `dim=0`, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use `dim=None`. """ def compute_weight(self, module=None, name=None): """ Computes weight normalized weight value to assign value to module attribute with name `name`. Arguments: module (nn.Module): module with weight we'd like to reparameterize Returns: w (Tensor): Tensor object containing value of reparameterized weight """ if module is None: module = self.module if name is None: name = self.name module, name = Reparameterization.get_module_and_name(module, name) g = getattr(module, name + '_g') v = getattr(module, name + '_v') fused_weight_norm = Fused_Weight_Norm.apply v = v.contiguous() w = fused_weight_norm(v, g, self.dim) return w def reparameterize(self, name, weight, dim): """ Creates Parameters v and gto be used for weight normalization and creates names that for attributes for the module these Parameters will correspond to. The parameters will be registered according to the names provided. Arguments: module (nn.Module): module with weight we'd like to reparameterize name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute parameterization Returns: names (list, str): names of Parameters to be used for reparameterization params (list, Parameter): Parameters to be used for reparameterization """ names = [name + '_g', name + '_v'] params = [Parameter(_norm(weight, dim).data), Parameter(weight.data)] return names, params ================================================ FILE: KoSentenceT5/data/dataloader.py ================================================ import numpy import torch import logging from torch.utils.data import DataLoader, Dataset from transformers import AutoModel, AutoTokenizer, PreTrainedTokenizerFast logger = logging.getLogger(__name__) class ModelDataLoader(Dataset): def __init__(self, file_path, args, metric, tokenizer, type_): self.type = type_ self.args = args self.metric = metric """NLI""" self.anchor = [] self.anchor_dec = [] self.positive = [] self.positive_dec = [] self.negative = [] self.negative_dec = [] """STS""" self.label = [] self.sentence_1 = [] self.sentence_1_dec = [] self.sentence_2 = [] self.sentence_2_dec = [] # ------------------------------------- self.bert_tokenizer = tokenizer self.file_path = file_path special_tokens = {'bos_token': "[CLS]"} self.bert_tokenizer.add_special_tokens(special_tokens) self.init_token = self.bert_tokenizer.bos_token self.pad_token = self.bert_tokenizer.pad_token self.unk_token = self.bert_tokenizer.unk_token self.eos_token = self.bert_tokenizer.eos_token self.init_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.init_token) self.pad_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.pad_token) self.unk_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.unk_token) self.eos_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.eos_token) print(self.init_token, self.init_token_idx) print(self.pad_token, self.pad_token_idx) print(self.unk_token, self.unk_token_idx) print(self.eos_token, self.eos_token_idx) def load_data(self, type): with open(self.file_path) as file: lines = file.readlines() for line in lines: _ = self.data2tensor(line, type) if type == 'train': assert len(self.anchor) == len(self.positive) == len(self.negative) else: assert len(self.sentence_1) == len(self.sentence_2) == len(self.label) def data2tensor(self, line, type): split_data = line.split('\t') if type == 'train': anchor_sen, positive_sen, negative_sen = split_data anchor = self.bert_tokenizer(anchor_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, padding='max_length') anh_dec_ids = torch.cat([torch.tensor([self.init_token_idx]).unsqueeze(0), anchor['input_ids'][:, :-1]], dim=-1) anchor['dec_ids'] = anh_dec_ids positive = self.bert_tokenizer(positive_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, padding='max_length') pos_dec_ids = torch.cat([torch.tensor([self.init_token_idx]).unsqueeze(0), positive['input_ids'][:, :-1]], dim=-1) positive['dec_ids'] = pos_dec_ids negative = self.bert_tokenizer(negative_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, padding='max_length') neg_dec_ids = torch.cat([torch.tensor([self.init_token_idx]).unsqueeze(0), negative['input_ids'][:, :-1]], dim=-1) negative['dec_ids'] = neg_dec_ids self.anchor.append(anchor) self.positive.append(positive) self.negative.append(negative) else: sentence_1, sentence_2, label = split_data sentence_1 = self.bert_tokenizer(sentence_1, truncation=True, return_tensors="pt", max_length=self.args.max_len, padding='max_length') s1_dec_ids = torch.cat([torch.tensor([self.init_token_idx]).unsqueeze(0), sentence_1['input_ids'][:, :-1]], dim=-1) sentence_1['dec_ids'] = s1_dec_ids sentence_2 = self.bert_tokenizer(sentence_2, truncation=True, return_tensors="pt", max_length=self.args.max_len, padding='max_length') s2_dec_ids = torch.cat([torch.tensor([self.init_token_idx]).unsqueeze(0), sentence_2['input_ids'][:, :-1]], dim=-1) sentence_2['dec_ids'] = s2_dec_ids self.sentence_1.append(sentence_1) self.sentence_2.append(sentence_2) self.label.append(float(label.strip())/5.0) def __getitem__(self, index): if self.type == 'train': inputs = {'anchor': { 'source': torch.LongTensor(self.anchor[index]['input_ids']), 'attention_mask': self.anchor[index]['attention_mask'], 'dec_ids': torch.LongTensor(self.anchor[index]['dec_ids']) }, 'positive': { 'source': torch.LongTensor(self.positive[index]['input_ids']), 'attention_mask': self.positive[index]['attention_mask'], 'dec_ids': torch.LongTensor(self.positive[index]['dec_ids']) }, 'negative': { 'source': torch.LongTensor(self.negative[index]['input_ids']), 'attention_mask': self.negative[index]['attention_mask'], 'dec_ids': torch.LongTensor(self.negative[index]['dec_ids']) }} else: inputs = {'sentence_1': { 'source': torch.LongTensor(self.sentence_1[index]['input_ids']), 'attention_mask': self.sentence_1[index]['attention_mask'], 'dec_ids': torch.LongTensor(self.sentence_1[index]['dec_ids']) }, 'sentence_2': { 'source': torch.LongTensor(self.sentence_2[index]['input_ids']), 'attention_mask': self.sentence_2[index]['attention_mask'], 'dec_ids': torch.LongTensor(self.sentence_2[index]['dec_ids']) }, 'label': { 'value': torch.FloatTensor([self.label[index]])} } for key, value in inputs.items(): for inner_key, inner_value in value.items(): inputs[key][inner_key] = inner_value.squeeze(0) inputs = self.metric.move2device(inputs, self.args.device) return inputs def __len__(self): if self.type == 'train': return len(self.anchor) else: return len(self.label) # Get train, valid, test data loader and BERT tokenizer def get_loader(args, metric): tokenizer = AutoTokenizer.from_pretrained(args.model) path_to_train_data = args.path_to_data + '/' + args.train_data path_to_valid_data = args.path_to_data + '/' + args.valid_data path_to_test_data = args.path_to_data + '/' + args.test_data if args.train == 'True' and args.test == 'False': train_iter = ModelDataLoader(path_to_train_data, args, metric, tokenizer, type_='train') valid_iter = ModelDataLoader(path_to_valid_data, args, metric, tokenizer, type_='valid') train_iter.load_data('train') valid_iter.load_data('valid') loader = {'train': DataLoader(dataset=train_iter, batch_size=args.batch_size, shuffle=True), 'valid': DataLoader(dataset=valid_iter, batch_size=args.batch_size, shuffle=True)} elif args.train == 'False' and args.test == 'True': test_iter = ModelDataLoader(path_to_test_data, args, metric, tokenizer, type_='test') test_iter.load_data('test') loader = {'test': DataLoader(dataset=test_iter, batch_size=args.batch_size, shuffle=True)} else: loader = None return loader, tokenizer if __name__ == '__main__': get_loader('test') ================================================ FILE: KoSentenceT5/main.py ================================================ from model.setting import Setting, Arguments from model.simcse.processor import Processor def main(args, logger) -> None: processor = Processor(args) config = processor.model_setting() logger.info('Model Setting Complete') if args.train == 'True': logger.info('Start Training') for epoch in range(args.epochs): processor.train(epoch+1) if args.test == 'True': logger.info("Start Test") processor.test() processor.metric.print_size_of_model(config['model']) processor.metric.count_parameters(config['model']) if __name__ == '__main__': args, logger = Setting().run() main(args, logger) ================================================ FILE: KoSentenceT5/model/loss.py ================================================ import torch import logging import numpy as np import torch.nn as nn from model.utils import Metric from scipy.stats import pearsonr, spearmanr from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances logger = logging.getLogger(__name__) class Loss(): def __init__(self, args): self.args = args self.cos = nn.CosineSimilarity(dim=-1) self.metric = Metric(args) def train_loss_fct(self, config, inputs, a, p, n): positive_similarity = self.cos(a.unsqueeze(1), p.unsqueeze(0)) / self.args.temperature negative_similarity = self.cos(a.unsqueeze(1), n.unsqueeze(0)) / self.args.temperature cosine_similarity = torch.cat([positive_similarity, negative_similarity], dim=1).to(self.args.device) labels = torch.arange(cosine_similarity.size(0)).long().to(self.args.device) loss = config['criterion'](cosine_similarity, labels) return loss def evaluation_during_training(self, embeddings1, embeddings2, labels, indicator): embeddings1 = embeddings1.cpu().numpy() embeddings2 = embeddings2.cpu().numpy() labels = labels['value'].cpu().numpy().flatten() cosine_scores = 1 - (paired_cosine_distances(embeddings1, embeddings2)) manhattan_distances = -paired_manhattan_distances(embeddings1, embeddings2) euclidean_distances = -paired_euclidean_distances(embeddings1, embeddings2) dot_products = [np.dot(emb1, emb2) for emb1, emb2 in zip(embeddings1, embeddings2)] eval_pearson_cosine, _ = pearsonr(labels, cosine_scores) eval_spearman_cosine, _ = spearmanr(labels, cosine_scores) eval_pearson_manhattan, _ = pearsonr(labels, manhattan_distances) eval_spearman_manhattan, _ = spearmanr(labels, manhattan_distances) eval_pearson_euclidean, _ = pearsonr(labels, euclidean_distances) eval_spearman_euclidean, _ = spearmanr(labels, euclidean_distances) eval_pearson_dot, _ = pearsonr(labels, dot_products) eval_spearman_dot, _ = spearmanr(labels, dot_products) score = {'eval_pearson_cosine': eval_pearson_cosine, 'eval_spearman_cosine': eval_spearman_cosine, 'eval_pearson_manhattan': eval_pearson_manhattan, 'eval_spearman_manhattan': eval_spearman_manhattan, 'eval_pearson_euclidean': eval_pearson_euclidean, 'eval_spearman_euclidean': eval_spearman_euclidean, 'eval_pearson_dot': eval_pearson_dot, 'eval_spearman_dot': eval_spearman_dot} self.metric.update_indicator(indicator, score) return max(eval_spearman_cosine, eval_spearman_manhattan, eval_spearman_euclidean, eval_spearman_dot) ================================================ FILE: KoSentenceT5/model/setting.py ================================================ import torch import random import logging import numpy as np from argparse import ArgumentParser class Arguments(): def __init__(self): self.parser = ArgumentParser() def add_type_of_processing(self): self.add_argument('--opt_level', type=str, default='O1') self.add_argument('--fp16', type=str, default='True') self.add_argument('--train', type=str, default='True') self.add_argument('--test', type=str, default='True') self.add_argument('--multi_gpu', type=str, default='False') self.add_argument('--device', type=str, default=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')) def add_hyper_parameters(self): self.add_argument('--model', type=str, default='KETI-AIR/ke-t5-base') self.add_argument('--patient', type=int, default=10) self.add_argument('--dropout', type=int, default=0.1) self.add_argument('--max_len', type=int, default=50) self.add_argument('--batch_size', type=int, default=256) self.add_argument('--epochs', type=int, default=2) self.add_argument('--eval_steps', type=int, default=250) self.add_argument('--seed', type=int, default=12) self.add_argument('--lr', type=float, default=0.00005) self.add_argument('--weight_decay', type=float, default=0.1) self.add_argument('--warmup_ratio', type=float, default=0.05) self.add_argument('--temperature', type=float, default=0.05) def add_data_parameters(self): self.add_argument('--train_data', type=str, default='train_nli.tsv') self.add_argument('--valid_data', type=str, default='valid_sts.tsv') self.add_argument('--test_data', type=str, default='test_sts.tsv') self.add_argument('--task', type=str, default='NLU') self.add_argument('--path_to_data', type=str, default='./data/') self.add_argument('--path_to_save', type=str, default='./output/') self.add_argument('--path_to_saved_model', type=str, default='./output/') self.add_argument('--ckpt', type=str, default='best_checkpoint.pt') def print_args(self, args): for idx, (key, value) in enumerate(args.__dict__.items()): if idx == 0:print("argparse{\n", "\t", key, ":", value) elif idx == len(args.__dict__) - 1:print("\t", key, ":", value, "\n}") else:print("\t", key, ":", value) def add_argument(self, *args, **kw_args): return self.parser.add_argument(*args, **kw_args) def parse(self): args = self.parser.parse_args() self.print_args(args) return args class Setting(): def set_logger(self): _logger = logging.getLogger() formatter = logging.Formatter( '[%(levelname)s] %(asctime)s [ %(message)s ] | file::%(filename)s | line::%(lineno)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) _logger.addHandler(stream_handler) _logger.setLevel(logging.DEBUG) return _logger def set_seed(self, args): seed = args.seed random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) def run(self): parser = Arguments() parser.add_type_of_processing() parser.add_hyper_parameters() parser.add_data_parameters() args = parser.parse() logger = self.set_logger() self.set_seed(args) return args, logger ================================================ FILE: KoSentenceT5/model/simcse/kost5.py ================================================ import torch from torch import nn from transformers import BartForSequenceClassification, AutoModel class KoSentenceT5(nn.Module): def __init__(self, model): super(KoSentenceT5, self).__init__() self.model = AutoModel.from_pretrained(model) def forward(self, config, inputs, mode): if mode == 'train': anchor_pooler = self.model(input_ids=inputs['anchor']['source'], attention_mask=inputs['anchor']['attention_mask'], decoder_input_ids=inputs['anchor']['dec_ids'] ) positive_pooler = self.model(input_ids=inputs['positive']['source'], attention_mask=inputs['positive']['attention_mask'], decoder_input_ids=inputs['positive']['dec_ids'] ) negative_pooler = self.model(input_ids=inputs['negative']['source'], attention_mask=inputs['negative']['attention_mask'], decoder_input_ids=inputs['negative']['dec_ids'] ) return anchor_pooler, positive_pooler, negative_pooler else: sentence_1_pooler = self.model(input_ids=inputs['sentence_1']['source'], attention_mask=inputs['sentence_1']['attention_mask'], decoder_input_ids=inputs['sentence_1']['dec_ids'] ) sentence_2_pooler = self.model(input_ids=inputs['sentence_2']['source'], attention_mask=inputs['sentence_2']['attention_mask'], decoder_input_ids=inputs['sentence_2']['dec_ids'] ) return sentence_1_pooler, sentence_2_pooler def encode(self, inputs, device): embeddings = self.model(input_ids=inputs['source'].to(device), attention_mask=inputs['attention_mask'].to(device), ) return ((embeddings * inputs['attention_mask'].unsqueeze(-1)).sum(1) / inputs['attention_mask'].sum(-1).unsqueeze(-1)) ================================================ FILE: KoSentenceT5/model/simcse/processor.py ================================================ import os import logging from apex import amp import torch.nn as nn from tqdm import tqdm import torch.quantization import torch.optim as optim from model.loss import Loss from model.utils import Metric from accelerate import Accelerator from transformers import AutoModel from model.simcse.kost5 import KoSentenceT5 from data.dataloader import get_loader from transformers import get_linear_schedule_with_warmup logger = logging.getLogger(__name__) class Processor(): def __init__(self, args): self.args = args self.config = None self.metric = Metric(args) self.loss = Loss(args) self.total_steps = 0 self.model_checker = {'early_stop': False, 'early_stop_patient': 0, 'best_valid_score': 0} self.dev_progress = {'score': 0, 'iter': 0} self.model_progress = {'loss': 0, 'iter': 0} def run(self, inputs, indicator=None, type=None): if type == 'train': anchor_embeddings, positive_embeddings, negative_embeddings = self.config['model'](self.config, inputs, type) loss = self.loss.train_loss_fct(self.config, inputs, anchor_embeddings, positive_embeddings, negative_embeddings) return loss else: sentence_1_embeddings, sentence_2_embeddings = self.config['model'](self.config, inputs, type) score = self.loss.evaluation_during_training(sentence_1_embeddings, sentence_2_embeddings, inputs['label'], indicator) return score def progress(self, loss): self.model_progress['loss'] += loss self.model_progress['iter'] += 1 def progress_validation(self, score): self.dev_progress['score'] += score self.dev_progress['iter'] += 1 def return_value(self): loss = self.model_progress['loss'].data.cpu().numpy() / self.model_progress['iter'] acc = self.model_progress['acc'].data.cpu().numpy() / self.model_progress['iter'] return loss, acc def get_object(self, tokenizer, model): no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': self.args.weight_decay}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] criterion = nn.CrossEntropyLoss() optimizer = optim.AdamW(optimizer_grouped_parameters, lr=self.args.lr) return criterion, optimizer def get_scheduler(self, optim, train_loader): train_total = len(train_loader) * self.args.epochs scheduler = get_linear_schedule_with_warmup(optim, num_warmup_steps=self.args.warmup_ratio * train_total, num_training_steps=train_total) return scheduler, train_total def model_setting(self): accelerator = Accelerator(fp16=False) loader, tokenizer = get_loader(self.args, self.metric) model = KoSentenceT5(AutoModel.from_pretrained(self.args.model)) vocab = tokenizer.get_vocab() model.model.resize_token_embeddings(len(vocab)) if self.args.multi_gpu == 'True': model = nn.DataParallel(model, output_device=0) model.to(self.args.device) criterion, optimizer = self.get_object(tokenizer, model) if self.args.train == 'True': scheduler, total_steps = self.get_scheduler(optimizer, loader['train']) self.total_steps = total_steps else: scheduler = None config = {'loader': loader, 'optimizer': optimizer, 'criterion': criterion, 'scheduler': scheduler, 'tokenizer': tokenizer, 'accelerator': accelerator, 'args': self.args, 'model': model} config['model'], config['optimizer'] = accelerator.prepare(model, optimizer) self.config = config return self.config def train(self, epoch): self.config['model'].train() train_loader = self.config['accelerator'].prepare(self.config['loader']['train']) for step, batch in enumerate(tqdm(train_loader)): self.config['optimizer'].zero_grad() inputs = batch loss = self.run(inputs, type='train') loss = torch.mean(loss) if self.args.fp16 == 'True' and self.args.multi_gpu == 'False': with amp.scale_loss(loss, self.config['optimizer']) as scaled_loss: scaled_loss.backward() else: self.config['accelerator'].backward(loss) self.config['optimizer'].step() self.config['scheduler'].step() self.progress(loss.data) if self.model_progress['iter'] % self.args.eval_steps == 0 or self.model_progress['iter'] == self.total_steps: valid_score = self.valid() performance = {'tl': loss, 'vs': valid_score, 'ep': epoch, 'step': self.model_progress['iter']} self.metric.save_model(self.config, performance, self.model_checker) def valid(self): self.config['model'].eval() self.dev_progress = self.dev_progress.fromkeys(self.dev_progress, 0) score_indicator = {'eval_pearson_cosine': 0, 'eval_spearman_cosine': 0, 'eval_pearson_manhattan': 0, 'eval_spearman_manhattan': 0, 'eval_pearson_euclidean': 0, 'eval_spearman_euclidean': 0, 'eval_pearson_dot': 0, 'eval_spearman_dot': 0} valid_loader = self.config['accelerator'].prepare(self.config['loader']['valid']) with torch.no_grad(): for step, batch in enumerate(valid_loader): inputs = batch score = self.run(inputs, indicator=score_indicator, type='valid') self.progress_validation(score) score = self.metric.cal_dev_score(self.dev_progress, score_indicator) return score def test(self): self.config['model'].load_state_dict(torch.load(self.args.path_to_saved_model)) self.config['model'].eval() self.dev_progress = self.dev_progress.fromkeys(self.dev_progress, 0) score_indicator = {'eval_pearson_cosine': 0, 'eval_spearman_cosine': 0, 'eval_pearson_manhattan': 0, 'eval_spearman_manhattan': 0, 'eval_pearson_euclidean': 0, 'eval_spearman_euclidean': 0, 'eval_pearson_dot': 0, 'eval_spearman_dot': 0} with torch.no_grad(): for step, batch in enumerate(self.config['loader']['test']): inputs = batch score = self.run(inputs, indicator=score_indicator, type='test') self.progress_validation(score) logger.info('### TEST SCORE ###') score = self.metric.cal_dev_score(self.dev_progress, score_indicator) ================================================ FILE: KoSentenceT5/model/utils.py ================================================ import os import torch import logging from tensorboardX import SummaryWriter logger = logging.getLogger(__name__) writer = SummaryWriter() class Metric(): def __init__(self, args): self.args = args def get_lr(self, optimizer): return optimizer.state_dict()['param_groups'][0]['lr'] def count_parameters(self, model): print(sum(p.numel() for p in model.parameters() if p.requires_grad)) def cal_acc(self, yhat, y): with torch.no_grad(): yhat = yhat.max(dim=-1)[1] # [0]: max value, [1]: index of max value acc = (yhat == y).float().mean() return acc def cal_time(self, start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs def cal_dev_score(self, score, indicator): validation_score = score['score'] / score['iter'] for key, value in indicator.items(): indicator[key] /= score['iter'] print("\n\nCosine-Similarity :\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_cosine'], indicator['eval_spearman_cosine'])) print("Manhattan-Distance:\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_manhattan'], indicator['eval_spearman_manhattan'])) print("Euclidean-Distance:\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_euclidean'], indicator['eval_spearman_euclidean'])) print("Dot-Product-Similarity:\tPearson: {:.4f}\tSpearman: {:.4f}\n".format( indicator['eval_pearson_dot'], indicator['eval_spearman_dot'])) return validation_score def update_indicator(self, indicator, score): for key, value in indicator.items(): if key == 'eval_spearman_cosine': indicator[key] += score['eval_spearman_cosine'] elif key == 'eval_pearson_cosine': indicator[key] += score['eval_pearson_cosine'] elif key == 'eval_spearman_manhattan': indicator[key] += score['eval_spearman_manhattan'] elif key == 'eval_pearson_manhattan': indicator[key] += score['eval_pearson_manhattan'] elif key == 'eval_spearman_euclidean': indicator[key] += score['eval_spearman_euclidean'] elif key == 'eval_pearson_euclidean': indicator[key] += score['eval_pearson_euclidean'] elif key == 'eval_spearman_dot': indicator[key] += score['eval_spearman_dot'] elif key == 'eval_pearson_dot': indicator[key] += score['eval_pearson_dot'] def draw_graph(self, cp): writer.add_scalars('loss_graph', {'train': cp['tl'], 'valid': cp['vl']}, cp['ep']) writer.add_scalars('acc_graph', {'train': cp['tma'], 'valid': cp['vma']}, cp['ep']) def performance_check(self, cp, config): print(f'\t==Epoch: {cp["ep"] + 1:02} | Epoch Time: {cp["epm"]}m {cp["eps"]}s==') print(f'\t==Train Loss: {cp["tl"]:.4f} | Train acc: {cp["tma"]:.4f}==') print(f'\t==Valid Loss: {cp["vl"]:.4f} | Valid acc: {cp["vma"]:.4f}==') print(f'\t==Epoch latest LR: {self.get_lr(config["optimizer"]):.9f}==\n') def print_size_of_model(self, model): torch.save(model.state_dict(), "temp.p") print('Size (MB):', os.path.getsize("temp.p") / 1e6) os.remove('temp.p') def move2device(self, sample, device): if len(sample) == 0: return {} def _move_to_device(maybe_tensor, device): if torch.is_tensor(maybe_tensor): return maybe_tensor.to(device) elif isinstance(maybe_tensor, dict): return { key: _move_to_device(value, device) for key, value in maybe_tensor.items() } elif isinstance(maybe_tensor, list): return [_move_to_device(x, device) for x in maybe_tensor] elif isinstance(maybe_tensor, tuple): return [_move_to_device(x, device) for x in maybe_tensor] else: return maybe_tensor return _move_to_device(sample, device) def save_model(self, config, cp, pco): if not os.path.exists(config['args'].path_to_save): os.makedirs(config['args'].path_to_save) sorted_path = config['args'].path_to_save + "kosimcse-" + config['args'].model.replace("/", "-") + '.pt' if cp['vs'] > pco['best_valid_score']: # pco['early_stop_patient'] = 0 pco['best_valid_score'] = cp['vs'] unwrapped_model = config['accelerator'].unwrap_model(config['model']) config['accelerator'].save(unwrapped_model.state_dict(), sorted_path) #state = {'model': config['model'].state_dict(), # 'optimizer': config['optimizer'].state_dict()} #torch.save(state, sorted_path) print(f'\t## SAVE {sorted_path} |' f' valid_score: {cp["vs"]:.4f} |' f' epochs: {cp["ep"]} |' f' steps: {cp["step"]} ##\n') # self.draw_graph(cp) # self.performance_check(cp, config) def pytorch_cos_sim(a, b): """ Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. This function can be used as a faster replacement for 1-scipy.spatial.distance.cdist(a,b) :return: Matrix with res[i][j] = cos_sim(a[i], b[j]) """ if not isinstance(a, torch.Tensor): a = torch.tensor(a) if not isinstance(b, torch.Tensor): b = torch.tensor(b) if len(a.shape) == 1: a = a.unsqueeze(0) if len(b.shape) == 1: b = b.unsqueeze(0) a_norm = a / a.norm(dim=1)[:, None] b_norm = b / b.norm(dim=1)[:, None] return torch.mm(a_norm, b_norm.transpose(0, 1)) ================================================ FILE: KoSentenceT5/run_example.sh ================================================ #!/bin/bash CUDA_VISIBLE_DEVICES=0,1 python main.py \ --model etri-t5 \ --multi_gpu True \ --test False \ --max_len 110 \ --batch_size 64 \ --epochs 2 \ --eval_steps 125 \ --lr 0.0001 \ --warmup_ratio 0.01 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --train_data train_nli.tsv \ --valid_data valid_sts.tsv CUDA_VISIBLE_DEVICES=1 python main.py \ --model etri-t5 \ --train False \ --test True \ --max_len 110 \ --batch_size 64 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --test_data test_sts.tsv \ --path_to_saved_model output/ ================================================ FILE: KoSimCSE/README.md ================================================ # KoSimCSE [[Github]](https://github.com/princeton-nlp/SimCSE) Official implementation of SimCSE.
KoSimCSE : Korean Sentence Embeddings using contrastive learning. ## Quick start - If you want to do inference quickly, download the pre-trained models and then you can start some downstream tasks. ``` bash get_model_checkpoint.sh python SemanticSearch.py ``` ## Training - Before training or evaluation, please download the datasets by running ``` bash get_model_dataset.sh ``` ### Train KoSimCSE (Supervised Only) ``` python main.py \ --model klue/bert-base \ --test False \ --max_len 50 \ --batch_size 256 \ --epochs 2 \ --eval_steps 125 \ --lr 0.0001 \ --warmup_ratio 0.1 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --train_data train_nli.tsv \ --valid_data valid_sts.tsv ``` ### Evaluation ``` python main.py \ --model klue/bert-base \ --train False \ --test True \ --max_len 50 \ --batch_size 256 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --test_data test_sts.tsv \ --path_to_saved_model output/kosimcse-klue-bert-base.pt ``` ### Run Examples ``` bash run_example.sh ``` ### Hyperparameters - Train KoSimCSE (BERT BASE) 1. Pooling Method: [CLS] strategy 2. Batch Size: 256 3. Evaluation Steps: 125 4. Epochs: 2 5. Token Max Length: 128 6. Learning Rate: 0.0001 7. Warmup Ratio: 0.1 8. Temperature: 0.05 - Train KoSimCSE (RoBERTa BASE) 1. Pooling Method: [CLS] strategy 2. Batch Size: 256 3. Evaluation Steps: 125 4. Epochs: 2 5. Token Max Length: 128 6. Learning Rate: 0.0001 7. Warmup Ratio: 0.05 8. Temperature: 0.05 ### Semantic Search ``` python SemanticSearch.py ``` ```python from model.simcse.bert import BERT from transformers import AutoModel, AutoTokenizer def main(): model = BERT(AutoModel.from_pretrained('BM-K/KoSimCSE-roberta')) tokenizer = AutoTokenizer.from_pretrained('BM-K/KoSimCSE-roberta') model.to(device) model.eval() model, tokenizer, device = example_model_setting(model_name) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 속으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.'] inputs_corpus = convert_to_tensor(corpus, tokenizer, device) corpus_embeddings = model.encode(inputs_corpus, device) # Query sentences: queries = ['한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] # Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity top_k = 5 for query in queries: query_embedding = model.encode(convert_to_tensor([query], tokenizer, device), device) cos_scores = pytorch_cos_sim(query_embedding, corpus_embeddings)[0] cos_scores = cos_scores.cpu().detach().numpy() top_results = np.argpartition(-cos_scores, range(top_k))[0:top_k] print("\n\n======================\n\n") print("Query:", query) print("\nTop 5 most similar sentences in corpus:") for idx in top_results[0:top_k]: print(corpus[idx].strip(), "(Score: %.4f)" % (cos_scores[idx])) ``` - Results are as follows : ``` Query: 한 남자가 파스타를 먹는다. Top 5 most similar sentences in corpus: 한 남자가 음식을 먹는다. (Score: 0.6141) 한 남자가 빵 한 조각을 먹는다. (Score: 0.5952) 한 남자가 말을 탄다. (Score: 0.1231) 한 남자가 담으로 싸인 땅에서 백마를 타고 있다. (Score: 0.0752) 두 남자가 수레를 숲 솦으로 밀었다. (Score: 0.0486) ====================== Query: 고릴라 의상을 입은 누군가가 드럼을 연주하고 있다. Top 5 most similar sentences in corpus: 원숭이 한 마리가 드럼을 연주한다. (Score: 0.6656) 치타 한 마리가 먹이 뒤에서 달리고 있다. (Score: 0.2988) 한 여자가 바이올린을 연주한다. (Score: 0.1566) 한 남자가 말을 탄다. (Score: 0.1112) 한 남자가 담으로 싸인 땅에서 백마를 타고 있다. (Score: 0.0262) ====================== Query: 치타가 들판을 가로 질러 먹이를 쫓는다. Top 5 most similar sentences in corpus: 치타 한 마리가 먹이 뒤에서 달리고 있다. (Score: 0.7570) 두 남자가 수레를 숲 솦으로 밀었다. (Score: 0.3658) 원숭이 한 마리가 드럼을 연주한다. (Score: 0.3583) 한 남자가 말을 탄다. (Score: 0.0505) 그 여자가 아이를 돌본다. (Score: -0.0087) ``` ### Clustering ```python import torch from tqdm import tqdm from sklearn.cluster import KMeans from transformers import ( AutoModel, AutoTokenizer ) def encode(model=None, tokenizer=None, corpus=None, ): tokenized_corpus = tokenizer(corpus, truncation=True, return_tensors='pt', max_length=token_max_len, padding='max_length') embeddings, _ = model(input_ids=tokenized_corpus['input_ids'].to(device), token_type_ids=tokenized_corpus['token_type_ids'].to(device), attention_mask=tokenized_corpus['attention_mask'].to(device), return_dict=False) return embeddings[:, 0].cpu().detach() def get_model(): model = AutoModel.from_pretrained('BM-K/KoSimCSE-roberta-multitask') tokenizer = AutoTokenizer.from_pretrained('BM-K/KoSimCSE-roberta-multitask') model.eval() return model.to(device), tokenizer def get_cluster(corpus_embeddings ): clustering_model = KMeans(n_clusters=num_clusters) clustering_model.fit(corpus_embeddings) return clustering_model.labels_ def main(): # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.', '한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] n_corpus = len(corpus) model, tokenizer = get_model() corpus_embeddings = torch.tensor([]) for start_idx in tqdm(range(0, n_corpus, embedding_batch)): batch_corps = corpus[start_idx:start_idx+embedding_batch] batch_embedding = encode(model, tokenizer, batch_corps) corpus_embeddings = torch.cat([corpus_embeddings, batch_embedding], dim=0) assert n_corpus == corpus_embeddings.size(0) cluster_assignment = get_cluster(corpus_embeddings) clustered_sentences = [[] for _ in range(num_clusters)] for sentence_id, cluster_id in enumerate(cluster_assignment): clustered_sentences[cluster_id].append(corpus[sentence_id]) for i, cluster in enumerate(clustered_sentences): print("Cluster ", i + 1) print(cluster) print("") if __name__ == '__main__': num_clusters = 5 token_max_len = 50 embedding_batch = 3 device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') main() ``` - Results are as follows : ``` Cluster 1 ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '한 남자가 파스타를 먹는다.'] Cluster 2 ['한 여자가 바이올린을 연주한다.', '원숭이 한 마리가 드럼을 연주한다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.'] Cluster 3 ['한 남자가 말을 탄다.', '두 남자가 수레를 숲 솦으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.'] Cluster 4 ['그 여자가 아이를 돌본다.'] Cluster 5 ['치타 한 마리가 먹이 뒤에서 달리고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] ``` ================================================ FILE: KoSimCSE/SemanticSearch.py ================================================ import numpy as np from model.utils import pytorch_cos_sim from data.dataloader import convert_to_tensor, example_model_setting def main(): model_name = 'klue/bert-base' model_ckpt = '../Checkpoint/KoSimCSE/kosimcse-klue-bert-base.pt' model, tokenizer, device = example_model_setting(model_ckpt, model_name) # Corpus with example sentences corpus = ['한 남자가 음식을 먹는다.', '한 남자가 빵 한 조각을 먹는다.', '그 여자가 아이를 돌본다.', '한 남자가 말을 탄다.', '한 여자가 바이올린을 연주한다.', '두 남자가 수레를 숲 속으로 밀었다.', '한 남자가 담으로 싸인 땅에서 백마를 타고 있다.', '원숭이 한 마리가 드럼을 연주한다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.'] inputs_corpus = convert_to_tensor(corpus, tokenizer, device) corpus_embeddings = model.encode(inputs_corpus, device) # Query sentences: queries = ['한 남자가 파스타를 먹는다.', '고릴라 의상을 입은 누군가가 드럼을 연주하고 있다.', '치타가 들판을 가로 질러 먹이를 쫓는다.'] # Find the closest 5 sentences of the corpus for each query sentence based on cosine similarity top_k = 5 for query in queries: query_embedding = model.encode(convert_to_tensor([query], tokenizer, device), device) cos_scores = pytorch_cos_sim(query_embedding, corpus_embeddings)[0] cos_scores = cos_scores.cpu().detach().numpy() top_results = np.argpartition(-cos_scores, range(top_k))[0:top_k] print("\n\n======================\n\n") print("Query:", query) print("\nTop 5 most similar sentences in corpus:") for idx in top_results[0:top_k]: print(corpus[idx].strip(), "(Score: %.4f)" % (cos_scores[idx])) if __name__ == '__main__': main() ================================================ FILE: KoSimCSE/apex/RNN/README.md ================================================ Under construction... ================================================ FILE: KoSimCSE/apex/RNN/RNNBackend.py ================================================ import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F import math def is_iterable(maybe_iterable): return isinstance(maybe_iterable, list) or isinstance(maybe_iterable, tuple) def flatten_list(tens_list): """ flatten_list """ if not is_iterable(tens_list): return tens_list return torch.cat(tens_list, dim=0).view(len(tens_list), *tens_list[0].size() ) #These modules always assumes batch_first class bidirectionalRNN(nn.Module): """ bidirectionalRNN """ def __init__(self, inputRNN, num_layers=1, dropout = 0): super(bidirectionalRNN, self).__init__() self.dropout = dropout self.fwd = stackedRNN(inputRNN, num_layers=num_layers, dropout = dropout) self.bckwrd = stackedRNN(inputRNN.new_like(), num_layers=num_layers, dropout = dropout) self.rnns = nn.ModuleList([self.fwd, self.bckwrd]) #collect hidden option will return all hidden/cell states from entire RNN def forward(self, input, collect_hidden=False): """ forward() """ seq_len = input.size(0) bsz = input.size(1) fwd_out, fwd_hiddens = list(self.fwd(input, collect_hidden = collect_hidden)) bckwrd_out, bckwrd_hiddens = list(self.bckwrd(input, reverse=True, collect_hidden = collect_hidden)) output = torch.cat( [fwd_out, bckwrd_out], -1 ) hiddens = tuple( torch.cat(hidden, -1) for hidden in zip( fwd_hiddens, bckwrd_hiddens) ) return output, hiddens def reset_parameters(self): """ reset_parameters() """ for rnn in self.rnns: rnn.reset_parameters() def init_hidden(self, bsz): """ init_hidden() """ for rnn in self.rnns: rnn.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for rnn in self.rnns: rnn.detachHidden() def reset_hidden(self, bsz): """ reset_hidden() """ for rnn in self.rnns: rnn.reset_hidden(bsz) def init_inference(self, bsz): """ init_inference() """ for rnn in self.rnns: rnn.init_inference(bsz) #assumes hidden_state[0] of inputRNN is output hidden state #constructor either takes an RNNCell or list of RNN layers class stackedRNN(nn.Module): """ stackedRNN """ def __init__(self, inputRNN, num_layers=1, dropout=0): super(stackedRNN, self).__init__() self.dropout = dropout if isinstance(inputRNN, RNNCell): self.rnns = [inputRNN] for i in range(num_layers-1): self.rnns.append(inputRNN.new_like(inputRNN.output_size)) elif isinstance(inputRNN, list): assert len(inputRNN) == num_layers, "RNN list length must be equal to num_layers" self.rnns=inputRNN else: raise RuntimeError() self.nLayers = len(self.rnns) self.rnns = nn.ModuleList(self.rnns) ''' Returns output as hidden_state[0] Tensor([sequence steps][batch size][features]) If collect hidden will also return Tuple( [n_hidden_states][sequence steps] Tensor([layer][batch size][features]) ) If not collect hidden will also return Tuple( [n_hidden_states] Tensor([layer][batch size][features]) ''' def forward(self, input, collect_hidden=False, reverse=False): """ forward() """ seq_len = input.size(0) bsz = input.size(1) inp_iter = reversed(range(seq_len)) if reverse else range(seq_len) hidden_states = [[] for i in range(self.nLayers)] outputs = [] for seq in inp_iter: for layer in range(self.nLayers): if layer == 0: prev_out = input[seq] outs = self.rnns[layer](prev_out) if collect_hidden: hidden_states[layer].append(outs) elif seq == seq_len-1: hidden_states[layer].append(outs) prev_out = outs[0] outputs.append(prev_out) if reverse: outputs = list(reversed(outputs)) ''' At this point outputs is in format: list( [seq_length] x Tensor([bsz][features]) ) need to convert it to: list( Tensor([seq_length][bsz][features]) ) ''' output = flatten_list(outputs) ''' hidden_states at this point is in format: list( [layer][seq_length][hidden_states] x Tensor([bsz][features]) ) need to convert it to: For not collect hidden: list( [hidden_states] x Tensor([layer][bsz][features]) ) For collect hidden: list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) ) ''' if not collect_hidden: seq_len = 1 n_hid = self.rnns[0].n_hidden_states new_hidden = [ [ [ None for k in range(self.nLayers)] for j in range(seq_len) ] for i in range(n_hid) ] for i in range(n_hid): for j in range(seq_len): for k in range(self.nLayers): new_hidden[i][j][k] = hidden_states[k][j][i] hidden_states = new_hidden #Now in format list( [hidden_states][seq_length][layer] x Tensor([bsz][features]) ) #Reverse seq_length if reverse if reverse: hidden_states = list( list(reversed(list(entry))) for entry in hidden_states) #flatten layer dimension into tensor hiddens = list( list( flatten_list(seq) for seq in hidden ) for hidden in hidden_states ) #Now in format list( [hidden_states][seq_length] x Tensor([layer][bsz][features]) ) #Remove seq_length dimension if not collect_hidden if not collect_hidden: hidden_states = list( entry[0] for entry in hidden_states) return output, hidden_states def reset_parameters(self): """ reset_parameters() """ for rnn in self.rnns: rnn.reset_parameters() def init_hidden(self, bsz): """ init_hidden() """ for rnn in self.rnns: rnn.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for rnn in self.rnns: rnn.detach_hidden() def reset_hidden(self, bsz): """ reset_hidden() """ for rnn in self.rnns: rnn.reset_hidden(bsz) def init_inference(self, bsz): """ init_inference() """ for rnn in self.rnns: rnn.init_inference(bsz) class RNNCell(nn.Module): """ RNNCell gate_multiplier is related to the architecture you're working with For LSTM-like it will be 4 and GRU-like will be 3. Always assumes input is NOT batch_first. Output size that's not hidden size will use output projection Hidden_states is number of hidden states that are needed for cell if one will go directly to cell as tensor, if more will go as list """ def __init__(self, gate_multiplier, input_size, hidden_size, cell, n_hidden_states = 2, bias = False, output_size = None): super(RNNCell, self).__init__() self.gate_multiplier = gate_multiplier self.input_size = input_size self.hidden_size = hidden_size self.cell = cell self.bias = bias self.output_size = output_size if output_size is None: self.output_size = hidden_size self.gate_size = gate_multiplier * self.hidden_size self.n_hidden_states = n_hidden_states self.w_ih = nn.Parameter(torch.Tensor(self.gate_size, self.input_size)) self.w_hh = nn.Parameter(torch.Tensor(self.gate_size, self.output_size)) #Check if there's recurrent projection if(self.output_size != self.hidden_size): self.w_ho = nn.Parameter(torch.Tensor(self.output_size, self.hidden_size)) self.b_ih = self.b_hh = None if self.bias: self.b_ih = nn.Parameter(torch.Tensor(self.gate_size)) self.b_hh = nn.Parameter(torch.Tensor(self.gate_size)) #hidden states for forward self.hidden = [ None for states in range(self.n_hidden_states)] self.reset_parameters() def new_like(self, new_input_size=None): """ new_like() """ if new_input_size is None: new_input_size = self.input_size return type(self)(self.gate_multiplier, new_input_size, self.hidden_size, self.cell, self.n_hidden_states, self.bias, self.output_size) #Use xavier where we can (weights), otherwise use uniform (bias) def reset_parameters(self, gain=1): """ reset_parameters() """ stdev = 1.0 / math.sqrt(self.hidden_size) for param in self.parameters(): param.data.uniform_(-stdev, stdev) ''' Xavier reset: def reset_parameters(self, gain=1): stdv = 1.0 / math.sqrt(self.gate_size) for param in self.parameters(): if (param.dim() > 1): torch.nn.init.xavier_normal(param, gain) else: param.data.uniform_(-stdv, stdv) ''' def init_hidden(self, bsz): """ init_hidden() """ for param in self.parameters(): if param is not None: a_param = param break for i, _ in enumerate(self.hidden): if(self.hidden[i] is None or self.hidden[i].data.size()[0] != bsz): if i==0: hidden_size = self.output_size else: hidden_size = self.hidden_size tens = a_param.data.new(bsz, hidden_size).zero_() self.hidden[i] = Variable(tens, requires_grad=False) def reset_hidden(self, bsz): """ reset_hidden() """ for i, _ in enumerate(self.hidden): self.hidden[i] = None self.init_hidden(bsz) def detach_hidden(self): """ detach_hidden() """ for i, _ in enumerate(self.hidden): if self.hidden[i] is None: raise RuntimeError("Must initialize hidden state before you can detach it") for i, _ in enumerate(self.hidden): self.hidden[i] = self.hidden[i].detach() def forward(self, input): """ forward() if not inited or bsz has changed this will create hidden states """ self.init_hidden(input.size()[0]) hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden self.hidden = self.cell(input, hidden_state, self.w_ih, self.w_hh, b_ih=self.b_ih, b_hh=self.b_hh) if(self.n_hidden_states > 1): self.hidden = list(self.hidden) else: self.hidden=[self.hidden] if self.output_size != self.hidden_size: self.hidden[0] = F.linear(self.hidden[0], self.w_ho) return tuple(self.hidden) ================================================ FILE: KoSimCSE/apex/RNN/__init__.py ================================================ from .models import LSTM, GRU, ReLU, Tanh, mLSTM __all__ = ['models'] ================================================ FILE: KoSimCSE/apex/RNN/cells.py ================================================ import torch import torch.nn as nn import torch.nn.functional as F from .RNNBackend import RNNCell from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend import math class mLSTMRNNCell(RNNCell): """ mLSTMRNNCell """ def __init__(self, input_size, hidden_size, bias = False, output_size = None): gate_multiplier = 4 super(mLSTMRNNCell, self).__init__(gate_multiplier, input_size, hidden_size, mLSTMCell, n_hidden_states = 2, bias = bias, output_size = output_size) self.w_mih = nn.Parameter(torch.Tensor(self.output_size, self.input_size)) self.w_mhh = nn.Parameter(torch.Tensor(self.output_size, self.output_size)) self.reset_parameters() def forward(self, input): """ mLSTMRNNCell.forward() """ #if not inited or bsz has changed this will create hidden states self.init_hidden(input.size()[0]) hidden_state = self.hidden[0] if self.n_hidden_states == 1 else self.hidden self.hidden = list( self.cell(input, hidden_state, self.w_ih, self.w_hh, self.w_mih, self.w_mhh, b_ih=self.b_ih, b_hh=self.b_hh) ) if self.output_size != self.hidden_size: self.hidden[0] = F.linear(self.hidden[0], self.w_ho) return tuple(self.hidden) def new_like(self, new_input_size=None): if new_input_size is None: new_input_size = self.input_size return type(self)( new_input_size, self.hidden_size, self.bias, self.output_size) def mLSTMCell(input, hidden, w_ih, w_hh, w_mih, w_mhh, b_ih=None, b_hh=None): """ mLSTMCell """ if input.is_cuda: igates = F.linear(input, w_ih) m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh) hgates = F.linear(m, w_hh) state = fusedBackend.LSTMFused.apply return state(igates, hgates, hidden[1], b_ih, b_hh) hx, cx = hidden m = F.linear(input, w_mih) * F.linear(hidden[0], w_mhh) gates = F.linear(input, w_ih, b_ih) + F.linear(m, w_hh, b_hh) ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1) ingate = F.sigmoid(ingate) forgetgate = F.sigmoid(forgetgate) cellgate = F.tanh(cellgate) outgate = F.sigmoid(outgate) cy = (forgetgate * cx) + (ingate * cellgate) hy = outgate * F.tanh(cy) return hy, cy ================================================ FILE: KoSimCSE/apex/RNN/models.py ================================================ import torch from torch.nn._functions.rnn import LSTMCell, RNNReLUCell, RNNTanhCell, GRUCell from .RNNBackend import bidirectionalRNN, stackedRNN, RNNCell from .cells import mLSTMRNNCell, mLSTMCell def toRNNBackend(inputRNN, num_layers, bidirectional=False, dropout = 0): """ :class:`toRNNBackend` """ if bidirectional: return bidirectionalRNN(inputRNN, num_layers, dropout = dropout) else: return stackedRNN(inputRNN, num_layers, dropout = dropout) def LSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`LSTM` """ inputRNN = RNNCell(4, input_size, hidden_size, LSTMCell, 2, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def GRU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`GRU` """ inputRNN = RNNCell(3, input_size, hidden_size, GRUCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def ReLU(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`ReLU` """ inputRNN = RNNCell(1, input_size, hidden_size, RNNReLUCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def Tanh(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`Tanh` """ inputRNN = RNNCell(1, input_size, hidden_size, RNNTanhCell, 1, bias, output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) def mLSTM(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None): """ :class:`mLSTM` """ inputRNN = mLSTMRNNCell(input_size, hidden_size, bias=bias, output_size=output_size) return toRNNBackend(inputRNN, num_layers, bidirectional, dropout=dropout) ================================================ FILE: KoSimCSE/apex/__init__.py ================================================ # May help avoid undefined symbol errors https://pytorch.org/cppdocs/notes/faq.html#undefined-symbol-errors-from-pytorch-aten import torch import warnings if torch.distributed.is_available(): from . import parallel from . import amp from . import fp16_utils # For optimizers and normalization there is no Python fallback. # Absence of cuda backend is a hard error. # I would like the errors from importing fused_adam_cuda or fused_layer_norm_cuda # to be triggered lazily, because if someone has installed with --cpp_ext and --cuda_ext # so they expect those backends to be available, but for some reason they actually aren't # available (for example because they built improperly in a way that isn't revealed until # load time) the error message is timely and visible. from . import optimizers from . import normalization from . import pyprof ================================================ FILE: KoSimCSE/apex/amp/README.md ================================================ # amp: Automatic Mixed Precision ## Annotating User Functions Nearly all PyTorch user code needs nothing more than the two steps above to use amp. After all, custom layers are built out of simpler PyTorch components, and amp already can see those. However, any custom C++ or CUDA code is outside of amp's (default) view of things. For example, suppose I implemented a new recurrent cell called a "forgetful recurrent unit" that calls directly into a CUDA backend: ```python from backend import FRUBackend def fru(input, hidden, weight, bias): # call to CUDA code FRUBackend(input, hidden, weight, bias) ``` In this case, it is possible to get a runtime type mismatch. For example, you might have `input` in fp16, and `weight` in fp32, and amp doesn't have the visibility to insert an appropriate cast. amp exposes two ways to handle "invisible" backend code: function annotations and explicit registration. #### Function annotation The first way to handle backend code is a set of function annotations: - `@amp.half_function` - `@amp.float_function` - `@amp.promote_function` These correspond to: - Cast all arguments to fp16 - Cast all argumnets fo fp32 - If there are any type mismatches, cast everything to the widest type In our example, we believe that the FRU unit is fp16-safe and will get performance gains from casting its arguments to fp16, so we write: ```python @amp.half_function def fru(input, hidden, weight, bias): #... ``` #### Explicit registration The other way to handle backend code is with explicit function registration: - `amp.register_half_function(module, function_name)` - `amp.register_float_function(module, function_name)` - `amp.register_promote_function(module, function_name)` When using this API, `module` is the containing class or module for the function, and `function_name` is the _string_ name of the function. Note that the function must be registered before the call to `amp.initalize()`. For our FRU unit, we can register the backend function directly: ```python import backend amp.register_half_function(backend, 'FRUBackend') ``` ================================================ FILE: KoSimCSE/apex/amp/__init__.py ================================================ from .amp import init, half_function, float_function, promote_function,\ register_half_function, register_float_function, register_promote_function from .handle import scale_loss, disable_casts from .frontend import initialize, state_dict, load_state_dict from ._amp_state import master_params, _amp_state ================================================ FILE: KoSimCSE/apex/amp/__version__.py ================================================ VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) ================================================ FILE: KoSimCSE/apex/amp/_amp_state.py ================================================ # This is a "header object" that allows different amp modules to communicate. # I'm a C++ guy, not a python guy. I decided this approach because it seemed most C++-like. # But apparently it's ok: # http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm import os import torch TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 1 and TORCH_MINOR < 8: from torch._six import container_abcs else: import collections.abc as container_abcs class AmpState(object): def __init__(self): self.hard_override=False self.allow_incoming_model_not_fp32 = False self.verbosity=1 # Attribute stash. Could also just stash things as global module attributes. _amp_state = AmpState() def warn_or_err(msg): if _amp_state.hard_override: print("Warning: " + msg) else: raise RuntimeError(msg) # I'm not sure if allowing hard_override is a good idea. # + " If you're sure you know what you're doing, supply " + # "hard_override=True to amp.initialize.") def maybe_print(msg, rank0=False): distributed = torch.distributed.is_available() and \ torch.distributed.is_initialized() and \ torch.distributed.get_world_size() > 1 if _amp_state.verbosity > 0: if rank0: if distributed: if torch.distributed.get_rank() == 0: print(msg) else: print(msg) else: print(msg) # def iter_params(param_groups): # for group in param_groups: # for p in group['params']: # yield p def master_params(optimizer): """ Generator expression that iterates over the params owned by ``optimizer``. Args: optimizer: An optimizer previously returned from ``amp.initialize``. """ for group in optimizer.param_groups: for p in group['params']: yield p ================================================ FILE: KoSimCSE/apex/amp/_initialize.py ================================================ import torch from torch._six import string_classes import functools import numpy as np import sys from types import MethodType import warnings from ._amp_state import _amp_state, warn_or_err, container_abcs from .handle import disable_casts from .scaler import LossScaler from ._process_optimizer import _process_optimizer from apex.fp16_utils import convert_network from ..fp16_utils import FP16_Optimizer as FP16_Optimizer_general from ..contrib.optimizers import FP16_Optimizer as FP16_Optimizer_for_fused if torch.distributed.is_available(): from ..parallel import DistributedDataParallel as apex_DDP from ..parallel.LARC import LARC def to_type(dtype, t): if isinstance(t, torch.Tensor): if not t.is_cuda: # This should not be a hard error, since it may be legitimate. warnings.warn("An input tensor was not cuda.") # GANs require this. # if t.requires_grad: # warn_or_err("input data requires grad. Since input data is not a model parameter,\n" # "its gradients will not be properly allreduced by DDP.") if t.is_floating_point(): return t.to(dtype) return t else: # Trust the user's custom batch type, that's all I can do here. return t.to(dtype) # Modified from torch.optim.optimizer.py. This is a bit more general than casted_args in utils.py. def applier(value, fn): if isinstance(value, torch.Tensor): return fn(value) elif isinstance(value, string_classes): return value elif isinstance(value, np.ndarray): return value elif hasattr(value, "to"): # Allow handling of custom batch classes return fn(value) elif isinstance(value, container_abcs.Mapping): return {applier(k, fn) : applier(v, fn) for k, v in value.items()} elif isinstance(value, container_abcs.Iterable): return type(value)(applier(v, fn) for v in value) else: # Do I want this to fire off even if someone chooses to pass something ordinary like # an int or float? May be more annoying than it's worth. # print("Warning: unrecognized type in applier. If your input data is a custom class, " # "provide it with a .to(dtype) method which converts its floating-point Tensors to dtype. " # "Amp will check for your custom to() and invoke it to cast the batch's " # "floating-point Tensors to the appropriate type. " # "Also, if your data is a custom class, it is your responsibility to ensure that " # "any Tensors you want to be cuda are already cuda." return value def check_models(models): for model in models: parallel_type = None if isinstance(model, torch.nn.parallel.DistributedDataParallel): parallel_type = "torch.nn.parallel.DistributedDataParallel" if ('apex_DDP' in sys.modules) and isinstance(model, apex_DDP): parallel_type = "apex.parallel.DistributedDataParallel" if isinstance(model, torch.nn.parallel.DataParallel): parallel_type = "torch.nn.parallel.DataParallel" if parallel_type is not None: raise RuntimeError("Incoming model is an instance of {}. ".format(parallel_type) + "Parallel wrappers should only be applied to the model(s) AFTER \n" "the model(s) have been returned from amp.initialize.") def check_params_fp32(models): for model in models: for name, param in model.named_parameters(): if param.is_floating_point(): if 'Half' in param.type(): warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you do not need to call .half() on your model\n" "before passing it, no matter what optimization level you choose.".format( name, param.type())) elif not param.is_cuda: warn_or_err("Found param {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you need to provide a model with parameters\n" "located on a CUDA device before passing it no matter what optimization level\n" "you chose. Use model.to('cuda') to use the default device.".format( name, param.type())) # Backward compatibility for PyTorch 0.4 if hasattr(model, 'named_buffers'): buf_iter = model.named_buffers() else: buf_iter = model._buffers for obj in buf_iter: if type(obj)==tuple: name, buf = obj else: name, buf = obj, buf_iter[obj] if buf.is_floating_point(): if 'Half' in buf.type(): warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you do not need to call .half() on your model\n" "before passing it, no matter what optimization level you choose.".format( name, buf.type())) elif not buf.is_cuda: warn_or_err("Found buffer {} with type {}, expected torch.cuda.FloatTensor.\n" "When using amp.initialize, you need to provide a model with buffers\n" "located on a CUDA device before passing it no matter what optimization level\n" "you chose. Use model.to('cuda') to use the default device.".format( name, buf.type())) def check_optimizers(optimizers): for optim in optimizers: bad_optim_type = None if isinstance(optim, FP16_Optimizer_general): bad_optim_type = "apex.fp16_utils.FP16_Optimizer" if isinstance(optim, FP16_Optimizer_for_fused): bad_optim_type = "apex.optimizers.FP16_Optimizer" if bad_optim_type is not None: raise RuntimeError("An incoming optimizer is an instance of {}. ".format(bad_optim_type) + "The optimizer(s) passed to amp.initialize() must be bare \n" "instances of either ordinary Pytorch optimizers, or Apex fused \n" "optimizers.\n") class O2StateDictHook(object): def __init__(self, fn): self.fn = fn def __call__(self, module, state_dict, prefix, local_metadata): for key in state_dict: param = state_dict[key] if 'Half' in param.type(): param = param.to(torch.float32) state_dict[key] = param def _initialize(models, optimizers, properties, num_losses=1, cast_model_outputs=None): from .amp import init as amp_init optimizers_was_list = False if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)): optimizers = [optimizers] elif optimizers is None: optimizers = [] elif isinstance(optimizers, list): optimizers_was_list = True check_optimizers(optimizers) else: check_optimizers([optimizers]) raise TypeError("optimizers must be either a single optimizer or a list of optimizers.") if isinstance(models, torch.nn.Module): models_was_list = False models = [models] elif isinstance(models, list): models_was_list = True else: raise TypeError("models must be either a single model or a list of models.") check_models(models) if not _amp_state.allow_incoming_model_not_fp32: check_params_fp32(models) # In the future, when FP16_Optimizer can be deprecated and master weights can # become an attribute, remember to stash master weights before casting the model. if properties.cast_model_type: if properties.keep_batchnorm_fp32: for model in models: convert_network(model, properties.cast_model_type) else: for model in models: model.to(properties.cast_model_type) input_caster = functools.partial(to_type, properties.cast_model_type) if cast_model_outputs is not None: output_caster = functools.partial(to_type, cast_model_outputs) else: output_caster = functools.partial(to_type, torch.float32) for model in models: # Patch the forward method to cast incoming data to the correct type, and # outgoing data to float32, so "the user never needs to call .half()." # I like writing things explicitly more than decorators. def patch_forward(old_fwd): def new_fwd(*args, **kwargs): output = old_fwd(*applier(args, input_caster), **applier(kwargs, input_caster)) return applier(output, output_caster) return new_fwd model.forward = patch_forward(model.forward) # State dict trick to recast any preexisting per-param state tensors for optimizer in optimizers: optimizer.load_state_dict(optimizer.state_dict()) # patch model.state_dict() to return float32 params for model in models: for module in model.modules(): module._register_state_dict_hook(O2StateDictHook(functools.partial(to_type, torch.float32))) elif cast_model_outputs is not None: output_caster = functools.partial(to_type, cast_model_outputs) for model in models: def patch_forward(old_fwd): def new_fwd(*args, **kwargs): output = old_fwd(*args, **kwargs) return applier(output, output_caster) return new_fwd model.forward = patch_forward(model.forward) for i, optimizer in enumerate(optimizers): optimizers[i] = _process_optimizer(optimizer, properties) _amp_state.loss_scalers = [] for _ in range(num_losses): _amp_state.loss_scalers.append(LossScaler(properties.loss_scale, min_loss_scale=_amp_state.min_loss_scale, max_loss_scale=_amp_state.max_loss_scale)) if properties.patch_torch_functions: # handle is unused here. It's accessible later through a global value anyway. handle = amp_init(loss_scale=properties.loss_scale, verbose=(_amp_state.verbosity == 2)) for optimizer in optimizers: # Disable Amp casting for the optimizer step, because it should only be # applied to FP32 master params anyway. def patch_step(old_step): def new_step(self, *args, **kwargs): with disable_casts(): output = old_step(*args, **kwargs) return output return new_step optimizer.step = MethodType(patch_step(optimizer.step), optimizer) if optimizers_was_list: if models_was_list: return models, optimizers else: return models[0], optimizers else: if models_was_list: if len(optimizers) == 0: return models else: return models, optimizers[0] else: if len(optimizers) == 0: return models[0] else: return models[0], optimizers[0] ================================================ FILE: KoSimCSE/apex/amp/_process_optimizer.py ================================================ import types from ..fp16_utils import master_params_to_model_params from ..multi_tensor_apply import multi_tensor_applier from ._amp_state import maybe_print import torch from ..optimizers import FusedSGD class AmpOptimizerState(object): def __init__(self): pass def _master_params_to_model_params(self): stash = self._amp_stash if multi_tensor_applier.available: if len(stash.all_fp16_params) > 0: multi_tensor_applier( stash.multi_tensor_scale, stash.dummy_overflow_buf, [stash.all_fp32_from_fp16_params, stash.all_fp16_params], 1.0) else: for fp16_group, fp32_from_fp16_group in zip(stash.fp16_groups, stash.fp32_from_fp16_groups): master_params_to_model_params(fp16_group, fp32_from_fp16_group) def lazy_init_with_master_weights(self): stash = self._amp_stash stash.fp16_groups = [] stash.fp32_from_fp16_groups = [] stash.fp32_from_fp32_groups = [] for i, param_group in enumerate(self.param_groups): # maybe_print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(param_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': # maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}" # .format(param.size())) fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True param_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) # Reset existing state dict key to the new master param. # We still need to recast per-param state tensors, if any, to FP32. if param in self.state: self.state[master_param] = self.state.pop(param) elif param.type() == 'torch.cuda.FloatTensor': # maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}" # .format(param.size())) fp32_params_this_group.append(param) param_group['params'][i] = param else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.fp16_groups.append(fp16_params_this_group) stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) stash.fp32_from_fp32_groups.append(fp32_params_this_group) stash.all_fp16_params = [] for group in stash.fp16_groups: stash.all_fp16_params += group stash.all_fp32_from_fp16_params = [] for group in stash.fp32_from_fp16_groups: stash.all_fp32_from_fp16_params += group stash.all_fp32_from_fp32_params = [] for group in stash.fp32_from_fp32_groups: stash.all_fp32_from_fp32_params += group # all_fp16_grad_stash is only needed for fused optimizers. stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params] # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params] stash.all_fp32_from_fp32_grad_stash = [None for _ in stash.all_fp32_from_fp32_params] for param in stash.all_fp32_from_fp16_params: param.grad = None for param in stash.all_fp32_from_fp32_params: param.grad = None # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors self.load_state_dict(self.state_dict()) def post_backward_models_are_masters(scaler, params, stashed_grads, scale_override=None): grads_have_scale, stashed_have_scale, out_scale = scaler.loss_scale(), 1.0, 1.0 # not much to do if scale == 1.0 and static scaling if scaler.loss_scale() == 1.0 and not scaler.dynamic: # Clear the stash. for i in range(len(stashed_grads)): stashed_grads[i] = None return if scale_override is not None: grads_have_scale, stashed_have_scale, out_scale = scale_override # This is a lot of python overhead... grads_needing_unscale = [] grads_needing_unscale_with_stash = [] stashed = [] for param, stashed_grad in zip(params, stashed_grads): if param.grad is None and stashed_grad is not None: param.grad = stashed_grad elif param.grad is not None and stashed_grad is None: grads_needing_unscale.append(param.grad) elif param.grad is not None and stashed_grad is not None: grads_needing_unscale_with_stash.append(param.grad) stashed.append(stashed_grad) else: # param.grad is None and stashed_grad is None continue # unscale() implements grads*(1/scale), so "scale" should be grads_have_scale/out_scale. if len(grads_needing_unscale) > 0: scaler.unscale( grads_needing_unscale, grads_needing_unscale, None, # unused_scale, currently present to avoid API breakage elsewhere models_are_masters=True, scale_override=grads_have_scale/out_scale) if len(grads_needing_unscale_with_stash) > 0: scaler.unscale_with_stashed( grads_needing_unscale_with_stash, stashed, grads_needing_unscale_with_stash, scale_override=(grads_have_scale, stashed_have_scale, out_scale)) # Clear the stash. for i in range(len(stashed_grads)): stashed_grads[i] = None def prepare_backward_with_master_weights(self): stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): # Set up to leverage grad copy elision. # This may behave differently from an unpatched optimizer if zero_grad is used and the param is unused. param.grad = None # for i, param in enumerate(stash.all_fp32_from_fp16_params): # stash.all_fp32_from_fp16_grad_stash[i] = param.grad for i, param in enumerate(stash.all_fp32_from_fp32_params): stash.all_fp32_from_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_with_master_weights(self, scaler): stash = self._amp_stash self._amp_lazy_init() # This is a lot of python overhead... fp16_grads_needing_unscale = [] new_fp32_grads = [] fp16_grads_needing_unscale_with_stash = [] preexisting_fp32_grads = [] for fp16_param, fp32_param in zip(stash.all_fp16_params, stash.all_fp32_from_fp16_params): if fp16_param.grad is None and fp32_param.grad is not None: continue elif fp16_param.grad is not None and fp32_param.grad is None: fp32_param.grad = torch.empty_like(fp32_param) fp16_grads_needing_unscale.append(fp16_param.grad) new_fp32_grads.append(fp32_param.grad) elif fp16_param.grad is not None and fp32_param.grad is not None: fp16_grads_needing_unscale_with_stash.append(fp16_param.grad) preexisting_fp32_grads.append(fp32_param.grad) else: # fp16_param.grad is None and fp32_param.grad is None: continue if len(fp16_grads_needing_unscale) > 0: scaler.unscale( fp16_grads_needing_unscale, new_fp32_grads, scaler.loss_scale(), models_are_masters=False) if len(fp16_grads_needing_unscale_with_stash) > 0: scaler.unscale_with_stashed( fp16_grads_needing_unscale_with_stash, preexisting_fp32_grads, preexisting_fp32_grads) # fp32 params can be treated as they would be in the "no_master_weights" case. post_backward_models_are_masters( scaler, stash.all_fp32_from_fp32_params, stash.all_fp32_from_fp32_grad_stash) def lazy_init_no_master_weights(self): stash = self._amp_stash stash.all_fp16_params = [] stash.all_fp32_params = [] for i, param_group in enumerate(self.param_groups): for i, param in enumerate(param_group['params']): if param.type() == 'torch.cuda.HalfTensor': stash.all_fp16_params.append(param) elif param.type() == 'torch.cuda.FloatTensor': stash.all_fp32_params.append(param) else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.all_fp16_grad_stash = [None for _ in stash.all_fp16_params] stash.all_fp32_grad_stash = [None for _ in stash.all_fp32_params] def prepare_backward_no_master_weights(self): stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): stash.all_fp16_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None for i, param in enumerate(stash.all_fp32_params): stash.all_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_no_master_weights(self, scaler): stash = self._amp_stash self._amp_lazy_init() split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash), (stash.all_fp32_params, stash.all_fp32_grad_stash)) for params, stashed_grads in split_types: post_backward_models_are_masters(scaler, params, stashed_grads) ##################################################################################### # FusedSGD versions ##################################################################################### # FusedSGD never explicitly materializes the fp32 gradients for "fp32 from fp16" master params # outside the kernel, so we must accumulate directly into the model grads. def prepare_backward_with_master_weights_FusedSGD(self): if self.materialize_master_grads: prepare_backward_with_master_weights(self) else: stash = self._amp_stash self._amp_lazy_init() for i, param in enumerate(stash.all_fp16_params): stash.all_fp16_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None for i, param in enumerate(stash.all_fp32_from_fp32_params): stash.all_fp32_from_fp32_grad_stash[i] = param.grad # Set up to leverage grad copy elision: param.grad = None def post_backward_with_master_weights_FusedSGD(self, scaler): if self.materialize_master_grads: post_backward_with_master_weights(self, scaler) else: stash = self._amp_stash self._amp_lazy_init() grads_have_scale = scaler.loss_scale() stashed_have_scale = self.most_recent_scale out_scale = grads_have_scale if self.scale_set_by_backward: out_scale = min(grads_have_scale, self.most_recent_scale) split_types = ((stash.all_fp16_params, stash.all_fp16_grad_stash), (stash.all_fp32_from_fp32_params, stash.all_fp32_from_fp32_grad_stash)) # unscale_with_stashed() implements grads*1/scale + stashed_grads*1. # stashed_grads are scaled by self.most_recent_scale. for params, stashed_grads in split_types: post_backward_models_are_masters(scaler, params, stashed_grads, (grads_have_scale, stashed_have_scale, out_scale)) self.most_recent_scale = out_scale self.scale_set_by_backward = True def prepare_backward_no_master_weights_FusedSGD(self): prepare_backward_no_master_weights(self) def post_backward_no_master_weights_FusedSGD(self, scaler): post_backward_no_master_weights(self, scaler) def _amp_lazy_init(self): stash = self._amp_stash if not stash.lazy_init_called: self._lazy_init_maybe_master_weights() stash.lazy_init_called = True def _process_optimizer(optimizer, properties): if hasattr(optimizer, "_amp_stash"): raise RuntimeError("A given optimizer should only be passed through amp.initialize once.") else: optimizer._amp_stash = AmpOptimizerState() optimizer._amp_stash.lazy_init_called = False optimizer._amp_stash.already_patched = False optimizer._amp_stash.params_have_scaled_gradients = False for name in ("_lazy_init_maybe_master_weights", "_master_params_to_model_params", "_prepare_amp_backward", "_post_amp_backward", "_amp_lazy_init"): if hasattr(optimizer, name): raise RuntimeError("Incoming optimizer already has {} defined.".format(name)) # TODO: Centralize exposure and import error checking for the C backend. if multi_tensor_applier.available: import amp_C optimizer._amp_stash.multi_tensor_scale = amp_C.multi_tensor_scale optimizer._amp_stash.multi_tensor_l2norm = amp_C.multi_tensor_l2norm optimizer._amp_stash.dummy_overflow_buf = torch.cuda.IntTensor([0]); if properties.master_weights: optimizer._lazy_init_maybe_master_weights = types.MethodType( lazy_init_with_master_weights, optimizer) optimizer._master_params_to_model_params = types.MethodType( _master_params_to_model_params, optimizer) old_step = optimizer.step def new_step(self, closure=None): if closure is not None: raise RuntimeError("Currently, Amp does not support closure use with optimizers.") retval = old_step() if not isinstance(self, FusedSGD): self._master_params_to_model_params() # Clear the master grads that wouldn't be zeroed by model.zero_grad() for param in self._amp_stash.all_fp32_from_fp16_params: param.grad = None return retval optimizer.step = types.MethodType(new_step, optimizer) old_zero_grad = optimizer.zero_grad def new_zero_grad(self): stash = self._amp_stash self._amp_lazy_init() # Zero the model grads. for param in stash.all_fp16_params: if param.grad is not None: param.grad.detach_() param.grad.zero_() for param in stash.all_fp32_from_fp32_params: if param.grad is not None: param.grad.detach_() param.grad.zero_() # Clear the master grads that are independent of model grads for param in self._amp_stash.all_fp32_from_fp16_params: param.grad = None optimizer.zero_grad = types.MethodType(new_zero_grad, optimizer) if isinstance(optimizer, FusedSGD): optimizer._prepare_amp_backward = types.MethodType( prepare_backward_with_master_weights_FusedSGD, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_with_master_weights_FusedSGD, optimizer) else: optimizer._prepare_amp_backward = types.MethodType( prepare_backward_with_master_weights, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_with_master_weights, optimizer) else: optimizer._lazy_init_maybe_master_weights = types.MethodType( lazy_init_no_master_weights, optimizer) if isinstance(optimizer, FusedSGD): optimizer._prepare_amp_backward = types.MethodType( prepare_backward_no_master_weights_FusedSGD, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_no_master_weights_FusedSGD, optimizer) else: optimizer._prepare_amp_backward = types.MethodType( prepare_backward_no_master_weights, optimizer) optimizer._post_amp_backward = types.MethodType( post_backward_no_master_weights, optimizer) optimizer._amp_lazy_init = types.MethodType(_amp_lazy_init, optimizer) old_add_param_group = optimizer.add_param_group def new_add_param_group(self, new_group): stash = self._amp_stash if not stash.lazy_init_called: self._lazy_init_maybe_master_weights() stash.lazy_init_called = True assert isinstance(new_group, dict), "param group must be a dict" new_params = new_group['params'] if isinstance(new_params, torch.Tensor): new_group['params'] = [new_params] elif isinstance(new_params, set): raise TypeError('optimizer parameters need to be organized in ordered collections, but ' 'the ordering of tensors in sets will change between runs. Please use a list instead.') else: new_group['params'] = list(new_params) if properties.master_weights: # Mutate new_group in-place to use FP32 master params fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(new_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True new_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) elif param.type() == 'torch.cuda.FloatTensor': fp32_params_this_group.append(param) new_group['params'][i] = param else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) stash.fp16_groups.append(fp16_params_this_group) stash.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) stash.fp32_from_fp32_groups.append(fp32_params_this_group) stash.all_fp16_params += fp16_params_this_group stash.all_fp32_from_fp16_params += fp32_from_fp16_params_this_group stash.all_fp32_from_fp32_params += fp32_params_this_group # stash.all_fp32_from_fp16_grad_stash = [None for _ in stash.all_fp32_from_fp16_params] stash.all_fp32_from_fp32_grad_stash += [None for _ in fp32_params_this_group] # It should be ok to let params be added with existing .grad attributes. # for param in fp16_params_this_group: # param.grad = None # for param in fp32_from_fp16_params_this_group: # param.grad = None # for param in stash.fp32_params_this_group: # param.grad = None else: for param in new_group['params']: if param.type() == 'torch.cuda.HalfTensor': stash.all_fp16_params.append(param) stash.all_fp16_grad_stash.append(None) elif param.type() == 'torch.cuda.FloatTensor': stash.all_fp32_params.append(param) stash.all_fp32_grad_stash.append(None) else: raise TypeError("Optimizer's parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) old_add_param_group(new_group) optimizer.add_param_group = types.MethodType(new_add_param_group, optimizer) return optimizer ================================================ FILE: KoSimCSE/apex/amp/amp.py ================================================ from . import compat, rnn_compat, utils, wrap from .handle import AmpHandle, NoOpHandle from .lists import functional_overrides, torch_overrides, tensor_overrides from ._amp_state import _amp_state from .frontend import * import functools import itertools import torch _DECORATOR_HANDLE = None _USER_CAST_REGISTRY = set() _USER_PROMOTE_REGISTRY = set() def _decorator_helper(orig_fn, cast_fn, wrap_fn): def wrapper(*args, **kwargs): handle = _DECORATOR_HANDLE if handle is None or not handle.is_active(): return orig_fn(*args, **kwargs) inner_cast_fn = utils.verbosify(cast_fn, orig_fn.__name__, handle.verbose) return wrap_fn(orig_fn, inner_cast_fn, handle)(*args, **kwargs) return wrapper # Decorator form def half_function(fn): wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=True) return _decorator_helper(fn, utils.maybe_half, wrap_fn) def float_function(fn): wrap_fn = functools.partial(wrap.make_cast_wrapper, try_caching=False) return _decorator_helper(fn, utils.maybe_float, wrap_fn) def promote_function(fn): wrap_fn = functools.partial(wrap.make_promote_wrapper) return _decorator_helper(fn, utils.maybe_float, wrap_fn) # Registry form def register_half_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_CAST_REGISTRY.add((module, name, utils.maybe_half)) def register_float_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_CAST_REGISTRY.add((module, name, utils.maybe_float)) def register_promote_function(module, name): if not hasattr(module, name): raise ValueError('No function named {} in module {}.'.format( name, module)) _USER_PROMOTE_REGISTRY.add((module, name)) # Top-level function to insert _all_ the hooks. def init(enabled=True, loss_scale="dynamic", enable_caching=True, verbose=False, allow_banned=False): global _DECORATOR_HANDLE if not enabled: handle = NoOpHandle() _DECORATOR_HANDLE = handle return handle handle = AmpHandle(loss_scale, enable_caching, verbose) # 0) Force-{fp16, fp32} for user-annotated functions for mod, fn, cast_fn in _USER_CAST_REGISTRY: try_caching = (cast_fn == utils.maybe_half) wrap.cached_cast(mod, fn, cast_fn, handle, try_caching, verbose) _USER_CAST_REGISTRY.clear() # 0.5) Force-promote for user-annotated functions for mod, fn in _USER_PROMOTE_REGISTRY: wrap.promote(mod, fn, handle, verbose) _USER_PROMOTE_REGISTRY.clear() # 1) Force-{fp16, fp32} on white- / black-list functions override_modules = [functional_overrides, torch_overrides, tensor_overrides] cast_table = [('FP16_FUNCS', utils.maybe_half), ('FP32_FUNCS', utils.maybe_float)] for module, (list_name, cast_fn) in itertools.product(override_modules, cast_table): for fn in getattr(module, list_name): try_caching = (cast_fn == utils.maybe_half) wrap.cached_cast(module.MODULE, fn, cast_fn, handle, try_caching, verbose) # 1.5) Pre-0.4, put the blacklist methods on HalfTensor and whitelist # methods on FloatTensor, since they're distinct types. if compat.tensor_is_float_tensor(): for fn in tensor_overrides.FP16_FUNCS: wrap.cached_cast(torch.cuda.FloatTensor, fn, utils.maybe_half, handle, try_caching=True, verbose=verbose) for fn in tensor_overrides.FP32_FUNCS: wrap.cached_cast(torch.cuda.HalfTensor, fn, utils.maybe_float, handle, try_caching=False, verbose=verbose) # 2) Enable type-promotion on multi-arg functions and methods. # NB: special handling for sequence fns (e.g. `torch.cat`). promote_modules = [torch_overrides, tensor_overrides] promote_table = [('CASTS', wrap.promote), ('SEQUENCE_CASTS', wrap.sequence_promote)] for promote_mod, (list_name, promote_fn) in itertools.product(promote_modules, promote_table): for fn in getattr(promote_mod, list_name): promote_fn(promote_mod.MODULE, fn, handle, verbose) # 2.5) Pre-0.4, add blacklist methods directly to HalfTensor and FloatTensor types if compat.tensor_is_float_tensor(): for cls, (list_name, promote_fn) in itertools.product([torch.cuda.FloatTensor, torch.cuda.HalfTensor], promote_table): for fn in getattr(tensor_overrides, list_name): promote_fn(cls, fn, handle, verbose) # 3) For any in-place version of a blacklist function, error if any input is fp16. # NB: this is overly conservative. for fn in utils.as_inplace(torch_overrides.FP32_FUNCS): wrap.err_if_any_half(torch_overrides.MODULE, fn, handle) # 3.5) For any in-place blacklist method, error if called on fp16 tensor for fn in utils.as_inplace(tensor_overrides.FP32_FUNCS): wrap.err_if_arg0_half(tensor_overrides.MODULE, fn, handle, verbose) if compat.tensor_is_float_tensor(): wrap.err_if_arg0_half(torch.cuda.HalfTensor, fn, handle, verbose) # 4) For other in-place methods, match the type of self tensor for fn in utils.as_inplace(itertools.chain( tensor_overrides.FP16_FUNCS, tensor_overrides.CASTS)): wrap.promote_match_arg0(tensor_overrides.MODULE, fn, handle, verbose) if compat.tensor_is_float_tensor(): wrap.promote_match_arg0(torch.cuda.HalfTensor, fn, handle, verbose) wrap.promote_match_arg0(torch.cuda.FloatTensor, fn, handle, verbose) # 5) RNNs + RNN cells are whitelisted specially if rnn_compat.has_old_rnns(): wrap.rnn_cast(torch.nn.backends.thnn.backend, 'RNN', handle, verbose) if not rnn_compat.has_old_rnns(): # Patch in our own indirection of `_VF` in modules/rnn s.t. it is mutable. torch.nn.modules.rnn._VF = rnn_compat.VariableFunctionsShim() # Wrap all the rnns for x in rnn_compat.RNN_NAMES: wrap.new_rnn_cast(x.upper(), handle, verbose) # Wrap all the RNN cells rnn_compat.whitelist_rnn_cells(handle, verbose) # 6) Place error+print message on banned functions. # Or, if allow_banned, then cast to FP32. for fn, err_msg in functional_overrides.BANNED_FUNCS: if allow_banned: wrap.cached_cast(functional_overrides.MODULE, fn, utils.maybe_float, handle, try_caching=True, verbose=verbose) else: wrap.err_if_any_half(functional_overrides.MODULE, fn, handle, err_msg) _DECORATOR_HANDLE = handle _amp_state.handle = handle return handle ================================================ FILE: KoSimCSE/apex/amp/compat.py ================================================ import torch # True for post-0.4, when Variables/Tensors merged. def variable_is_tensor(): v = torch.autograd.Variable() return isinstance(v, torch.Tensor) def tensor_is_variable(): x = torch.Tensor() return type(x) == torch.autograd.Variable # False for post-0.4 def tensor_is_float_tensor(): x = torch.Tensor() return type(x) == torch.FloatTensor # Akin to `torch.is_tensor`, but returns True for Variable # objects in pre-0.4. def is_tensor_like(x): return torch.is_tensor(x) or isinstance(x, torch.autograd.Variable) # Wraps `torch.is_floating_point` if present, otherwise checks # the suffix of `x.type()`. def is_floating_point(x): if hasattr(torch, 'is_floating_point'): return torch.is_floating_point(x) try: torch_type = x.type() return torch_type.endswith('FloatTensor') or \ torch_type.endswith('HalfTensor') or \ torch_type.endswith('DoubleTensor') except AttributeError: return False def scalar_python_val(x): if hasattr(x, 'item'): return x.item() else: if isinstance(x, torch.autograd.Variable): return x.data[0] else: return x[0] # Accounts for the possibility that some ops may be removed from a namespace. def filter_attrs(module, attrs): return list(attrname for attrname in attrs if hasattr(module, attrname)) ================================================ FILE: KoSimCSE/apex/amp/frontend.py ================================================ import torch from ._initialize import _initialize from ._amp_state import _amp_state, warn_or_err, maybe_print from collections import OrderedDict class Properties(object): """ This class has two purposes: to establish a set of default properties, and to route setting of these attributes through __setattr__ so that (in theory) they can be checked for consistency with other existing args. """ def __init__(self): self.options = { "enabled" : False, "opt_level" : None, "cast_model_type" : None, "patch_torch_functions" : False, "keep_batchnorm_fp32" : None, "master_weights" : None, "loss_scale" : 1.0, # Reserved for future functionality # "fused_optimizer" : False, # "enable_ddp_interop" : False, } """ This function allows updating several options at a time without routing through __setattr__ checks, to avoid "you can't get there from here" scenarios. Currently not intended to be exposed; users are expected to select an opt_level and apply consistent modifications. """ def _update_options_dict(self, new_options): for k, v in new_options: if k in self.options: self.options[k] = v else: raise ValueError("Tried to set unexpected option {}".format(k)) """ The members of "options" are not direct attributes of self, so access attempts will roll down to __getattr__. This borrows from the logic in torch.nn.Module. """ def __getattr__(self, name): if "options" in self.__dict__: options = self.__dict__["options"] if name in options: return options[name] raise AttributeError("'{}' object has no attribute '{}'".format( type(self).__name__, name)) def __setattr__(self, name, value): if "options" in self.__dict__: if name in self.options: # print("setting {} {}".format(name, value)) if name == "cast_model_type": if self.opt_level == "O1" and value is not None: if value is not False: if value is not torch.float32: warn_or_err("O1 inserts casts around Torch functions rather than " "model weights, so with O1, the model weights themselves " "should remain FP32. If you wish to cast the model to a " "different type, use opt_level='O2' or 'O3'. " + "cast_model_type was {}".format(value)) self.options[name] = value elif name == "patch_torch_functions": if self.opt_level != "O1" and value: warn_or_err("Currently, patch_torch_functions=True should only be set by " "selecting opt_level='O1'.") self.options[name] = value elif name == "keep_batchnorm_fp32": if self.opt_level == "O1" and value is not None: warn_or_err("With opt_level O1, batchnorm functions are automatically patched " "to run in FP32, so keep_batchnorm_fp32 should be None." + " keep_batchnorm_fp32 was {}".format(value)) if value == "False": self.options[name] = False elif value == "True": self.options[name] = True else: assert (value is True or value is False or value is None),\ "keep_batchnorm_fp32 must be a boolean, the string 'True' or 'False', "\ "or None, found keep_batchnorm_fp32={}".format(value) self.options[name] = value elif name == "master_weights": if self.opt_level == "O1" and value is not None: warn_or_err("It doesn't make sense to use master_weights with O1. " "With O1, your model weights themselves should be FP32.") self.options[name] = value elif name == "loss_scale": if value == "dynamic": self.options[name] = value else: self.options[name] = float(value) else: self.options[name] = value else: super(Properties, self).__setattr__(name, value) """ O0-O3 are convenience wrappers to establish defaults for typically used mixed precision options. """ class O3: brief = "O3: Pure FP16 training." more = "Calls .half() on your model, converting the entire model to FP16.\n"\ "A casting operation is also inserted to cast incoming Tensors to FP16,\n"\ "so you don't need to change your data pipeline.\n"\ "This mode is useful for establishing a performance ceiling.\n"\ "It's also possible training may 'just work' in this mode.\n"\ "If not, try other optimization levels." def __call__(self, properties): properties.enabled = True properties.opt_level = "O3" properties.cast_model_type = torch.float16 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = False properties.master_weights = False properties.loss_scale = 1.0 # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O2: brief = "O2: FP16 training with FP32 batchnorm and FP32 master weights.\n" more = "Calls .half() on your model, converting the entire model (except for batchnorms)\n"\ "to FP16. Batchnorms are retained in FP32 for additional stability.\n"\ "The forward pass is patched to cast incoming Tensors to FP16, so you don't need to change\n"\ "your data pipeline.\n"\ "O2 creates FP32 master weights outside the model and patches any optimizers to update\n"\ "these master weights, then copy the master weights into the FP16 model weights.\n"\ "Master weights can also improve convergence and stability." def __call__(self, properties): properties.enabled = True properties.opt_level = "O2" properties.cast_model_type = torch.float16 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = True properties.master_weights = True properties.loss_scale = "dynamic" # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O1: brief = "O1: Insert automatic casts around Pytorch functions and Tensor methods.\n" more = "The type of your model's weights is not altered. However, internally,\n"\ "Pytorch functions are patched to cast any Tensor Core-friendly ops to FP16 for speed,\n"\ "while operations that might benefit from the additional stability of FP32 are patched\n"\ "to cast their inputs to fp32.\n"\ "O1 is the safest way to try mixed precision training, and is recommended when\n"\ "trying mixed precision training for the first time." def __call__(self, properties): properties.enabled = True properties.opt_level = "O1" properties.cast_model_type = None properties.patch_torch_functions = True properties.keep_batchnorm_fp32 = None properties.master_weights = None properties.loss_scale = "dynamic" # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary class O0: brief = "O0: Pure FP32 training.\n" more = "Your models are checked to make sure parameters are FP32, but otherwise the\n"\ "types of weights and internal Pytorch operations are not altered. This mode disables any\n"\ "FP16 arithmetic, although other optimizations like DDP interop may still be requested.\n" def __call__(self, properties): properties.enabled = True properties.opt_level = "O0" properties.cast_model_type = torch.float32 properties.patch_torch_functions = False properties.keep_batchnorm_fp32 = None properties.master_weights = False properties.loss_scale = 1.0 # properties.fused_optimizer = False # properties.enable_ddp_interop = False return properties # modified in place so this isn't really necessary opt_levels = {"O3": O3(), "O2": O2(), "O1": O1(), "O0": O0()} # allow user to directly pass Properties struct as well? def initialize( models, optimizers=None, enabled=True, opt_level="O1", cast_model_type=None, patch_torch_functions=None, keep_batchnorm_fp32=None, master_weights=None, loss_scale=None, cast_model_outputs=None, num_losses=1, verbosity=1, min_loss_scale=None, max_loss_scale=2.**24 ): """ Initialize your models, optimizers, and the Torch tensor and functional namespace according to the chosen ``opt_level`` and overridden properties, if any. ``amp.initialize`` should be called **after** you have finished constructing your model(s) and optimizer(s), but **before** you send your model through any DistributedDataParallel wrapper. See `Distributed training`_ in the Imagenet example. Currently, ``amp.initialize`` should only be called **once**, although it can process an arbitrary number of models and optimizers (see the corresponding `Advanced Amp Usage topic`_). If you think your use case requires ``amp.initialize`` to be called more than once, `let us know`_. Any property keyword argument that is not ``None`` will be interpreted as a manual override. To prevent having to rewrite anything else in your script, name the returned models/optimizers to replace the passed models/optimizers, as in the code sample below. Args: models (torch.nn.Module or list of torch.nn.Modules): Models to modify/cast. optimizers (optional, torch.optim.Optimizer or list of torch.optim.Optimizers): Optimizers to modify/cast. REQUIRED for training, optional for inference. enabled (bool, optional, default=True): If False, renders all Amp calls no-ops, so your script should run as if Amp were not present. opt_level (str, optional, default="O1"): Pure or mixed precision optimization level. Accepted values are "O0", "O1", "O2", and "O3", explained in detail above. cast_model_type (``torch.dtype``, optional, default=None): Optional property override, see above. patch_torch_functions (bool, optional, default=None): Optional property override. keep_batchnorm_fp32 (bool or str, optional, default=None): Optional property override. If passed as a string, must be the string "True" or "False". master_weights (bool, optional, default=None): Optional property override. loss_scale (float or str, optional, default=None): Optional property override. If passed as a string, must be a string representing a number, e.g., "128.0", or the string "dynamic". cast_model_outputs (torch.dtype, optional, default=None): Option to ensure that the outputs of your model(s) are always cast to a particular type regardless of ``opt_level``. num_losses (int, optional, default=1): Option to tell Amp in advance how many losses/backward passes you plan to use. When used in conjunction with the ``loss_id`` argument to ``amp.scale_loss``, enables Amp to use a different loss scale per loss/backward pass, which can improve stability. See "Multiple models/optimizers/losses" under `Advanced Amp Usage`_ for examples. If ``num_losses`` is left to 1, Amp will still support multiple losses/backward passes, but use a single global loss scale for all of them. verbosity (int, default=1): Set to 0 to suppress Amp-related output. min_loss_scale (float, default=None): Sets a floor for the loss scale values that can be chosen by dynamic loss scaling. The default value of None means that no floor is imposed. If dynamic loss scaling is not used, `min_loss_scale` is ignored. max_loss_scale (float, default=2.**24): Sets a ceiling for the loss scale values that can be chosen by dynamic loss scaling. If dynamic loss scaling is not used, `max_loss_scale` is ignored. Returns: Model(s) and optimizer(s) modified according to the ``opt_level``. If either the ``models`` or ``optimizers`` args were lists, the corresponding return value will also be a list. Permissible invocations:: model, optim = amp.initialize(model, optim,...) model, [optim1, optim2] = amp.initialize(model, [optim1, optim2],...) [model1, model2], optim = amp.initialize([model1, model2], optim,...) [model1, model2], [optim1, optim2] = amp.initialize([model1, model2], [optim1, optim2],...) # This is not an exhaustive list of the cross product of options that are possible, # just a set of examples. model, optim = amp.initialize(model, optim, opt_level="O0") model, optim = amp.initialize(model, optim, opt_level="O0", loss_scale="dynamic"|128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O1") # uses "loss_scale="dynamic" default model, optim = amp.initialize(model, optim, opt_level="O1", loss_scale=128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O2") # uses "loss_scale="dynamic" default model, optim = amp.initialize(model, optim, opt_level="O2", loss_scale=128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O2", keep_batchnorm_fp32=True|False|"True"|"False") model, optim = amp.initialize(model, optim, opt_level="O3") # uses loss_scale=1.0 default model, optim = amp.initialize(model, optim, opt_level="O3", loss_scale="dynamic"|128.0|"128.0") model, optim = amp.initialize(model, optim, opt_level="O3", keep_batchnorm_fp32=True|False|"True"|"False") The `Imagenet example`_ demonstrates live use of various opt_levels and overrides. .. _`Distributed training`: https://github.com/NVIDIA/apex/tree/master/examples/imagenet#distributed-training .. _`Imagenet example`: https://github.com/NVIDIA/apex/tree/master/examples/imagenet .. _`Advanced Amp Usage`: https://nvidia.github.io/apex/advanced.html .. _`Advanced Amp Usage topic`: https://nvidia.github.io/apex/advanced.html#multiple-models-optimizers-losses .. _`let us know`: https://github.com/NVIDIA/apex/issues """ _amp_state.opt_properties = Properties() _amp_state.verbosity = verbosity if not enabled: if optimizers is None: return models else: return models, optimizers if not torch.backends.cudnn.enabled: raise RuntimeError( "Amp requires torch.backends.cudnn.enabled = True") if opt_level not in opt_levels: raise RuntimeError( "Unexpected optimization level {}. ".format(opt_level) + "Options are 'O0', 'O1', 'O2', 'O3'. Note that in `O0`, `O1`, etc., the prefix O is the letter O, " + "not the number zero.") else: _amp_state.opt_properties = opt_levels[opt_level](_amp_state.opt_properties) maybe_print("Selected optimization level {}".format(opt_levels[opt_level].brief), True) maybe_print("Defaults for this optimization level are:", True) for k, v in _amp_state.opt_properties.options.items(): maybe_print("{:22} : {}".format(k, v), True) _amp_state.min_loss_scale = min_loss_scale _amp_state.max_loss_scale = max_loss_scale maybe_print("Processing user overrides (additional kwargs that are not None)...", True) # I chose to have the keyword arguments listed directly in the argument list, # instead of **kwargs, so I can't use kwargs.items() here. if enabled is not None: _amp_state.opt_properties.enabled = enabled if opt_level is not None: _amp_state.opt_properties.opt_level = opt_level if cast_model_type is not None: _amp_state.opt_properties.cast_model_type = cast_model_type if patch_torch_functions is not None: _amp_state.opt_properties.patch_torch_functions = patch_torch_functions if keep_batchnorm_fp32 is not None: _amp_state.opt_properties.keep_batchnorm_fp32 = keep_batchnorm_fp32 if master_weights is not None: _amp_state.opt_properties.master_weights = master_weights if loss_scale is not None: _amp_state.opt_properties.loss_scale = loss_scale maybe_print("After processing overrides, optimization options are:", True) for k, v in _amp_state.opt_properties.options.items(): maybe_print("{:22} : {}".format(k, v), True) return _initialize(models, optimizers, _amp_state.opt_properties, num_losses, cast_model_outputs) def state_dict(destination=None): if destination is None: destination = OrderedDict() for idx, loss_scaler in enumerate(_amp_state.loss_scalers): destination['loss_scaler%d' % idx] = { 'loss_scale': loss_scaler.loss_scale(), 'unskipped': loss_scaler._unskipped, } return destination def load_state_dict(state_dict): # Check if state_dict containes the same number of loss_scalers as current setup if len(state_dict) != len(_amp_state.loss_scalers): print('Warning: state_dict contains {} entries, while {} loss_scalers are used'.format( len(state_dict), len(_amp_state.loss_scalers))) state_dict = state_dict.copy() nb_loss_scalers = len(_amp_state.loss_scalers) unexpected_keys = [] # Initialize idx outside, since unexpected_keys will increase it if enumerate is used idx = 0 for key in state_dict: if 'loss_scaler' not in key: unexpected_keys.append(key) else: if idx > (nb_loss_scalers - 1): print('Skipping loss_scaler[{}], since num_losses was set to {}'.format( idx, nb_loss_scalers)) break _amp_state.loss_scalers[idx]._loss_scale = state_dict[key]['loss_scale'] _amp_state.loss_scalers[idx]._unskipped = state_dict[key]['unskipped'] idx += 1 if len(unexpected_keys) > 0: raise RuntimeError( 'Error(s) in loading state_dict. Unexpected key(s) in state_dict: {}. '.format( ', '.join('"{}"'.format(k) for k in unexpected_keys))) # TODO: is this necessary/useful? # def check_option_consistency(enabled=True, # opt_level=None, # cast_model_type=None, # patch_torch_functions=None, # keep_batchnorm_fp32=None, # master_weights=None, # loss_scale=None, # enable_ddp_interop=None, # hard_override=False): # """ # Utility function that enables users to quickly check if the option combination they intend # to use is permitted. ``check_option_consistency`` does not require models or optimizers # to be constructed, and can be called at any point in the script. ``check_option_consistency`` # is totally self-contained; it does not set any amp global state or affect anything outside # of itself. # """ # # if not enabled: # return # # if opt_level not in opt_levels: # raise RuntimeError("Unexpected optimization level. Options are 'O0', 'O1', 'O2', 'O3'.") # else: # opt_properties = opt_levels[opt_level](Properties()) # print("Selected optimization level {}", opt_levels[opt_level].brief) # print("Defaults for this optimization level are:") # for k, v in opt_properties.options: # print("{:22} : {}".format(k, v)) # # print("Processing user overrides (additional kwargs that are not None)...") # for k, v in kwargs: # if k not in _amp_state.opt_properties.options: # raise RuntimeError("Unexpected kwarg {}".format(k)) # if v is not None: # setattr(opt_properties, k, v) # # print("After processing overrides, optimization options are:") # for k, v in opt_properties.options: # print("{:22} : {}".format(k, v)) ================================================ FILE: KoSimCSE/apex/amp/handle.py ================================================ import contextlib import warnings import sys import torch from . import utils from .opt import OptimWrapper from .scaler import LossScaler from ._amp_state import _amp_state, master_params, maybe_print if torch.distributed.is_available(): from ..parallel.LARC import LARC # There's no reason to expose the notion of a "handle". Everything can happen through amp.* calls. @contextlib.contextmanager def scale_loss(loss, optimizers, loss_id=0, model=None, delay_unscale=False, delay_overflow_check=False): """ On context manager entrance, creates ``scaled_loss = (loss.float())*current loss scale``. ``scaled_loss`` is yielded so that the user can call ``scaled_loss.backward()``:: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() On context manager exit (if ``delay_unscale=False``), the gradients are checked for infs/NaNs and unscaled, so that ``optimizer.step()`` can be called. .. note:: If Amp is using explicit FP32 master params (which is the default for ``opt_level=O2``, and can also be manually enabled by supplying ``master_weights=True`` to ``amp.initialize``) any FP16 gradients are copied to FP32 master gradients before being unscaled. ``optimizer.step()`` will then apply the unscaled master gradients to the master params. .. warning:: If Amp is using explicit FP32 master params, only the FP32 master gradients will be unscaled. The direct ``.grad`` attributes of any FP16 model params will remain scaled after context manager exit. This subtlety affects gradient clipping. See "Gradient clipping" under `Advanced Amp Usage`_ for best practices. Args: loss(Tensor): Typically a scalar Tensor. The ``scaled_loss`` that the context manager yields is simply ``loss.float()*loss_scale``, so in principle ``loss`` could have more than one element, as long as you call ``backward()`` on ``scaled_loss`` appropriately within the context manager body. optimizers: All optimizer(s) for which the current backward pass is creating gradients. Must be an optimizer or list of optimizers returned from an earlier call to ``amp.initialize``. For example use with multiple optimizers, see "Multiple models/optimizers/losses" under `Advanced Amp Usage`_. loss_id(int, optional, default=0): When used in conjunction with the ``num_losses`` argument to ``amp.initialize``, enables Amp to use a different loss scale per loss. ``loss_id`` must be an integer between 0 and ``num_losses`` that tells Amp which loss is being used for the current backward pass. See "Multiple models/optimizers/losses" under `Advanced Amp Usage`_ for examples. If ``loss_id`` is left unspecified, Amp will use the default global loss scaler for this backward pass. model(torch.nn.Module, optional, default=None): Currently unused, reserved to enable future optimizations. delay_unscale(bool, optional, default=False): ``delay_unscale`` is never necessary, and the default value of ``False`` is strongly recommended. If ``True``, Amp will not unscale the gradients or perform model->master gradient copies on context manager exit. ``delay_unscale=True`` is a minor ninja performance optimization and can result in weird gotchas (especially with multiple models/optimizers/losses), so only use it if you know what you're doing. "Gradient accumulation across iterations" under `Advanced Amp Usage`_ illustrates a situation where this CAN (but does not need to) be used. .. warning:: If ``delay_unscale`` is ``True`` for a given backward pass, ``optimizer.step()`` cannot be called yet after context manager exit, and must wait for another, later backward context manager invocation with ``delay_unscale`` left to False. .. _`Advanced Amp Usage`: https://nvidia.github.io/apex/advanced.html """ if not hasattr(_amp_state, "opt_properties"): raise RuntimeError("Invoked 'with amp.scale_loss`, but internal Amp state has not been initialized. " "model, optimizer = amp.initialize(model, optimizer, opt_level=...) must be called " "before `with amp.scale_loss`.") if not _amp_state.opt_properties.enabled: yield loss return if isinstance(optimizers, torch.optim.Optimizer) or ('LARC' in globals() and isinstance(optimizers, LARC)): optimizers = [optimizers] loss_scaler = _amp_state.loss_scalers[loss_id] loss_scale = loss_scaler.loss_scale() if ((not _amp_state.opt_properties.master_weights) and (not loss_scaler.dynamic) and loss_scale == 1.0): yield loss.float() # Needing to drop the cache here as well is an ugly gotcha. # But for now I think it's necessary to short-circuit. # Probably ok to skip this if not delay_unscale if _amp_state.opt_properties.patch_torch_functions: _amp_state.handle._clear_cache() return if not delay_unscale: if isinstance(optimizers, list): for optimizer in optimizers: if not optimizer._amp_stash.params_have_scaled_gradients: optimizer._prepare_amp_backward() yield (loss.float())*loss_scale if delay_unscale: for optimizer in optimizers: optimizer._amp_stash.params_have_scaled_gradients = True else: # FusedSGD may take care of unscaling as part of their step() methods. # if not isinstance(optimizers, FP16_Optimizer_for_fused): loss_scaler.clear_overflow_state() for optimizer in optimizers: optimizer._post_amp_backward(loss_scaler) optimizer._amp_stash.params_have_scaled_gradients = False # For future fused optimizers that enable sync-free dynamic loss scaling, # should_skip will always be False. should_skip = False if delay_overflow_check else loss_scaler.update_scale() if should_skip: for optimizer in optimizers: if not optimizer._amp_stash.already_patched: # Close on loss_scaler and loss_id as well, to be safe. Probably not # necessary because amp.scale_loss is already creating a temporary scope. def patch_step(opt, loss_scaler, loss_id): opt_step = opt.step def skip_step(closure=None): if closure is not None: raise RuntimeError("Currently, Amp does not support closure use with optimizers.") maybe_print(("Gradient overflow. Skipping step, loss scaler " + "{} reducing loss scale to {}").format(loss_id, loss_scaler.loss_scale())) # TODO: I don't like the special casing for different optimizer implementations. # Maybe skip should delegate to a method owned by the optimizers themselves. if hasattr(opt._amp_stash, "all_fp32_from_fp16_params"): # Clear the master grads that wouldn't be zeroed by model.zero_grad() for param in opt._amp_stash.all_fp32_from_fp16_params: param.grad = None if hasattr(opt, "most_recent_scale"): opt.most_recent_scale = 1.0 opt.scale_set_by_backward = False opt.step = opt_step opt._amp_stash.already_patched = False return skip_step optimizer.step = patch_step(optimizer, loss_scaler, loss_id) optimizer._amp_stash.already_patched = True # Probably ok to skip this if not delay_unscale if _amp_state.opt_properties.patch_torch_functions: _amp_state.handle._clear_cache() # Free function version of AmpHandle.disable_casts, another step on the # path to removing the concept of "AmpHandle" @contextlib.contextmanager def disable_casts(): _amp_state.handle._is_active = False yield _amp_state.handle._is_active = True class AmpHandle(object): def __init__(self, loss_scale="dynamic", enable_caching=True, verbose=False): self._enable_caching = enable_caching self._verbose = verbose self._cache = dict() self._default_scaler = LossScaler(loss_scale) self._is_active = True self._all_wrappers = [] def is_active(self): return self._is_active @contextlib.contextmanager def _disable_casts(self): self._is_active = False yield self._is_active = True def wrap_optimizer(self, optimizer, num_loss=1): self._default_scaler = None return OptimWrapper(optimizer, self, num_loss) @contextlib.contextmanager def scale_loss(self, loss, optimizer): raise RuntimeError("The old Amp API is no longer supported. Please move to the new API, " "documented here: https://nvidia.github.io/apex/amp.html. Transition guide: " "https://nvidia.github.io/apex/amp.html#transition-guide-for-old-api-users") if not self.is_active(): yield loss return if self._default_scaler is None: raise RuntimeError( 'After calling `handle.wrap_optimizer()`, you must explicitly ' + 'use `optimizer.scale_loss(loss)`.') # TODO: this code block is duplicated here and `opt.py`. Unify. loss_scale = self._default_scaler.loss_scale() yield loss * loss_scale self._default_scaler.clear_overflow_state() self._default_scaler.unscale( master_params(optimizer), master_params(optimizer), loss_scale) should_skip = self._default_scaler.update_scale() if should_skip: optimizer_step = optimizer.step def skip_step(): maybe_print('Gradient overflow, skipping update') optimizer.step = optimizer_step optimizer.step = skip_step self._clear_cache() def _clear_cache(self): self._cache.clear() # Experimental support for saving / restoring uncasted versions of functions def _save_func(self, mod, fn, func): self._all_wrappers.append((mod, fn, func)) def _deactivate(self): for mod, fn, func in self._all_wrappers: utils.set_func(mod, fn, func) self._all_wrappers = [] @property def has_cache(self): return self._enable_caching @property def cache(self): return self._cache def remove_cache(self, param): if self.has_cache and param in self.cache: del self.cache[param] @property def verbose(self): return self._verbose class NoOpHandle(object): def is_active(self): return False @contextlib.contextmanager def _disable_casts(self): yield def wrap_optimizer(self, optimizer, num_loss=1): return OptimWrapper(optimizer, self, num_loss) @contextlib.contextmanager def scale_loss(self, loss, optimizer): yield loss @property def has_cache(self): return False @property def verbose(self): return False def _clear_cache(self): pass def _deactivate(self): pass ================================================ FILE: KoSimCSE/apex/amp/lists/__init__.py ================================================ ================================================ FILE: KoSimCSE/apex/amp/lists/functional_overrides.py ================================================ # TODO: think about the following two. They do weird things. # - torch.nn.utils.clip_grad (but it should always be fp32 anyway) # - torch.nn.utils.weight_norm # Notes: # F.instance_norm uses batch_norm internally. Which correctly handles # fp16 in/out with fp32 weights. So we shouldn't do anything for # either of these. # F.normalize calls `input.norm()` internally, so it's redundant, but # kept here in case impl. changes. # F.cosine_similarity is same: calls `x.norm()` internally. import torch.nn.functional MODULE = torch.nn.functional FP16_FUNCS = [ 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d', 'conv_tbc', # Undocumented / maybe new? 'linear', ] FP32_FUNCS = [ # Interpolation/Upsampling TODO: Remove for 1.2 'interpolate', 'grid_sample', # Pointwise 'softplus', 'softmin', 'log_softmax', 'softmax', 'gelu', # Normalization 'layer_norm', 'group_norm', 'local_response_norm', 'normalize', 'cosine_similarity', # Loss functions # TODO: which of these can be fp16? 'poisson_nll_loss', 'cosine_embedding_loss', 'cross_entropy', 'hinge_embedding_loss', 'kl_div', 'l1_loss', 'mse_loss', 'margin_ranking_loss', 'multilabel_margin_loss', 'multilabel_soft_margin_loss', 'multi_margin_loss', 'nll_loss', 'binary_cross_entropy_with_logits', 'smooth_l1_loss', 'soft_margin_loss', 'triplet_margin_loss', 'ctc_loss' ] BANNED_FUNCS = [ ('binary_cross_entropy', ("\namp does not work out-of-the-box with `F.binary_cross_entropy` or `torch.nn.BCELoss.` " "It requires that the output of the previous function be already a FloatTensor. \n\n" "Most models have a Sigmoid right before BCELoss. In that case, you can use\n" " torch.nn.BCEWithLogitsLoss\nto combine Sigmoid+BCELoss into a single layer " "that is compatible with amp.\nAnother option is to add\n" " amp.register_float_function(torch, 'sigmoid')\nbefore calling `amp.init()`.\n" "If you _really_ know what you are doing, you can disable this warning by passing " "allow_banned=True to `amp.init()`.")) ] ================================================ FILE: KoSimCSE/apex/amp/lists/tensor_overrides.py ================================================ from .. import compat from . import torch_overrides import importlib import torch # if compat.variable_is_tensor() and not compat.tensor_is_variable(): MODULE = torch.Tensor # else: # MODULE = torch.autograd.Variable FP16_FUNCS = compat.filter_attrs(MODULE, [ '__matmul__', ]) FP32_FUNCS = compat.filter_attrs(MODULE, [ '__ipow__', '__pow__', '__rpow__', # Cast to fp32 before transfer to CPU 'cpu', ]) CASTS = compat.filter_attrs(MODULE, [ '__add__', '__div__', '__eq__', '__ge__', '__gt__', '__iadd__', '__idiv__', '__imul__', '__isub__', '__itruediv__', '__le__', '__lt__', '__mul__', '__ne__', '__radd__', '__rdiv__', '__rmul__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__', ]) # None of these, but here to make code cleaner. SEQUENCE_CASTS = [] # We need to grab all the methods from torch_overrides and add them to # the Tensor lists as well, as almost all methods are duplicated # between `torch` and `torch.Tensor` (and check with `hasattr`, # because a few random ones aren't defined on Tensor) _self_mod = importlib.import_module(__name__) for attrname in ['FP16_FUNCS', 'FP32_FUNCS', 'CASTS', 'SEQUENCE_CASTS']: lst = getattr(_self_mod, attrname) for fn in getattr(torch_overrides, attrname): if hasattr(MODULE, fn): lst.append(fn) ================================================ FILE: KoSimCSE/apex/amp/lists/torch_overrides.py ================================================ import torch from .. import utils MODULE = torch FP16_FUNCS = [ # Low level functions wrapped by torch.nn layers. # The wrapper layers contain the weights which are then passed in as a parameter # to these functions. 'conv1d', 'conv2d', 'conv3d', 'conv_transpose1d', 'conv_transpose2d', 'conv_transpose3d', 'conv_tbc', 'prelu', # BLAS 'addmm', 'addmv', 'addr', 'matmul', 'mm', 'mv', ] FP32_FUNCS = [ # Pointwise 'acos', 'asin', 'cosh', 'erfinv', 'exp', 'expm1', 'log', 'log10', 'log2', 'reciprocal', 'rsqrt', 'sinh', 'tan', # Other math 'pow', # Reduction 'cumprod', 'cumsum', 'dist', # 'mean', 'norm', 'prod', 'std', 'sum', 'var', # Misc 'renorm' ] version_strings = torch.__version__.split('.') version_major = version_strings[0] version_minor = version_strings[1] version_num = float(version_major + "." + version_minor) # Before torch 1.1, mean must be blacklisted. if version_num < 1.1: FP32_FUNCS.append('mean') # Before CUDA 9.1, batched matmul was missing fast FP16 kernels. We # check the CUDA version -- if at least 9.1, then put the bmm # functions on the fp16 list. Otherwise, put them on the fp32 list. _bmms = ['addbmm', 'baddbmm', 'bmm'] if utils.is_cuda_enabled(): # workaround https://github.com/facebookresearch/maskrcnn-benchmark/issues/802 if utils.get_cuda_version() >= (9, 1, 0): FP16_FUNCS.extend(_bmms) else: FP32_FUNCS.extend(_bmms) # Multi-tensor fns that may need type promotion CASTS = [ # Multi-tensor math 'addcdiv', 'addcmul', 'atan2', 'cross', 'bilinear', 'dot', # Element-wise _or_ tensor-wise math 'add', 'div', 'mul', # Comparison 'eq', 'equal', 'ge', 'gt', 'le', 'lt', 'ne' ] # Functions that take sequence arguments. We need to inspect the whole # sequence and cast to the widest type. SEQUENCE_CASTS = [ 'cat', 'stack' ] ================================================ FILE: KoSimCSE/apex/amp/opt.py ================================================ import contextlib import warnings from .scaler import LossScaler, master_params from ._amp_state import maybe_print import numpy as np class OptimWrapper(object): def __init__(self, optimizer, amp_handle, num_loss): self._optimizer = optimizer self._amp_handle = amp_handle self._num_loss = num_loss self._loss_idx = 0 self._skip_next = [False] * num_loss self._loss_scaler = [LossScaler('dynamic') for _ in range(num_loss)] @contextlib.contextmanager def scale_loss(self, loss): if not self._amp_handle.is_active(): yield loss return # When there are multiple losses per-optimizer, we need # to save out current grad accumulation, since we won't be # able to unscale this particulare loss once the grads are # all mixed together. cached_grads = [] if self._loss_idx > 0: for p in master_params(self._optimizer): if p.grad is not None: cached_grads.append(p.grad.data.detach().clone()) else: cached_grads.append(None) self._optimizer.zero_grad() loss_scale = self._cur_loss_scaler().loss_scale() yield loss * loss_scale self._cur_loss_scaler().clear_overflow_state() self._cur_loss_scaler().unscale( master_params(self._optimizer), master_params(self._optimizer), loss_scale) self._skip_next[self._loss_idx] = self._cur_loss_scaler().update_scale() self._loss_idx += 1 if len(cached_grads) > 0: for p, cached_grad in zip(master_params(self._optimizer), cached_grads): if cached_grad is not None: p.grad.data.add_(cached_grad) cached_grads = [] def _cur_loss_scaler(self): assert 0 <= self._loss_idx < self._num_loss return self._loss_scaler[self._loss_idx] def step(self, closure=None): if not self._amp_handle.is_active(): return self._optimizer.step(closure=closure) self._loss_idx = 0 for group in self._optimizer.param_groups: for p in group['params']: self._amp_handle.remove_cache(p) if closure is not None: raise NotImplementedError( 'The `closure` argument is unsupported by the amp ' + 'optimizer wrapper.') if any(self._skip_next): maybe_print('Gradient overflow, skipping update') self._skip_next = [False] * self._num_loss else: return self._optimizer.step(closure=closure) # Forward any attribute lookups def __getattr__(self, attr): return getattr(self._optimizer, attr) # Forward all torch.optim.Optimizer methods def __getstate__(self): return self._optimizer.__getstate__() def __setstate__(self): return self._optimizer.__setstate__() def __repr__(self): return self._optimizer.__repr__() def state_dict(self): return self._optimizer.state_dict() def load_state_dict(self, state_dict): return self._optimizer.load_state_dict(state_dict) def zero_grad(self): return self._optimizer.zero_grad() def add_param_group(self, param_group): return self._optimizer.add_param_group(param_group) ================================================ FILE: KoSimCSE/apex/amp/rnn_compat.py ================================================ from . import utils, wrap import torch _VF = torch._C._VariableFunctions RNN_NAMES = ['rnn_relu', 'rnn_tanh', 'gru', 'lstm'] def _gen_VF_wrapper(name): def wrapper(*args, **kwargs): return getattr(_VF, name)(*args, **kwargs) return wrapper # Some python magic to generate an object that has the rnn cell functions # defined on it, all of which call into corresponding _VF version. # Intended to patch torch.nn.modules.rnn._VF (aka, the ref named "_VF" # imported at module scope within torch.nn.modules.rnn). This should # not affect third-party importers of _VF.py. class VariableFunctionsShim(object): def __init__(self): for name in RNN_NAMES: for suffix in ['', '_cell']: fn_name = name + suffix setattr(self, fn_name, _gen_VF_wrapper(fn_name)) def has_old_rnns(): try: torch.nn.backends.thnn.backend.LSTMCell return True except: return False def whitelist_rnn_cells(handle, verbose): # Different module + function names in old/new RNN cases if has_old_rnns(): fn_names = ['RNNReLUCell', 'RNNTanhCell', 'LSTMCell', 'GRUCell'] mod = torch.nn.backends.thnn.backend else: fn_names = [x + '_cell' for x in RNN_NAMES] mod = torch.nn.modules.rnn._VF assert isinstance(mod, VariableFunctionsShim) # Insert casts on cell functions for fn in fn_names: wrap.cached_cast(mod, fn, utils.maybe_half, handle, try_caching=True, verbose=verbose) if has_old_rnns(): # Special handling of `backward` for fused gru / lstm: # The `backward` method calls Tensor.sum() (blacklist) internally, # and then the resulting grad_input has the wrong type. # TODO: where else is this a problem? for rnn_type in ['GRUFused', 'LSTMFused']: mod = getattr(torch.nn._functions.thnn.rnnFusedPointwise, rnn_type) wrap.disable_casts(mod, 'backward', handle) ================================================ FILE: KoSimCSE/apex/amp/scaler.py ================================================ import torch from ..multi_tensor_apply import multi_tensor_applier from ._amp_state import _amp_state, master_params, maybe_print from itertools import product def scale_check_overflow_python(model_grad, master_grad, scale, check_overflow=False): # Exception handling for 18.04 compatibility if check_overflow: cpu_sum = float(model_grad.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True if master_grad is not model_grad: # copy_ probably internally short-circuits this master_grad.copy_(model_grad) if scale != 1.0: master_grad.mul_(scale) return False def axpby_check_overflow_python(model_grad, stashed_grad, master_grad, a, b, check_overflow=False): # Exception handling for 18.04 compatibility if check_overflow: cpu_sum = float(model_grad.float().sum()) if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True # if master_grad is not model_grad: # copy_ probably internally short-circuits this # master_grad.copy_(model_grad) assert stashed_grad.dtype == master_grad.dtype converted_model_grad = model_grad.data.to(master_grad.dtype) master_grad.data = a*converted_model_grad.data + b*stashed_grad.data return False class LossScaler(object): warned_no_fused_kernel = False warned_unscaling_non_fp32_grad = False has_fused_kernel = False def __init__(self, loss_scale, init_scale=2.**16, scale_factor=2., scale_window=2000, min_loss_scale=None, max_loss_scale=2.**24): if loss_scale == "dynamic": self.dynamic = True self._loss_scale = min(max_loss_scale, init_scale) else: self.dynamic = False self._loss_scale = loss_scale self._max_loss_scale = max_loss_scale self._min_loss_scale = min_loss_scale self._scale_seq_len = scale_window self._unskipped = 0 self._has_overflow = False self._overflow_buf = torch.cuda.IntTensor([0]) if multi_tensor_applier.available: import amp_C LossScaler.has_fused_kernel = multi_tensor_applier.available LossScaler.multi_tensor_scale_cuda = amp_C.multi_tensor_scale LossScaler.multi_tensor_axpby_cuda = amp_C.multi_tensor_axpby else: if not LossScaler.warned_no_fused_kernel: maybe_print( "Warning: multi_tensor_applier fused unscale kernel is unavailable, " "possibly because apex was installed without --cuda_ext --cpp_ext. " "Using Python fallback. Original ImportError was: " + repr(multi_tensor_applier.import_err), True) LossScaler.has_fused_kernel = False LossScaler.warned_no_fused_kernel = True def loss_scale(self): return self._loss_scale def unscale_python(self, model_grads, master_grads, scale): for model, master in zip(model_grads, master_grads): if model is not None: if not LossScaler.warned_unscaling_non_fp32_grad: if master.dtype != torch.float32: maybe_print( "Attempting to unscale a grad with type {} ".format(master.type()) + "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") LossScaler.warned_unscaling_non_fp32_grad = True self._has_overflow = scale_check_overflow_python(model, master, 1./scale, self.dynamic) if self._has_overflow and self.dynamic: break # unused_scale keeps some of the old API alive for hopefully a short time. def unscale(self, model_grads, master_grads, unused_scale, models_are_masters=False, scale_override=None): if self._has_overflow: return scale = self._loss_scale if scale_override is not None: scale = scale_override if scale == 1.0 and models_are_masters and not self.dynamic: return if LossScaler.has_fused_kernel: # if (not LossScaler.warned_unscaling_non_fp32_grad # and master_grads[0].dtype == torch.float16): # print("Warning: unscaling grads that are not FP32. " # "Unscaling non-fp32 grads may indicate an error. " # "When using Amp, you don't need to call .half() on your model.") # # Setting this to True unconditionally allows the possibility of an escape # # if never-before-seen non-fp32 grads are created in some later iteration. # LossScaler.warned_unscaling_non_fp32_grad = True multi_tensor_applier(LossScaler.multi_tensor_scale_cuda, self._overflow_buf, [model_grads, master_grads], 1./scale) else: self.unscale_python(model_grads, master_grads, scale) # Defer to update_scale # If the fused kernel is available, we only need one D2H memcopy and sync. # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: # self._has_overflow = self._overflow_buf.item() def unscale_with_stashed_python(self, model_grads, stashed_master_grads, master_grads, a, b): for model, stashed, master in zip(model_grads, stashed_master_grads, master_grads): if model is None and stashed is None: continue else: if not LossScaler.warned_unscaling_non_fp32_grad: if master.dtype != torch.float32: maybe_print( "Attempting to unscale a grad with type {} ".format(master.type()) + "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") LossScaler.warned_unscaling_non_fp32_grad = True self._has_overflow = axpby_check_overflow_python(model, stashed, master, a, b, self.dynamic) if self._has_overflow and self.dynamic: break def unscale_with_stashed(self, model_grads, stashed_master_grads, master_grads, scale_override=None): if self._has_overflow: return grads_have_scale, stashed_have_scale, out_scale = self._loss_scale, 1.0, 1.0 if scale_override is not None: grads_have_scale, stashed_have_scale, out_scale = scale_override if LossScaler.has_fused_kernel: if (not LossScaler.warned_unscaling_non_fp32_grad and master_grads[0].dtype == torch.float16): print("Warning: unscaling grads that are not FP32. " "Unscaling non-fp32 grads may indicate an error. " "When using Amp, you don't need to call .half() on your model.") # Setting this to True unconditionally allows the possibility of an escape # if never-before-seen non-fp32 grads are created in some later iteration. LossScaler.warned_unscaling_non_fp32_grad = True multi_tensor_applier(LossScaler.multi_tensor_axpby_cuda, self._overflow_buf, [model_grads, stashed_master_grads, master_grads], out_scale/grads_have_scale, # 1./scale, out_scale/stashed_have_scale, # 1.0, 0) # check only arg 0, aka the incoming model grads, for infs else: self.unscale_with_stashed_python(model_grads, stashed_master_grads, master_grads, out_scale/grads_have_scale, out_scale/stashed_have_scale) # Defer to update_scale # If the fused kernel is available, we only need one D2H memcopy and sync. # if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: # self._has_overflow = self._overflow_buf.item() def clear_overflow_state(self): self._has_overflow = False if self.has_fused_kernel: self._overflow_buf.zero_() # Separate so unscale() can be called more that once before updating. def update_scale(self): # If the fused kernel is available, we only need one D2H memcopy and sync. if LossScaler.has_fused_kernel and self.dynamic and not self._has_overflow: self._has_overflow = self._overflow_buf.item() if self._has_overflow and self.dynamic: should_skip = True if(self._min_loss_scale): self._loss_scale = max(self._min_loss_scale, self._loss_scale/2.) else: self._loss_scale = self._loss_scale/2. self._unskipped = 0 else: should_skip = False self._unskipped += 1 if self._unskipped == self._scale_seq_len and self.dynamic: self._loss_scale = min(self._max_loss_scale, self._loss_scale*2.) self._unskipped = 0 return should_skip ================================================ FILE: KoSimCSE/apex/amp/utils.py ================================================ from . import compat import functools import itertools import torch def is_cuda_enabled(): return torch.version.cuda is not None def get_cuda_version(): return tuple(int(x) for x in torch.version.cuda.split('.')) def is_fp_tensor(x): if is_nested(x): # Fast-fail version of all(is_fp_tensor) for y in x: if not is_fp_tensor(y): return False return True return compat.is_tensor_like(x) and compat.is_floating_point(x) def is_nested(x): return isinstance(x, tuple) or isinstance(x, list) def should_cache(x): if is_nested(x): # Fast-fail version of all(should_cache) for y in x: if not should_cache(y): return False return True return isinstance(x, torch.nn.parameter.Parameter) and \ type_string(x) == 'FloatTensor' def collect_fp_tensor_types(args, kwargs): def collect_types(x, types): if is_nested(x): for y in x: collect_types(y, types) else: types.add(type_string(x)) all_args = itertools.chain(args, kwargs.values()) types = set() for x in all_args: if is_fp_tensor(x): collect_types(x, types) return types def type_string(x): return x.type().split('.')[-1] def maybe_half(x, name='', verbose=False): if is_nested(x): return type(x)([maybe_half(y) for y in x]) if not x.is_cuda or type_string(x) == 'HalfTensor': return x else: if verbose: print('Float->Half ({})'.format(name)) return x.half() def maybe_float(x, name='', verbose=False): if is_nested(x): return type(x)([maybe_float(y) for y in x]) if not x.is_cuda or type_string(x) == 'FloatTensor': return x else: if verbose: print('Half->Float ({})'.format(name)) return x.float() # NB: returneds casted `args`, mutates `kwargs` in-place def casted_args(cast_fn, args, kwargs): new_args = [] for x in args: if is_fp_tensor(x): new_args.append(cast_fn(x)) else: new_args.append(x) for k in kwargs: val = kwargs[k] if is_fp_tensor(val): kwargs[k] = cast_fn(val) return new_args def cached_cast(cast_fn, x, cache): if is_nested(x): return type(x)([cached_cast(y) for y in x]) if x in cache: cached_x = cache[x] if x.requires_grad and cached_x.requires_grad: # Make sure x is actually cached_x's autograd parent. if cached_x.grad_fn.next_functions[1][0].variable is not x: raise RuntimeError("x and cache[x] both require grad, but x is not " "cache[x]'s parent. This is likely an error.") # During eval, it's possible to end up caching casted weights with # requires_grad=False. On the next training iter, if cached_x is found # and reused from the cache, it will not actually have x as its parent. # Therefore, we choose to invalidate the cache (and force refreshing the cast) # if x.requires_grad and cached_x.requires_grad do not match. # # During eval (i.e. running under with torch.no_grad()) the invalidation # check would cause the cached value to be dropped every time, because # cached_x would always be created with requires_grad=False, while x would # still have requires_grad=True. This would render the cache effectively # useless during eval. Therefore, if we are running under the no_grad() # context manager (torch.is_grad_enabled=False) we elide the invalidation # check, and use the cached value even though its requires_grad flag doesn't # match. During eval, we don't care that there's no autograd-graph # connection between x and cached_x. if torch.is_grad_enabled() and x.requires_grad != cached_x.requires_grad: del cache[x] else: return cached_x casted_x = cast_fn(x) cache[x] = casted_x return casted_x def verbosify(cast_fn, fn_name, verbose): if verbose: return functools.partial(cast_fn, name=fn_name, verbose=verbose) else: return cast_fn def as_inplace(fns): for x in fns: yield x + '_' def has_func(mod, fn): if isinstance(mod, dict): return fn in mod else: return hasattr(mod, fn) def get_func(mod, fn): if isinstance(mod, dict): return mod[fn] else: return getattr(mod, fn) def set_func(mod, fn, new_fn): if isinstance(mod, dict): mod[fn] = new_fn else: setattr(mod, fn, new_fn) def set_func_save(handle, mod, fn, new_fn): cur_fn = get_func(mod, fn) handle._save_func(mod, fn, cur_fn) set_func(mod, fn, new_fn) # A couple problems get solved here: # - The flat_weight buffer is disconnected from autograd graph, # so the fp16 weights need to be derived from the input weights # to this forward call, not the flat buffer. # - The ordering of weights in the flat buffer is...idiosyncratic. # First problem is solved with combination of set_ (to set up # correct storage) and copy_ (so the fp16 weight derives from the # fp32 one in autograd. # Second is solved by doing ptr arithmetic on the fp32 weights # to derive the correct offset. # # TODO: maybe this should actually use # `torch._cudnn_rnn_flatten_weight`? But then I need to call # on first iter and cache the right offsets. Ugh. def synthesize_flattened_rnn_weights(fp32_weights, fp16_flat_tensor, rnn_fn='', verbose=False): fp16_weights = [] fp32_base_ptr = fp32_weights[0][0].data_ptr() for layer_weights in fp32_weights: fp16_layer_weights = [] for w_fp32 in layer_weights: w_fp16 = w_fp32.new().half() offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size() w_fp16.set_(fp16_flat_tensor.storage(), offset, w_fp32.shape) w_fp16.copy_(w_fp32) if verbose: print('Float->Half ({})'.format(rnn_fn)) fp16_layer_weights.append(w_fp16) fp16_weights.append(fp16_layer_weights) return fp16_weights # Roughly same as above, just the `fp32_weights` aren't nested. # Code kept separate for readability. def new_synthesize_flattened_rnn_weights(fp32_weights, fp16_flat_tensor, rnn_fn='', verbose=False): fp16_weights = [] fp32_base_ptr = fp32_weights[0].data_ptr() for w_fp32 in fp32_weights: w_fp16 = w_fp32.new().half() offset = (w_fp32.data_ptr() - fp32_base_ptr) // w_fp32.element_size() w_fp16.set_(fp16_flat_tensor.storage(), offset, w_fp32.shape) w_fp16.copy_(w_fp32) if verbose: print('Float->Half ({})'.format(rnn_fn)) fp16_weights.append(w_fp16) return fp16_weights ================================================ FILE: KoSimCSE/apex/amp/wrap.py ================================================ from . import compat from . import utils from ._amp_state import _amp_state from . import rnn_compat import functools import torch def make_cast_wrapper(orig_fn, cast_fn, handle, try_caching=False): @functools.wraps(orig_fn) def wrapper(*args, **kwargs): if not handle.is_active(): return orig_fn(*args, **kwargs) if try_caching and handle.has_cache: args = list(args) for i in range(len(args)): if utils.should_cache(args[i]): args[i] = utils.cached_cast(cast_fn, args[i], handle.cache) for k in kwargs: if utils.should_cache(kwargs[k]): kwargs[k] = utils.cached_cast(cast_fn, kwargs[k], handle.cache) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(*new_args, **kwargs) return wrapper def cached_cast(mod, fn, cast_fn, handle, try_caching=False, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) cast_fn = utils.verbosify(cast_fn, fn, verbose) wrapper = make_cast_wrapper(orig_fn, cast_fn, handle, try_caching) utils.set_func_save(handle, mod, fn, wrapper) # `handle` arg is unused, but simplifies API to make `make_cast_wrapper` # Annoyingly, make_promote_wrapper still uses the global handle. Once everyone # is on the new API and I am free to get rid of handle, I can clean this up. def make_promote_wrapper(orig_fn, cast_fn, handle=None): @functools.wraps(orig_fn) def wrapper(*args, **kwargs): if not _amp_state.handle.is_active(): return orig_fn(*args, **kwargs) types = utils.collect_fp_tensor_types(args, kwargs) if len(types) <= 1: return orig_fn(*args, **kwargs) elif len(types) == 2 and types == set(['HalfTensor', 'FloatTensor']): new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(*new_args, **kwargs) else: raise NotImplementedError('Do not know how to handle ' + 'these types to promote: {}' .format(types)) return wrapper def promote(mod, fn, handle, verbose=False): orig_fn = utils.get_func(mod, fn) maybe_float = utils.verbosify(utils.maybe_float, fn, verbose) wrapper = make_promote_wrapper(orig_fn, maybe_float) utils.set_func_save(handle, mod, fn, wrapper) def sequence_promote(mod, fn, handle, verbose=False): orig_fn = utils.get_func(mod, fn) maybe_float = utils.verbosify(utils.maybe_float, fn, verbose) @functools.wraps(orig_fn) def wrapper(seq, *args, **kwargs): if not _amp_state.handle.is_active(): return orig_fn(seq, *args, **kwargs) types = set([utils.type_string(x) for x in seq]) if len(types) <= 1: return orig_fn(seq, *args, **kwargs) elif types == set(['HalfTensor', 'FloatTensor']): cast_seq = utils.casted_args(maybe_float, seq, {}) return orig_fn(cast_seq, *args, **kwargs) else: # TODO: other mixed-type cases aren't due to amp. # Just pass through? return orig_fn(seq, *args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def promote_match_arg0(mod, fn, handle, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(arg0, *args, **kwargs): assert compat.is_tensor_like(arg0) if not _amp_state.handle.is_active(): return orig_fn(arg0, *args, **kwargs) if utils.type_string(arg0) == 'HalfTensor': cast_fn = utils.maybe_half elif utils.type_string(arg0) == 'FloatTensor': cast_fn = utils.maybe_float else: return orig_fn(arg0, *args, **kwargs) cast_fn = utils.verbosify(cast_fn, fn, verbose) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(arg0, *new_args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def err_if_any_half(mod, fn, handle, custom_err_msg=None): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): types = utils.collect_fp_tensor_types(args, kwargs) if 'HalfTensor' in types: if custom_err_msg: raise NotImplementedError(custom_err_msg) else: raise NotImplementedError('Cannot call in-place function ' + '{} with fp16 arguments.'.format(fn)) else: return orig_fn(*args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) def err_if_arg0_half(mod, fn, handle, verbose=False): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(arg0, *args, **kwargs): assert compat.is_tensor_like(arg0) if utils.type_string(arg0) == 'HalfTensor': raise NotImplementedError('Cannot call in-place method ' + '{} on fp16 Tensors.'.format(fn)) else: cast_fn = utils.verbosify(utils.maybe_float, fn, verbose) new_args = utils.casted_args(cast_fn, args, kwargs) return orig_fn(arg0, *new_args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) # Current RNN approach: # - Wrap top-level `RNN` function in thnn backend # - Will call into either CudnnRNN or AutogradRNN # - Each of these are factory functions that return a per-iter # `forward` function # - We interpose on the factory function to: # 1) Interpose on the actual forward function and put in casts # 2) Insert an fp16 `flat_weight` if necessary def rnn_cast(backend, fn, handle, verbose=False): orig_rnn = utils.get_func(backend, fn) @functools.wraps(orig_rnn) def rnn_wrapper(*args, **kwargs): flat_weight = kwargs.get('flat_weight') if flat_weight is not None: # We replace `flat_weight` with an uninitialized fp16 # Tensor. The "actual" weight tensors (provided in `forward`), # will then be set up as ptrs into the buffer and have the # corresponding fp32 values copied in. # We need to call `copy` on the "actual" weights so that the # autograd graph correctly backprops from the wgrads computed # inside cuDNN (on fp16 weights) into the fp32 weights. assert utils.type_string(flat_weight) == 'FloatTensor' if compat.tensor_is_float_tensor() or compat.tensor_is_variable(): # Pre-0.4. A little slower, since it zeros out memory. flat_weight_fp16 = flat_weight.new().half().resize_(flat_weight.shape) else: flat_weight_fp16 = torch.empty_like(flat_weight, dtype=torch.float16) kwargs['flat_weight'] = flat_weight_fp16 else: flat_weight_fp16 = None forward = orig_rnn(*args, **kwargs) @functools.wraps(forward) def fwd_wrapper(*fargs, **fkwargs): assert len(fargs) == 3 or len(fargs) == 4 inputs, weights, hiddens = fargs[:3] assert utils.is_fp_tensor(inputs) assert isinstance(weights, list) cast_fn = utils.verbosify(utils.maybe_half, fn, verbose) new_args = [] # 0) Inputs new_args.append(cast_fn(inputs)) # 1) Weights if flat_weight_fp16 is not None: fp16_weights = utils.synthesize_flattened_rnn_weights( weights, flat_weight_fp16, fn, verbose) else: fp16_weights = [[cast_fn(w) for w in layer] for layer in weights] new_args.append(fp16_weights) # 2) Inputs: either a tuple (for LSTM) or single tensor if isinstance(hiddens, tuple): new_args.append(tuple(cast_fn(x) for x in hiddens)) elif utils.is_fp_tensor(hiddens): new_args.append(cast_fn(hiddens)) else: # Hiddens can, in principle, be `None` -- pass through new_args.append(hiddens) # 3) Batch sizes (0.4 or later only) if len(fargs) == 4: new_args.append(fargs[3]) return forward(*new_args, **fkwargs) return fwd_wrapper utils.set_func_save(handle, backend, fn, rnn_wrapper) def new_rnn_cast(fn, handle, verbose=False): # Forward+backward compatibility around https://github.com/pytorch/pytorch/pull/15744 # For rnn backend calls that route through _rnn_impls, we must patch the ref # that _rnn_impls stashed. For rnn backend calls that directly invoke # _VF., e.g. _VF.lstm, we can patch onto VariableFunctionsShim, # which in turn has patched the ref named "_VF" in torch.nn.modules.rnn. if utils.has_func(torch.nn.modules.rnn._rnn_impls, fn): mod = torch.nn.modules.rnn._rnn_impls else: mod = torch.nn.modules.rnn._VF assert isinstance(mod, rnn_compat.VariableFunctionsShim) fn = fn.lower() orig_fn = utils.get_func(mod, fn) cast_fn = utils.verbosify(utils.maybe_half, fn, verbose) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): # Exact call signature from modules/rnn.py assert len(args) == 9 assert len(kwargs) == 0 if not _amp_state.handle.is_active(): return orig_fn(*args, **kwargs) if isinstance(args[6], bool): params_idx = 2 # Not PackedSequence case else: params_idx = 3 # PackedSequence case new_args = [] for i, arg in enumerate(args): if i == params_idx: num_params = sum([x.numel() for x in arg]) fp16_weight_buf = args[0].new_empty((num_params,), dtype=torch.half) casted_weights = utils.new_synthesize_flattened_rnn_weights( arg, fp16_weight_buf, fn, verbose) new_args.append(casted_weights) elif utils.is_fp_tensor(arg): new_args.append(cast_fn(arg)) else: new_args.append(arg) return orig_fn(*new_args) utils.set_func_save(handle, mod, fn, wrapper) def disable_casts(mod, fn, handle): if not utils.has_func(mod, fn): return orig_fn = utils.get_func(mod, fn) @functools.wraps(orig_fn) def wrapper(*args, **kwargs): with handle._disable_casts(): return orig_fn(*args, **kwargs) utils.set_func_save(handle, mod, fn, wrapper) ================================================ FILE: KoSimCSE/apex/contrib/__init__.py ================================================ ================================================ FILE: KoSimCSE/apex/contrib/bottleneck/__init__.py ================================================ from .bottleneck import Bottleneck ================================================ FILE: KoSimCSE/apex/contrib/bottleneck/bottleneck.py ================================================ import torch from torch import nn import fast_bottleneck def kaiming_uniform_(tensor, a=0, mode='fan_in', nonlinearity='leaky_relu'): weight_tensor_nchw = tensor nn.init.kaiming_uniform_(weight_tensor_nchw, a=a, mode=mode, nonlinearity=nonlinearity) class FrozenBatchNorm2d(torch.nn.Module): """ BatchNorm2d where the batch statistics and the affine parameters are fixed """ def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self.register_buffer("bias", torch.zeros(n)) self.register_buffer("running_mean", torch.zeros(n)) self.register_buffer("running_var", torch.ones(n)) def get_scale_bias(self, nhwc=False): scale = self.weight * self.running_var.rsqrt() bias = self.bias - self.running_mean * scale if nhwc: scale = scale.reshape(1, 1, 1, -1) bias = bias.reshape(1, 1, 1, -1) else: scale = scale.reshape(1, -1, 1, 1) bias = bias.reshape(1, -1, 1, 1) return scale, bias def forward(self, x): scale, bias = self.get_scale_bias() return x * scale + bias @torch.jit.script def drelu_dscale1(grad_o, output, scale1): relu_mask = (output>0).half() dx_relu = relu_mask * grad_o g1 = dx_relu * scale1 return g1, dx_relu @torch.jit.script def drelu_dscale2(grad_o, output, scale1, scale2): relu_mask = (output>0).half() dx_relu = relu_mask * grad_o g1 = dx_relu * scale1 g2 = dx_relu * scale2 return g1, g2 class BottleneckFunction(torch.autograd.Function): @staticmethod def forward(ctx, nhwc, stride_1x1, scale, bias, x, *conv): # TODO: clean up order of tensors args = [x, *conv[0:3], *scale[0:3], *bias[0:3]] ctx.downsample = len(conv) > 3 if ctx.downsample: args.append(conv[3]) args.append(scale[3]) args.append(bias[3]) # weight buffers are always in nhwc while shape can be nhwc or channels_last # here we pass in flag and let c++ handle it # alternatively, we can put all sizes into a fixed format and pass it in outputs = fast_bottleneck.forward(nhwc, stride_1x1, args) ctx.save_for_backward(*(args+outputs)) # save relu outputs for drelu ctx.nhwc = nhwc ctx.stride_1x1 = stride_1x1 return outputs[2] # backward relu is not exposed, MUL with mask used now # only support dgrad @staticmethod def backward(ctx, grad_o): outputs = ctx.saved_tensors[-3:] if ctx.downsample: grad_conv3, grad_conv4 = drelu_dscale2(grad_o, outputs[2], ctx.saved_tensors[6], ctx.saved_tensors[11]) else: grad_conv3, grad_conv4 = drelu_dscale1(grad_o, outputs[2], ctx.saved_tensors[6]) # create input vector for backward t_list = [*ctx.saved_tensors[0:10]] t_list.append(grad_conv3) t_list.append(grad_conv4) # outputs used for wgrad and generating drelu mask t_list.append(outputs[0]) t_list.append(outputs[1]) # in case there is downsample if ctx.downsample: t_list.append(ctx.saved_tensors[10]) grads = fast_bottleneck.backward(ctx.nhwc, ctx.stride_1x1, t_list) return (None, None, None, None, *grads) bottleneck_function = BottleneckFunction.apply def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(torch.nn.Module): # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) # while original implementation places the stride at the first 1x1 convolution(self.conv1) # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. # This variant is also known as ResNet V1.5 and improves accuracy according to # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. # here we put it at 1x1 def __init__(self, in_channels, bottleneck_channels, out_channels, stride=1, groups=1, dilation=1, norm_func=None, use_cudnn=False, explicit_nhwc=False): super(Bottleneck, self).__init__() if groups != 1: raise RuntimeError('Only support groups == 1') if dilation != 1: raise RuntimeError('Only support dilation == 1') if norm_func == None: norm_func = FrozenBatchNorm2d else: raise RuntimeError('Only support frozen BN now.') if stride != 1 or in_channels != out_channels: self.downsample = nn.Sequential( conv1x1(in_channels, out_channels, stride), norm_func(out_channels), ) else: self.downsample = None # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(in_channels, bottleneck_channels, stride) self.conv2 = conv3x3(bottleneck_channels, bottleneck_channels) self.conv3 = conv1x1(bottleneck_channels, out_channels) self.relu = nn.ReLU(inplace=True) self.stride = stride self.bn1 = norm_func(bottleneck_channels) self.bn2 = norm_func(bottleneck_channels) self.bn3 = norm_func(out_channels) self.use_cudnn = use_cudnn # setup conv weights self.w_conv = [self.conv1.weight, self.conv2.weight, self.conv3.weight] if self.downsample is not None: self.w_conv.append(self.downsample[0].weight) # init weight in nchw format before possible transpose for w in self.w_conv: kaiming_uniform_(w, a=1) # TODO: prevent unsupported case usage # support cases # native cudnn # normal yes no # channel_last yes yes # explicit_nhwc no yes self.explicit_nhwc = explicit_nhwc if self.explicit_nhwc: for p in self.parameters(): with torch.no_grad(): p.data = p.data.permute(0,2,3,1).contiguous() return def forward(self, x): if self.use_cudnn: # calculate scale/bias from registered buffers # TODO: make this better s1, b1 = self.bn1.get_scale_bias(self.explicit_nhwc) s2, b2 = self.bn2.get_scale_bias(self.explicit_nhwc) s3, b3 = self.bn3.get_scale_bias(self.explicit_nhwc) w_scale = [s1, s2, s3] w_bias = [b1, b2, b3] if self.downsample is not None: s4, b4 = self.downsample[1].get_scale_bias(self.explicit_nhwc) w_scale.append(s4) w_bias.append(b4) out = bottleneck_function(self.explicit_nhwc, self.stride, w_scale, w_bias, x, *self.w_conv) return out if self.explicit_nhwc: raise RuntimeError('explicit nhwc with native ops is not supported.') # fallback to native ops identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out ================================================ FILE: KoSimCSE/apex/contrib/bottleneck/test.py ================================================ import torch from bottleneck import Bottleneck torch.manual_seed(23337) # use True to print layerwise sum for all outputs in reference code path DEBUG = False#True for stride, o_channel in [(1,32), (1,128), (2,32)]: print("testing stride ==", stride, ", in_channel == 32 , out_channel ==", o_channel) a_ = torch.randn(17,32,28,28) a = a_.cuda().half().to(memory_format=torch.channels_last).requires_grad_() model = Bottleneck(32,8,o_channel,stride=stride).cuda().half().to(memory_format=torch.channels_last) # test model b = model(a) b.mean().backward() d_grad = a.grad.float() a.grad = None torch.cuda.synchronize() if DEBUG: print("[DEBUG] ref dx :", d_grad.sum().item()) # print wgrad. we don't need to reset since later cpp print before accumulation for i, w in enumerate(model.w_conv): print("[DEBUG] ref wgrad{} :".format(i+1), w.grad.sum().item()) wgrads = [] for w in model.w_conv: wgrads.append(w.grad.float()) model.use_cudnn = True model.zero_grad() c = model(a) c.mean().backward() torch.cuda.synchronize() print("comparing native and channels_last:") print("max error fprop:", (b-c).abs().max().item(), "max elem:", b.abs().max().item()) print("max error dgrad:", (d_grad-a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item()) for i, (w, wgrad) in enumerate(zip(model.w_conv, wgrads)): print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item()) nhwc_a = a_.permute(0,2,3,1).contiguous().cuda().half().requires_grad_() nhwc_model = Bottleneck(32,8,o_channel,stride=stride,explicit_nhwc=True, use_cudnn=True).cuda().half() for p,q in zip(model.parameters(), nhwc_model.parameters()): # model's storage is already in nhwc, we clone and assign to explicit nhwc model q.data.copy_(p.data.permute(0,2,3,1).contiguous()) for p,q in zip(model.buffers(), nhwc_model.buffers()): q.data.copy_(p.data) d = nhwc_model(nhwc_a) d.mean().backward() torch.cuda.synchronize() # reset reference to cudnn channels_last permute #c_s = c.storage().tolist() #d_s = d.storage().tolist() #print(max([x-y for x,y in zip(c_s,d_s)])) c = c.contiguous(memory_format=torch.contiguous_format).permute(0,2,3,1).contiguous() d_grad = a.grad.float().permute(0,2,3,1).contiguous() wgrads = [] for w in model.w_conv: wgrads.append(w.grad.float().permute(0,2,3,1).contiguous()) torch.cuda.synchronize() print("comparing nhwc and channels_last:") print("max error fprop:", (d-c).abs().max().item(), "max elem:", c.abs().max().item()) print("max error dgrad:", (d_grad-nhwc_a.grad.float()).abs().max().item(), "max elem:", d_grad.abs().max().item()) for i, (w, wgrad) in enumerate(zip(nhwc_model.w_conv, wgrads)): print("max error wgrad{}:".format(i+1), (wgrad - w.grad.float()).abs().max().item(), "max elem:", wgrad.abs().max().item()) ================================================ FILE: KoSimCSE/apex/contrib/csrc/bottleneck/bottleneck.cpp ================================================ #include #include // for getcudnnhandle #include #include #include #include #include #ifdef DEBUG #define DEBUG_MSG(str) do { std::cout << str << std::endl; } while( false ) #else #define DEBUG_MSG(str) do { } while ( false ) #endif #ifdef DEBUG_CUDNN #define DEBUG_CUDNN_MSG(buf, str) do { buf << str << std::endl; } while( false ) #else #define DEBUG_CUDNN_MSG(buf, str) do { } while ( false ) #endif #define checkCudnnErr(...) \ do { \ int err = checkCudnnError(__VA_ARGS__, #__VA_ARGS__, __FILE__, __LINE__); \ if (err) { \ return; \ } \ } while (0) int checkCudnnError(cudnnStatus_t code, const char* expr, const char* file, int line) { if (code) { printf("CUDNN error at %s:%d, code=%d (%s) in '%s'\n", file, line, (int)code, cudnnGetErrorString(code), expr); return 1; } return 0; } void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort = true); #define checkCUDAError(val) { checkError((val), #val, __FILE__, __LINE__); } // in-line regular function void checkError(cudaError_t code, char const * func, const char *file, const int line, bool abort) { if (code != cudaSuccess) { const char * errorMessage = cudaGetErrorString(code); fprintf(stderr, "CUDA error returned from \"%s\" at %s:%d, Error code: %d (%s)\n", func, file, line, code, errorMessage); if (abort){ cudaDeviceReset(); exit(code); } } } void generateStrides(const int64_t* dimA, int64_t* strideA, int nbDims, cudnnTensorFormat_t filterFormat) { // For INT8x4 and INT8x32 we still compute standard strides here to input // into the cuDNN functions. We will manually scale by resizeFactor in the cpu ref. if (filterFormat == CUDNN_TENSOR_NCHW) { strideA[nbDims - 1] = 1; for (int64_t d = nbDims - 2; d >= 0; d--) { strideA[d] = strideA[d + 1] * dimA[d + 1]; } } else { // Here we assume that the format is CUDNN_TENSOR_NHWC strideA[1] = 1; strideA[nbDims - 1] = strideA[1] * dimA[1]; for (int64_t d = nbDims - 2; d >= 2; d--) { strideA[d] = strideA[d + 1] * dimA[d + 1]; } strideA[0] = strideA[2] * dimA[2]; } } int getFwdConvDilatedFilterDim(int filterDim, int dilation) { return ((filterDim - 1) * dilation) + 1; } int getFwdConvPaddedImageDim(int tensorDim, int pad) { return tensorDim + (2 * pad); } int getFwdConvOutputDim( int tensorDim, int pad, int filterDim, int stride, int dilation) { int p = (getFwdConvPaddedImageDim(tensorDim, pad) - getFwdConvDilatedFilterDim(filterDim, dilation)) / stride + 1; return (p); } enum { X_TENSOR, Y_TENSOR, W_TENSOR, Z_TENSOR, B_TENSOR, AFTERADD_TENSOR, AFTERBIAS_TENSOR, AFTERCONV_TENSOR, OPTIONAL, AFTEROPT_TENSOR, }; using common_conv_descriptors = std::tuple; common_conv_descriptors create_common_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, cudnnConvolutionMode_t mode) { const int convDim = 2; int64_t strideA_padded[4]; int64_t outstrideA_padded[4]; int64_t filterstrideA_padded[4]; generateStrides(w_dim_padded, filterstrideA_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, strideA_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, outstrideA_padded, 4, CUDNN_TENSOR_NHWC); return common_conv_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, strideA_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, outstrideA_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, filterstrideA_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(mode) .setNDims(convDim) .setStrides(convDim, convstrideA) .setPrePadding(convDim, padA) .setPostPadding(convDim, padA) .setDilation(convDim, dilationA) .build()); } using common_convbias_descriptors = std::tuple; common_convbias_descriptors create_conv_bias_add_act_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType) { const int convDim = 2; int64_t b_dim_padded[4]; b_dim_padded[0] = 1; b_dim_padded[1] = y_dim_padded[1]; b_dim_padded[2] = 1; b_dim_padded[3] = 1; int64_t x_stride_padded[4]; int64_t y_stride_padded[4]; int64_t w_stride_padded[4]; int64_t b_stride_padded[4]; generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC); return common_convbias_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, w_stride_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('z') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('b') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setVirtual() .setId('A') // after add .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setVirtual() .setId('B') // after bias .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('C') // after conv .setAlignment(16) .setVirtual() .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('i') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('D') // after optional add .setAlignment(16) .setVirtual() .setDataType(dataType) .build()); } // tensor descriptors used for dgrad enum { X_OR_DX_TENSOR, DY_TENSOR, W_OR_DW_TENSOR, SCALE_TENSOR, RELU_TENSOR, AFTER_DCONV_TENSOR, AFTER_DRELU_TENSOR, }; using dconv_descriptors = std::tuple; dconv_descriptors create_dconv_descriptors(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType) { const int convDim = 2; int64_t b_dim_padded[4]; b_dim_padded[0] = 1; b_dim_padded[1] = x_dim_padded[1]; b_dim_padded[2] = 1; b_dim_padded[3] = 1; int64_t x_stride_padded[4]; int64_t y_stride_padded[4]; int64_t w_stride_padded[4]; int64_t b_stride_padded[4]; generateStrides(w_dim_padded, w_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(x_dim_padded, x_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(y_dim_padded, y_stride_padded, 4, CUDNN_TENSOR_NHWC); generateStrides(b_dim_padded, b_stride_padded, 4, CUDNN_TENSOR_NHWC); return dconv_descriptors(cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('x') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, y_dim_padded) .setStrides(4, y_stride_padded) .setId('y') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, w_dim_padded) .setStrides(4, w_stride_padded) .setId('w') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, b_dim_padded) .setStrides(4, b_stride_padded) .setId('s') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setId('r') .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setVirtual() .setId('A') // after dconv .setAlignment(16) .setDataType(dataType) .build(), cudnn_frontend::TensorBuilder() .setDim(4, x_dim_padded) .setStrides(4, x_stride_padded) .setVirtual() .setId('B') // after drelu .setAlignment(16) .setDataType(dataType) .build()); } // create a cache for plan std::unordered_map plan_cache; // TODO: better name std::string getConvFusionString(int64_t* x_dim_padded, int64_t* padA, int64_t* convstrideA, int64_t* dilationA, int64_t* w_dim_padded, cudnnDataType_t dataType, std::string fusion_string) { for(int i=0;i<4;i++) { fusion_string += 'X'; fusion_string += std::to_string(x_dim_padded[i]); } for(int i=0;i<4;i++) { fusion_string += 'W'; fusion_string += std::to_string(w_dim_padded[i]); } for(int i=0;i<2;i++) { fusion_string += 'P'; fusion_string += std::to_string(padA[i]); } for(int i=0;i<2;i++) { fusion_string += 'S'; fusion_string += std::to_string(convstrideA[i]); } for(int i=0;i<2;i++) { fusion_string += 'D'; fusion_string += std::to_string(dilationA[i]); } fusion_string += 'T'; fusion_string += std::to_string(dataType); return fusion_string; } cudnn_frontend::ExecutionPlan& getOrCreatePlan(cudnnHandle_t handle_, std::stringstream& log_buf, cudnn_frontend::OperationGraph& opGraph, std::string cache_string, bool use_heuristic = true){ auto it = plan_cache.find(cache_string); if (it != plan_cache.end()) { DEBUG_CUDNN_MSG(log_buf, "Found plan in cache"); return it->second; } else { if (use_heuristic){ // TODO: confirm which mode to use auto heuristics = cudnn_frontend::EngineHeuristicsBuilder() .setOperationGraph(opGraph) .setHeurMode(CUDNN_HEUR_MODE_INSTANT) .build(); // try 3 times for now as WAR for no heuristic training int max_tries = 3, count = 0; auto& engine_configs = heuristics.getEngineConfig(max_tries); while(true) { try { plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder() .setHandle(handle_) .setEngineConfig(engine_configs[count], opGraph.getTag()) .build())); break; } catch (cudnn_frontend::cudnnException e) { if (++count == max_tries) throw e; } } }else{ DEBUG_CUDNN_MSG(log_buf, "No plan in cache"); // How many engines support this operation graph ? auto total_engines = opGraph.getEngineCount(); DEBUG_CUDNN_MSG(log_buf, opGraph.describe() << " has " << total_engines << " engines."); // We have to randomly pick one engine from [0, total_engines) // Selecting "0" by default auto engine = cudnn_frontend::EngineBuilder().setGlobalEngineIdx(0).setOperationGraph(opGraph).build(); DEBUG_CUDNN_MSG(log_buf, engine.describe()); auto& knobs = engine.getSupportedKnobs(); for (auto it = std::begin(knobs); it != std::end(knobs); ++it) { DEBUG_CUDNN_MSG(log_buf, it->describe()); } if (knobs.begin() != knobs.end()) { DEBUG_CUDNN_MSG(log_buf, "Updated knob choice"); knobs.begin()->setChoice(knobs.begin()->getMinValue() + 1); DEBUG_CUDNN_MSG(log_buf, knobs.begin()->describe()); } // Createmplacee the requisite engine config auto engine_config = cudnn_frontend::EngineConfigBuilder().setEngine(engine).build(); DEBUG_CUDNN_MSG(log_buf, engine_config.describe()); plan_cache.emplace(cache_string, std::move(cudnn_frontend::ExecutionPlanBuilder().setHandle(handle_).setEngineConfig(engine_config).build())); } return plan_cache.find(cache_string)->second; } } void run_conv_scale_bias_add_activation(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrB, at::Half* devPtrI) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the add operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); // Define the bias operation auto biasDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, biasDesc.describe()); // optional add auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); // Define the activation operation auto actDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_RELU_FWD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, actDesc.describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) .setxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create a Add Node with scaling parameters. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(conv_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create a Bias Node. auto bias_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(scale_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(biasDesc) .build(); DEBUG_CUDNN_MSG(log_buf, bias_op.describe()); // Create a optional add Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(bias_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Activation Node. auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(devPtrI ? add_op.getOutputTensor() : bias_op.getOutputTensor()) .setyDesc(std::get(tensors)) .setpwDesc(actDesc) .build(); DEBUG_CUDNN_MSG(log_buf, act_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &scale_op, &bias_op, devPtrI ? &add_op : &act_op, &act_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(devPtrI ? ops.size() : 4, ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB, devPtrI}; int64_t uids[] = {'x', 'y', 'w', 'z', 'b', 'i'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(devPtrI ? 6 : 5, data_ptrs) .setUids(devPtrI ? 6 : 5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_conv_scale_bias(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrB) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors common_convbias_descriptors tensors = create_conv_bias_add_act_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the add operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); // Define the bias operation auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_FORWARD_DESCRIPTOR) .setxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create a Add Node with scaling parameters. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(conv_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) // TODO: change enum to aftermul .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create a Bias Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(scale_op.getOutputTensor()) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &scale_op, &add_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrB}; int64_t uids[] = {'x', 'y', 'w', 'z', 'b'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(5, data_ptrs) .setUids(5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv_drelu_dscale(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrZ, at::Half* devPtrR) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); // Define the activation backward operation auto actDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_RELU_BWD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, actDesc.describe()); // Define the scale backward operation auto scaleDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_MUL) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, scaleDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) .setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // TODO: do we need getOutputTensor(), and what it returns in backward case? // Create an relu backward Node. auto act_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setdyDesc(std::get(tensors)) .setxDesc(std::get(tensors)) .setdxDesc(std::get(tensors)) .setpwDesc(actDesc) .build(); DEBUG_CUDNN_MSG(log_buf, act_op.describe()); // Create a Scale Node. auto scale_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(std::get(tensors)) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(scaleDesc) .build(); DEBUG_CUDNN_MSG(log_buf, scale_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &act_op, &scale_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrZ, devPtrR}; int64_t uids[] = {'x', 'y', 'w', 's', 'r'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(5, data_ptrs) .setUids(5, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, cudnnBackendDescriptorType_t mode) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node // mode should be one of following // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR // CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR auto conv_op_builder = cudnn_frontend::OperationBuilder(mode); if (mode == CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) { conv_op_builder.setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta); } else { conv_op_builder.setxDesc(std::get(tensors)) .setdwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta); } auto conv_op = conv_op_builder.build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW}; int64_t uids[] = {'x', 'y', 'w'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(3, data_ptrs) .setUids(3, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } void run_dconv_add(int64_t* x_dim_padded, int64_t* pad, int64_t* convstride, int64_t* dilation, int64_t* w_dim_padded, int64_t* y_dim_padded, cudnnDataType_t dataType, at::Half* devPtrX, at::Half* devPtrW, at::Half* devPtrY, at::Half* devPtrR) { cudnnHandle_t handle_ = torch::native::getCudnnHandle(); std::stringstream log_buf; try { int convDim = 2; // Creates the necessary tensor descriptors dconv_descriptors tensors = create_dconv_descriptors( x_dim_padded, pad, convstride, dilation, w_dim_padded, y_dim_padded, dataType); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); DEBUG_CUDNN_MSG(log_buf, std::get(tensors).describe()); // Define the convolution problem auto convDesc = cudnn_frontend::ConvDescBuilder() .setDataType(CUDNN_DATA_FLOAT) .setMathMode(CUDNN_CROSS_CORRELATION) .setNDims(convDim) .setStrides(convDim, convstride) .setPrePadding(convDim, pad) .setPostPadding(convDim, pad) .setDilation(convDim, dilation) .build(); DEBUG_CUDNN_MSG(log_buf, convDesc.describe()); // Define the add backward operation auto addDesc = cudnn_frontend::PointWiseDescBuilder() .setMode(CUDNN_POINTWISE_ADD) .setMathPrecision(CUDNN_DATA_FLOAT) .build(); DEBUG_CUDNN_MSG(log_buf, addDesc.describe()); float alpha = 1.0f; float beta = 0.0f; // Create a convolution Node auto conv_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR) .setdxDesc(std::get(tensors)) .setwDesc(std::get(tensors)) .setdyDesc(std::get(tensors)) .setcDesc(convDesc) .setAlpha(alpha) .setBeta(beta) .build(); DEBUG_CUDNN_MSG(log_buf, conv_op.describe()); // TODO: do we need getOutputTensor(), and what it returns in backward case? // Create add Node. auto add_op = cudnn_frontend::OperationBuilder(CUDNN_BACKEND_OPERATION_POINTWISE_DESCRIPTOR) .setxDesc(std::get(tensors)) .setbDesc(std::get(tensors)) .setyDesc(std::get(tensors)) .setpwDesc(addDesc) .build(); DEBUG_CUDNN_MSG(log_buf, add_op.describe()); // Create an Operation Graph. In this case it is convolution add bias activation std::array ops = {&conv_op, &add_op}; auto opGraph = cudnn_frontend::OperationGraphBuilder() .setHandle(handle_) .setOperationGraph(ops.size(), ops.data()) .build(); // Create string encoding for plan caching auto cache_string = getConvFusionString(x_dim_padded, pad, convstride, dilation, w_dim_padded, dataType, opGraph.getTag()); DEBUG_CUDNN_MSG(log_buf, "[convstring] " << cache_string); auto& plan = getOrCreatePlan(handle_, log_buf, opGraph, cache_string); DEBUG_CUDNN_MSG(log_buf, "Plan tag: " << plan.getTag()); auto workspace_size = plan.getWorkspaceSize(); DEBUG_CUDNN_MSG(log_buf, plan.describe() << " requires workspace " << workspace_size); void* workspace_ptr = nullptr; auto workspace_tensor = at::empty({(workspace_size+3)/4}, at::TensorOptions(at::kCUDA).dtype(at::kFloat)); if (workspace_size > 0) { workspace_ptr = workspace_tensor.data_ptr(); } void* data_ptrs[] = {devPtrX, devPtrY, devPtrW, devPtrR}; int64_t uids[] = {'x', 'y', 'w', 'r'}; auto variantPack = cudnn_frontend::VariantPackBuilder() .setWorkspacePointer(workspace_ptr) .setDataPointers(4, data_ptrs) .setUids(4, uids) .build(); DEBUG_CUDNN_MSG(log_buf, "variantPack " << variantPack.describe()); cudnnStatus_t status = cudnnBackendExecute(handle_, plan.get_raw_desc(), variantPack.get_raw_desc()); checkCudnnErr(status); cudnn_frontend::throw_if([status]() { return (status != CUDNN_STATUS_SUCCESS); }, "Plan execute error"); } catch (cudnn_frontend::cudnnException e) { std::cout << log_buf.str() << "[ERROR] Exception " << e.what() << std::endl; } } // inputs contains x,w,z,b,(i) std::vector bottleneck_forward(bool explicit_nhwc, int stride_1X1, std::vector inputs) { std::cout << std::fixed; // create output vector std::vector outputs; auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast; // setup dimensions int64_t dimA[] = {0, 0, 0, 0}; int64_t filterdimA1[] = {0, 0, 0, 0}; int64_t filterdimA2[] = {0, 0, 0, 0}; int64_t filterdimA3[] = {0, 0, 0, 0}; int64_t filterdimA4[] = {0, 0, 0, 0}; // All dim calculation after this order of n,c,h,w int axis[] {0,1,2,3}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 3; axis[2] = 1; axis[3] = 2; } for (int dim=0;dim<4;dim++) { dimA[dim] = inputs[0].size(axis[dim]); filterdimA1[dim] = inputs[1].size(axis[dim]); filterdimA2[dim] = inputs[2].size(axis[dim]); filterdimA3[dim] = inputs[3].size(axis[dim]); } if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { for (int dim=0;dim<4;dim++) { filterdimA4[dim] = inputs[10].size(axis[dim]); } } // output dim in n,c,h,w used by backend int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below // use these fixed value for test run int64_t padA[] = {0, 0}; int64_t padA1[] = {1, 1}; int64_t dilationA[] = {1, 1}; int64_t convstrideA[] = {1, 1}; int64_t convstride1X1[] = {stride_1X1, stride_1X1}; // compute output from pad/stride/dilation outdimA1[0] = dimA[0]; outdimA1[1] = filterdimA1[0]; for (int dim = 0; dim < 2; dim++) { outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]); } outdimA2[0] = outdimA1[0]; outdimA2[1] = filterdimA2[0]; for (int dim = 0; dim < 2; dim++) { outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]); } outdimA3[0] = outdimA2[0]; outdimA3[1] = filterdimA3[0]; for (int dim = 0; dim < 2; dim++) { outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]); } // Create output tensor in the correct shape in pytorch's view int64_t outdim1[] = {0, 0, 0, 0}; int64_t outdim2[] = {0, 0, 0, 0}; int64_t outdim3[] = {0, 0, 0, 0}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 2; axis[2] = 3; axis[3] = 1; } for (int dim=0;dim<4;dim++) { outdim1[dim] = outdimA1[axis[dim]]; outdim2[dim] = outdimA2[axis[dim]]; outdim3[dim] = outdimA3[axis[dim]]; } // run at::Half* x = inputs[0].data_ptr(); at::Half* w = inputs[1].data_ptr(); at::Half* z = inputs[4].data_ptr(); at::Half* b = inputs[7].data_ptr(); auto out1 = at::empty(outdim1, inputs[0].type(), output_format); at::Half* y1 = out1.data_ptr(); run_conv_scale_bias_add_activation(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, x, w, y1, z, b, nullptr); DEBUG_MSG("[DEBUG] new relu1 : " << out1.to(at::kFloat).sum().item()); w = inputs[2].data_ptr(); z = inputs[5].data_ptr(); b = inputs[8].data_ptr(); auto out2 = at::empty(outdim2, inputs[0].type(), output_format); at::Half* y2 = out2.data_ptr(); run_conv_scale_bias_add_activation(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, y1, w, y2, z, b, nullptr); DEBUG_MSG("[DEBUG] new relu2 : " << out2.to(at::kFloat).sum().item()); // create output of conv3 auto out3 = at::empty(outdim3, inputs[0].type(), output_format); at::Half* y3 = out3.data_ptr(); // create output of conv4 that may exist auto identity = at::empty_like(out3); at::Half* yi = identity.data_ptr(); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){ w = inputs[10].data_ptr(); z = inputs[11].data_ptr(); b = inputs[12].data_ptr(); run_conv_scale_bias(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, x, w, yi, z, b); DEBUG_MSG("[DEBUG] new downsample : " << identity.to(at::kFloat).sum().item()); } else { yi = x; } w = inputs[3].data_ptr(); z = inputs[6].data_ptr(); b = inputs[9].data_ptr(); run_conv_scale_bias_add_activation(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, y2, w, y3, z, b, yi); DEBUG_MSG("[DEBUG] new relu3 : " << out3.to(at::kFloat).sum().item()); outputs.push_back(out1); outputs.push_back(out2); outputs.push_back(out3); return outputs; } std::vector bottleneck_backward(bool explicit_nhwc, int stride_1X1, std::vector inputs) { bool requires_grad = inputs[0].requires_grad(); std::cout << std::fixed; // create output vector std::vector outputs; auto output_format = explicit_nhwc ? at::MemoryFormat::Contiguous : at::MemoryFormat::ChannelsLast; // setup dimensions int64_t dimA[] = {0, 0, 0, 0}; int64_t filterdimA1[] = {0, 0, 0, 0}; int64_t filterdimA2[] = {0, 0, 0, 0}; int64_t filterdimA3[] = {0, 0, 0, 0}; int64_t filterdimA4[] = {0, 0, 0, 0}; // All dim calculation after this order of n,c,h,w int axis[] {0,1,2,3}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 3; axis[2] = 1; axis[3] = 2; } for (int dim=0;dim<4;dim++) { dimA[dim] = inputs[0].size(axis[dim]); filterdimA1[dim] = inputs[1].size(axis[dim]); filterdimA2[dim] = inputs[2].size(axis[dim]); filterdimA3[dim] = inputs[3].size(axis[dim]); } if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { for (int dim=0;dim<4;dim++) { filterdimA4[dim] = inputs[14].size(axis[dim]); } } // output dim in n,c,h,w used by backend int64_t outdimA1[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA2[] = {0, 0, 0, 0}; // Computed Below int64_t outdimA3[] = {0, 0, 0, 0}; // Computed Below // use these fixed value for test run int64_t padA[] = {0, 0}; int64_t padA1[] = {1, 1}; int64_t dilationA[] = {1, 1}; int64_t convstrideA[] = {1, 1}; int64_t convstride1X1[] = {stride_1X1, stride_1X1}; // compute output from pad/stride/dilation outdimA1[0] = dimA[0]; outdimA1[1] = filterdimA1[0]; for (int dim = 0; dim < 2; dim++) { outdimA1[dim + 2] = getFwdConvOutputDim(dimA[dim + 2], padA[dim], filterdimA1[dim + 2], convstride1X1[dim], dilationA[dim]); } outdimA2[0] = outdimA1[0]; outdimA2[1] = filterdimA2[0]; for (int dim = 0; dim < 2; dim++) { outdimA2[dim + 2] = getFwdConvOutputDim(outdimA1[dim + 2], padA1[dim], filterdimA2[dim + 2], convstrideA[dim], dilationA[dim]); } outdimA3[0] = outdimA2[0]; outdimA3[1] = filterdimA3[0]; for (int dim = 0; dim < 2; dim++) { outdimA3[dim + 2] = getFwdConvOutputDim(outdimA2[dim + 2], padA[dim], filterdimA3[dim + 2], convstrideA[dim], dilationA[dim]); } // Create output tensor in the correct shape in pytorch's view int64_t outdim1[] = {0, 0, 0, 0}; int64_t outdim2[] = {0, 0, 0, 0}; int64_t outdim3[] = {0, 0, 0, 0}; if (explicit_nhwc) { axis[0] = 0; axis[1] = 2; axis[2] = 3; axis[3] = 1; } for (int dim=0;dim<4;dim++) { outdim1[dim] = outdimA1[axis[dim]]; outdim2[dim] = outdimA2[axis[dim]]; outdim3[dim] = outdimA3[axis[dim]]; } // dconv3+drelu2+dscale2 at::Half* conv_in = inputs[13].data_ptr(); at::Half* dy3 = inputs[10].data_ptr(); DEBUG_MSG("[DEBUG] new dconv3 : " << inputs[10].to(at::kFloat).sum().item()); // wgrad auto wgrad3 = at::empty_like(inputs[3]); at::Half* dw3 = wgrad3.data_ptr(); run_dconv(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, conv_in, dw3, dy3, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad auto grad_out2 = at::empty(outdim2, inputs[0].type(), output_format); at::Half* dy2 = grad_out2.data_ptr(); at::Half* w = inputs[3].data_ptr(); at::Half* z = inputs[5].data_ptr(); at::Half* relu2 = inputs[13].data_ptr(); run_dconv_drelu_dscale(outdimA2, padA, convstrideA, dilationA, filterdimA3, outdimA3, CUDNN_DATA_HALF, dy2, w, dy3, z, relu2); DEBUG_MSG("[DEBUG] new dconv2 : " << grad_out2.to(at::kFloat).sum().item()); // dconv2+drelu1+dscale1 conv_in = inputs[12].data_ptr(); // wgrad auto wgrad2 = at::empty_like(inputs[2]); at::Half* dw2 = wgrad2.data_ptr(); run_dconv(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, conv_in, dw2, dy2, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad auto grad_out1 = at::empty(outdim1, inputs[0].type(), output_format); at::Half* dy1 = grad_out1.data_ptr(); w = inputs[2].data_ptr(); z = inputs[4].data_ptr(); at::Half* relu1 = inputs[12].data_ptr(); // fused dgrad run_dconv_drelu_dscale(outdimA1, padA1, convstrideA, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, z, relu1); /* // backward strided conv cannot be fused // if stride == 1 but channel changes, we can fuse here if (stride_1X1 != 1){ // dgrad run_dconv(outdimA1, padA1, convstride1X1, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // mul fused mask grad_out1.mul_(inputs[15]); } else { at::Half* relu1 = inputs[12].data_ptr(); // fused dgrad run_dconv_drelu_dscale(outdimA1, padA1, convstride1X1, dilationA, filterdimA2, outdimA2, CUDNN_DATA_HALF, dy1, w, dy2, z, relu1); } */ DEBUG_MSG("[DEBUG] new dconv1 : " << grad_out1.to(at::kFloat).sum().item()); // create grads of conv4 that may exist auto grad_x_conv4 = at::empty_like(inputs[0]); at::Half* dx_conv4 = grad_x_conv4.data_ptr(); at::Tensor wgrad4; // x used for dconv1 and dconv4 wgrad at::Half* x = inputs[0].data_ptr(); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]){ w = inputs[14].data_ptr(); at::Half* dy_conv4 = inputs[11].data_ptr(); if (requires_grad) { run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, dx_conv4, w, dy_conv4, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // we don't print here since we can't hook out this grad in pytorch alone to compare, due to addition with dx // DEBUG_MSG("[DEBUG] new dx_identity : " << grad_x_conv4.to(at::kFloat).sum().item()); } // wgrad wgrad4 = at::empty_like(inputs[14]); at::Half* dw4 = wgrad4.data_ptr(); run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA4, outdimA3, CUDNN_DATA_HALF, x, dw4, dy_conv4, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); } else { // if there is no downsample, dx_conv4 is fork of drelu3 dx_conv4 = inputs[11].data_ptr(); } // dconv1+add // wgrad auto wgrad1 = at::empty_like(inputs[1]); at::Half* dw1 = wgrad1.data_ptr(); run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, x, dw1, dy1, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_FILTER_DESCRIPTOR); // dgrad w = inputs[1].data_ptr(); auto grad_x = at::empty_like(inputs[0]); at::Half* dx = grad_x.data_ptr(); // backward strided conv cannot be fused // if stride == 1 but channel changes, we can fuse here if (requires_grad){ if (stride_1X1 != 1){ run_dconv(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, dx, w, dy1, CUDNN_BACKEND_OPERATION_CONVOLUTION_BACKWARD_DATA_DESCRIPTOR); // add 2 together grad_x.add_(grad_x_conv4); } else { run_dconv_add(dimA, padA, convstride1X1, dilationA, filterdimA1, outdimA1, CUDNN_DATA_HALF, dx, w, dy1, dx_conv4); } } DEBUG_MSG("[DEBUG] new dx : " << grad_x.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad1 : " << wgrad1.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad2 : " << wgrad2.to(at::kFloat).sum().item()); DEBUG_MSG("[DEBUG] new wgrad3 : " << wgrad3.to(at::kFloat).sum().item()); outputs.push_back(grad_x); outputs.push_back(wgrad1); outputs.push_back(wgrad2); outputs.push_back(wgrad3); if (stride_1X1 != 1 || filterdimA3[0] != dimA[1]) { DEBUG_MSG("[DEBUG] new wgrad4 : " << wgrad4.to(at::kFloat).sum().item()); outputs.push_back(wgrad4); } return outputs; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &bottleneck_forward, "Bottleneck block forward"); m.def("backward", &bottleneck_backward, "Bottleneck block backward"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/fmha_api.cpp ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include #include #include "fmha.h" void set_params(Fused_multihead_attention_fprop_params ¶ms, // sizes const size_t b, const size_t s, const size_t h, const size_t d, // device pointers void *qkv_packed_d, void *cu_seqlens_d, void *o_packed_d, void *s_d, float p_dropout) { Data_type acc_type = DATA_TYPE_FP32; Data_type data_type = DATA_TYPE_FP16; // Reset the parameters memset(¶ms, 0, sizeof(params)); // Set the pointers and strides. params.qkv_ptr = qkv_packed_d; params.qkv_stride_in_bytes = get_size_in_bytes(h * 3 * d, data_type); params.o_ptr = o_packed_d; params.o_stride_in_bytes = get_size_in_bytes(h * d, data_type); params.cu_seqlens = static_cast(cu_seqlens_d); // S = softmax(P) params.s_ptr = s_d; params.s_stride_in_bytes = get_size_in_bytes(b * h * s, data_type); // Set the dimensions. params.b = b; params.h = h; params.s = s; params.d = d; // Set the different scale values. const float scale_bmm1 = 1.f / sqrtf(d); constexpr float scale_softmax = 1.f; constexpr float scale_bmm2 = 1.f; set_alpha(params.scale_bmm1, scale_bmm1, acc_type); set_alpha(params.scale_softmax, scale_softmax, acc_type); set_alpha(params.scale_bmm2, scale_bmm2, data_type); // Set this to probability of keeping an element to simplify things. params.p_dropout = 1.f - p_dropout; params.rp_dropout = 1.f / params.p_dropout; TORCH_CHECK(p_dropout < 1.f); set_alpha(params.scale_dropout, params.rp_dropout, data_type); } std::vector mha_fwd(const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i const at::Tensor &cu_seqlens, // b+1 const float p_dropout, const int max_seq_len, const bool is_training, c10::optional gen_) { auto dprops = at::cuda::getCurrentDeviceProperties(); TORCH_CHECK(dprops->major == 8 && dprops->minor == 0); int seq_len = 512; auto launch = &run_fmha_fp16_512_64_sm80; if( max_seq_len <= 128 ) { seq_len = 128; launch = &run_fmha_fp16_128_64_sm80; } else if( max_seq_len <= 256 ) { seq_len = 256; launch = &run_fmha_fp16_256_64_sm80; } else if( max_seq_len <= 384 ) { seq_len = 384; launch = &run_fmha_fp16_384_64_sm80; } else if( max_seq_len <= 512 ) { seq_len = 512; launch = &run_fmha_fp16_512_64_sm80; } else { TORCH_CHECK(false); } constexpr int warps_m = 1; constexpr int warps_n = 4; // this leads to an upper bound const int mmas_m = seq_len / 16 / warps_m; const int mmas_n = seq_len / 16 / warps_n; const int elts_per_thread = 8 * mmas_m * mmas_n; auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.dtype() == torch::kFloat16); TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto opts = qkv.options(); auto ctx = torch::empty({ total, num_heads, head_size }, opts); auto s = torch::empty({ batch_size, num_heads, seq_len, seq_len }, opts); auto gen = at::get_generator_or_default( gen_, at::cuda::detail::getDefaultCUDAGenerator()); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), ctx.data_ptr(), s.data_ptr(), p_dropout); // number of times random will be generated per thread, to offset philox counter in thc random // state int64_t counter_offset = elts_per_thread; at::PhiloxCudaState rng_engine_inputs; if( is_training ) { // See Note [Acquire lock when using random generators] std::lock_guard lock(gen->mutex_); params.philox_args = gen->philox_cuda_state(counter_offset); } launch(params, is_training, stream); return { ctx, s }; } std::vector mha_bwd(const at::Tensor &dout, // total x num_heads, x head_size const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i at::Tensor &softmax, // b x h x s x s softmax and dmask - will be overwritten with dP const at::Tensor &cu_seqlens, // b+1 const float p_dropout, // probability to drop const int max_seq_len // max sequence length to choose the kernel ) { auto dprops = at::cuda::getCurrentDeviceProperties(); TORCH_CHECK(dprops->major == 8 && dprops->minor == 0); int seq_len = 512; auto launch = &run_fmha_dgrad_fp16_512_64_sm80; if( max_seq_len <= 128 ) { seq_len = 128; launch = &run_fmha_dgrad_fp16_128_64_sm80; } else if( max_seq_len <= 256 ) { seq_len = 256; launch = &run_fmha_dgrad_fp16_256_64_sm80; } else if( max_seq_len <= 384 ) { seq_len = 384; launch = &run_fmha_dgrad_fp16_384_64_sm80; } else if( max_seq_len <= 512 ) { seq_len = 512; launch = &run_fmha_dgrad_fp16_512_64_sm80; } else { TORCH_CHECK(false); } auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.dtype() == torch::kFloat16); TORCH_CHECK(dout.dtype() == torch::kFloat16); TORCH_CHECK(softmax.dtype() == torch::kFloat16); TORCH_CHECK(cu_seqlens.dtype() == torch::kInt32); TORCH_CHECK(qkv.is_cuda()); TORCH_CHECK(cu_seqlens.is_cuda()); TORCH_CHECK(qkv.is_contiguous()); TORCH_CHECK(cu_seqlens.is_contiguous()); TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto dqkv = torch::empty_like(qkv); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), dout.data_ptr(), // we set o_ptr to dout softmax.data_ptr(), // softmax gets overwritten by dP! p_dropout); // we're re-using these scales Data_type acc_type = DATA_TYPE_FP32; set_alpha(params.scale_bmm1, 1.f, acc_type); set_alpha(params.scale_softmax, 1.f / sqrtf(head_size), acc_type); set_alpha(params.scale_bmm2, 1.f, DATA_TYPE_FP16); params.dqkv_ptr = dqkv.data_ptr(); launch(params, stream); return { dqkv, softmax }; } std::vector mha_fwd_nl(const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i const at::Tensor &cu_seqlens, // b+1 const float p_dropout, const int max_seq_len, const bool is_training, c10::optional gen_) { int seq_len = 512; auto launch = &run_fmha_fp16_512_64_sm80_nl; TORCH_CHECK(max_seq_len == seq_len); constexpr int warps_m = 1; constexpr int warps_n = 4; // this leads to an upper bound const int mmas_m = seq_len / 16 / warps_m; const int mmas_n = seq_len / 16 / warps_n; // static_assert( mmas_m == 32 ); // static_assert( mmas_n == 4 ); const int elts_per_thread = 8 * mmas_m * mmas_n; auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); auto opts = qkv.options(); auto ctx = torch::empty({ total, num_heads, head_size }, opts); auto s = torch::empty({ batch_size, num_heads, seq_len, seq_len }, opts); auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), ctx.data_ptr(), s.data_ptr(), p_dropout); // number of times random will be generated per thread, to offset philox counter in thc random // state int64_t counter_offset = elts_per_thread; at::PhiloxCudaState rng_engine_inputs; if( is_training ) { // See Note [Acquire lock when using random generators] std::lock_guard lock(gen->mutex_); params.philox_args = gen->philox_cuda_state(counter_offset); } int num_chunks = 3; if(batch_size == 3) { num_chunks = 2; } launch(params, is_training, num_chunks, stream); return { ctx, s }; } std::vector mha_bwd_nl(const at::Tensor &dout, // total x num_heads, x head_size const at::Tensor &qkv, // total x num_heads x 3 x head_size, total := \sum_{i=0}^{b} s_i at::Tensor &softmax, // b x h x s x s softmax and dmask - will be overwritten with dP const at::Tensor &cu_seqlens, // b+1 const float p_dropout, // probability to drop const int max_seq_len // max sequence length to choose the kernel ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); TORCH_CHECK(qkv.is_cuda()) TORCH_CHECK(cu_seqlens.is_cuda()) TORCH_CHECK(qkv.is_contiguous()) TORCH_CHECK(cu_seqlens.is_contiguous()) TORCH_CHECK(cu_seqlens.dim() == 1); TORCH_CHECK(qkv.dim() == 4); const auto sizes = qkv.sizes(); TORCH_CHECK(sizes[THREE_DIM] == 3); const int batch_size = cu_seqlens.numel() - 1; const int total = sizes[TOTAL_DIM]; const int num_heads = sizes[H_DIM]; const int head_size = sizes[D_DIM]; TORCH_CHECK(batch_size > 0); TORCH_CHECK(head_size == 64); int seq_len = 512; auto launch = &run_fmha_dgrad_fp16_512_64_sm80_nl; auto opts = qkv.options(); auto dqkv = torch::empty_like(qkv); int num_chunks = 2; if( batch_size == 1 ) { num_chunks = 4; }else if( batch_size == 2 ) { num_chunks = 3; } auto dkv = torch::empty({total, num_chunks, 2, num_heads, head_size}, opts); Fused_multihead_attention_fprop_params params; set_params(params, batch_size, seq_len, num_heads, head_size, qkv.data_ptr(), cu_seqlens.data_ptr(), dout.data_ptr(), // o_ptr = dout softmax.data_ptr(), // softmax gets overwritten by dP! p_dropout); params.dkv_ptr = dkv.data_ptr(); Data_type acc_type = DATA_TYPE_FP32; set_alpha(params.scale_bmm1, 1.f, acc_type); set_alpha(params.scale_softmax, 1.f / sqrtf(head_size), acc_type); set_alpha(params.scale_bmm2, 1.f, DATA_TYPE_FP16); params.dqkv_ptr = dqkv.data_ptr(); launch(params, num_chunks, stream); //SPLIT-K reduction of num_chunks dK, dV parts // The equivalent of the following Pytorch code: // using namespace torch::indexing; // at::Tensor view_out = dqkv.index({Slice(), Slice(1, None, None)}); // torch::sum_out(view_out, dkv, 1); const int hidden_size = num_heads * head_size; fmha_run_noloop_reduce( dqkv.data_ptr(), dkv.data_ptr(), cu_seqlens.data_ptr(), hidden_size, batch_size, total, num_chunks, stream); return { dqkv, softmax, dkv }; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.doc() = "Fused Multi-head Self-attention for BERT"; m.def("fwd", &mha_fwd, "Forward pass"); m.def("bwd", &mha_bwd, "Backward pass"); m.def("fwd_nl", &mha_fwd_nl, "Forward pass (small-batch)"); m.def("bwd_nl", &mha_bwd_nl, "Backward pass (small-batch)"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/gemm.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #define FMHA_DIV_UP(m, n) (((m) + (n)-1) / (n)) namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type_, int NUM_ELTS_, int BITS_PER_ELT_, int ALIGNMENT_ > struct Fragment_base_ { // The data type. using Data_type = Data_type_; // default input type using Input_type_ = Data_type_; // Does it store the array of elements. enum { HAS_ELTS = BITS_PER_ELT_ >= 8 }; // The number of elements. enum { NUM_ELTS = NUM_ELTS_ }; // The size of element in bits. enum { BITS_PER_ELT = BITS_PER_ELT_ }; // The size of byte of a single register. enum { BYTES_PER_REG = 4 }; // The size in bits. enum { BITS_PER_REG = BYTES_PER_REG * 8 }; // The number of registers needed to store the fragment. enum { NUM_REGS = Div_up::VALUE }; // The size in bytes (as returned by sizeof(Fragment_base<>). enum { SIZE_IN_BYTES = NUM_REGS * BYTES_PER_REG }; // The alignment. enum { ALIGNMENT = ALIGNMENT_ > 0 ? ALIGNMENT_ : Min::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The type of the elements. typename Data_type_, // The number of elements. int NUM_ELTS_, // The alignment if you want to force a value -- use 0 otherwise. int ALIGNMENT_ = 0, // The base class. typename Base_ = Fragment_base_ > struct alignas(static_cast(Base_::ALIGNMENT)) Fragment : public Base_ { // The size of a load/store. enum { BYTES_PER_LOAD_STORE = Base_::NUM_REGS * sizeof(uint32_t) }; // Clear the fragment. Using PTX in that code seems to produce better SASS... inline __device__ void clear() { #pragma unroll for( int ii = 0; ii < Base_::NUM_REGS; ++ii ) { asm volatile("mov.u32 %0, 0; \n" : "=r"(this->reg(ii)) : ); } } // Immutable access to a register. inline __device__ const uint32_t& reg(int ii) const { return this->regs_[ii]; } // Mutable access to a register. inline __device__ uint32_t& reg(int ii) { return this->regs_[ii]; } uint32_t regs_[Base_::NUM_REGS]; // Immutable access to the elements. inline __device__ const Data_type_& elt(int ii) const { return reinterpret_cast(&this->regs_[0])[ii]; } // Mutable access to the elements. inline __device__ Data_type_& elt(int ii) { return reinterpret_cast(&this->regs_[0])[ii]; } // Immutable access to the elements with a cast. template< typename Cast_type > inline __device__ const Cast_type& elt_as(int ii) const { return reinterpret_cast(&this->regs_[0])[ii]; } // Mutable access to the elements. template< typename Cast_type > inline __device__ Cast_type& elt_as(int ii) { return reinterpret_cast(&this->regs_[0])[ii]; } // Add another fragment. inline __device__ void add(const Fragment &other) { #pragma unroll for( int ii = 0; ii < NUM_ELTS_; ++ii ) { this->elt(ii) += other.elt(ii); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Layout > struct Fragment_a : public Fragment { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Layout > struct Fragment_b : public Fragment { }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Fragment_accumulator : public Fragment { // The base class. using Base = Fragment; // Add two fragments. template< typename Other_fragment_ > inline __device__ void add(const Other_fragment_ &other) { for( int ii = 0; ii < Base::NUM_ELTS; ++ii ) { this->elt(ii) = this->elt(ii) + other.elt(ii); } } // Do the HMMA. template< typename Layout_a, typename Layout_b > inline __device__ void mma(const Fragment_a &a, const Fragment_b &b) { asm volatile( \ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \ " {%0, %1, %2, %3}, \n" \ " {%4, %5, %6, %7}, \n" \ " {%8, %9}, \n" \ " {%0, %1, %2, %3}; \n" \ : "+f"( elt(0)), "+f"( elt(1)), "+f"( elt(2)), "+f"( elt(3)) : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3)) , "r"(b.reg(0)), "r"(b.reg(1))); asm volatile( \ "mma.sync.aligned.m16n8k16.row.col.f32.f16.f16.f32 \n" \ " {%0, %1, %2, %3}, \n" \ " {%4, %5, %6, %7}, \n" \ " {%8, %9}, \n" \ " {%0, %1, %2, %3}; \n" \ : "+f"( elt(4)), "+f"( elt(5)), "+f"( elt(6)), "+f"( elt(7)) : "r"(a.reg(0)), "r"(a.reg(1)), "r"(a.reg(2)), "r"(a.reg(3)) , "r"(b.reg(2)), "r"(b.reg(3))); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Fragment, int M, int N > inline __device__ void clear(Fragment (&frag)[M][N]) { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ni = 0; ni < N; ++ni ) { frag[mi][ni].clear(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Accumulator_type, int WARPS_K > struct Clear_accumulator { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int WARPS_K > struct Clear_accumulator { template< typename Acc, int M, int N > static inline __device__ void apply(Acc (&acc)[M][N], bool = false) { fmha::clear(acc); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void gemm(Acc (&acc)[M][N], const A (&a)[M], const B (&b)[N]) { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ni = 0; ni < N; ++ni ) { acc[mi][ni].mma(a[mi], b[ni]); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The number of rows in the CTA tile. int M_, // The number of cols in the CTA tile. int N_, // The number of elements in the the K dimension of the GEMM loop. int K_, // The number of rows of warps. int WARPS_M_, // The number of cols of warps. int WARPS_N_, // The number of warps in the K dimension of the GEMM loop. int WARPS_K_> struct Cta_tile_ { enum { M = M_, N = N_, K = K_ }; // The number of warps. enum { WARPS_M = WARPS_M_, WARPS_N = WARPS_N_, WARPS_K = WARPS_K_ }; // The number of warps per CTA. enum { WARPS_PER_CTA = WARPS_M * WARPS_N * WARPS_K }; // The number of threads per warp. enum { THREADS_PER_WARP = 32 }; // The number of threads per CTA. enum { THREADS_PER_CTA = WARPS_PER_CTA * THREADS_PER_WARP }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Hmma_tile { // The number of elements computed with a single warp-MMA. enum { M_PER_MMA = 16, N_PER_MMA = 16, K_PER_MMA = 16 }; // The number of elements computed with a single CTA-MMA. enum { M_PER_MMA_PER_CTA = M_PER_MMA * Cta_tile::WARPS_M, N_PER_MMA_PER_CTA = N_PER_MMA * Cta_tile::WARPS_N, K_PER_MMA_PER_CTA = K_PER_MMA * Cta_tile::WARPS_K }; // The number of MMAs needed to compute the GEMM. enum { MMAS_M = Div_up::VALUE, MMAS_N = Div_up::VALUE, MMAS_K = Div_up::VALUE, }; // The number of elements computed per warp. enum { M_PER_WARP = MMAS_M * M_PER_MMA, N_PER_WARP = MMAS_N * N_PER_MMA, K_PER_WARP = MMAS_K * K_PER_MMA, }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// using A_type = uint16_t; using B_type = uint16_t; using C_type = uint16_t; using Accumulator_type = float; using Epilogue_type = float; constexpr int BITS_PER_ELEMENT_A = sizeof(A_type) * 8; constexpr int BITS_PER_ELEMENT_B = sizeof(B_type) * 8; constexpr int BITS_PER_ELEMENT_C = sizeof(C_type) * 8; //////////////////////////////////////////////////////////////////////////////////////////////////// template using Cta_tile_extd = Cta_tile_; //////////////////////////////////////////////////////////////////////////////////////////////////// template using Cta_tile_with_k_with_padding = Cta_tile_extd::VALUE, Cta_tile_::WARPS_M, Cta_tile_::WARPS_N, Cta_tile_::WARPS_K>; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/gmem_tile.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The number of bits per element. int BITS_PER_ELEMENT, // The number of rows of Q, K or V loaded by this tile. int ROWS, // The number of columns. int COLS, // The number of matrics. int NUM_MATS = 3 > struct Gmem_tile_qkv { // The size of each LDG. enum { BYTES_PER_LDG = 16 }; // The size of a row in bytes. enum { BYTES_PER_ROW = COLS * BITS_PER_ELEMENT / 8 }; // The number of threads to load a "row" of the matrix. enum { THREADS_PER_ROW = BYTES_PER_ROW / BYTES_PER_LDG }; // The number of "rows" loaded per LDG. enum { ROWS_PER_LDG = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // The number of LDGs needed to load a chunk of the Q matrix. enum { LDGS = fmha::Div_up::VALUE }; // Ctor. template< typename Params, typename BInfo > inline __device__ Gmem_tile_qkv(const Params ¶ms, int qkv_offset, const BInfo &binfo, int tidx) : params_qkv_stride_in_bytes_(params.qkv_stride_in_bytes) , actual_seqlen(binfo.actual_seqlen) , qkv_ptr_(reinterpret_cast(params.qkv_ptr)) { // Compute the position in the sequence (within the CTA for the moment). int row = tidx / THREADS_PER_ROW; // Compute the position of the thread in the row. int col = tidx % THREADS_PER_ROW; // Store the row as we need it to disable the loads. row_ = row; // The row offset in the batched GEMM. For each seq element, we store QKV in that order. int64_t row_offset = (int64_t)row * params.qkv_stride_in_bytes; // Add the block index. row_offset += (int64_t)((binfo.sum_s * NUM_MATS + qkv_offset) * binfo.h + binfo.bidh) * BYTES_PER_ROW; // Assemble the final pointer. qkv_ptr_ += row_offset + col * BYTES_PER_LDG; } // Store data to shared memory. template< typename Smem_tile > inline __device__ void commit(Smem_tile &smem_tile) { smem_tile.store(fetch_); } // Load data from memory. template< typename Smem_tile > inline __device__ void load(Smem_tile &smem_tile) { const void *ptrs[LDGS]; uint32_t preds[LDGS]; #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { ptrs[ii] = qkv_ptr_ + (int64_t)ii * ROWS_PER_LDG * params_qkv_stride_in_bytes_; preds[ii] = ((row_ + ii * ROWS_PER_LDG) < min(ROWS, actual_seqlen)); fetch_[ii] = make_uint4(0, 0, 0, 0); } // not packing predicates removes restrictions (e.g. FP16 384, 4 warps) Ldg_functor fct(fetch_, ptrs); #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { fct.load(ii, preds[ii]); } } // Store data to memory. inline __device__ void store(const uint4 (&data)[LDGS]) { #pragma unroll for( int ii = 0; ii < LDGS; ++ii ) { char *ptr = qkv_ptr_ + (int64_t)ii * ROWS_PER_LDG * params_qkv_stride_in_bytes_; if( (row_ + ii * ROWS_PER_LDG) < min(ROWS, actual_seqlen) ) { fmha::stg(ptr, data[ii]); } } } // Move the pointer to the next location. inline __device__ void move() { qkv_ptr_ += (int64_t)ROWS * params_qkv_stride_in_bytes_; actual_seqlen -= ROWS; } // The stride between rows for the QKV matrice. int64_t params_qkv_stride_in_bytes_; // The pointer. char *qkv_ptr_; // The fetch registers. uint4 fetch_[LDGS]; // Keep track of the row the thread is processing as we move the tile. int row_; // The length of the sequence loaded by that memory tile. int actual_seqlen; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile > struct Gmem_tile_o { // The mma tile. using Mma_tile = fmha::Hmma_tile; // The size of each element. enum { BYTES_PER_ELEMENT = 2 }; // The size of a row in bytes. enum { BYTES_PER_ROW = Cta_tile::N * BYTES_PER_ELEMENT }; // The number of threads to store a "row" of the matrix. enum { THREADS_PER_ROW = 16 }; // The size of each STG. enum { BYTES_PER_STG = BYTES_PER_ROW / THREADS_PER_ROW }; // The number of "rows" stored per iteration of the loop. The output of 1 MMA. enum { ROWS = Cta_tile::M }; // The number of "rows" stored per iteration of the loop. The output of 1 MMA. enum { ROWS_PER_LOOP = ROWS <= 64 ? ROWS : (int)Mma_tile::M_PER_MMA_PER_CTA }; // The number of outter loop for the stores. enum { LOOPS = ROWS / ROWS_PER_LOOP }; // The number of "rows" stored per STG. enum { ROWS_PER_STG = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Do we have to guard against partial writes/reads. enum { HAS_INCOMPLETE_STG = Cta_tile::M % ROWS_PER_STG != 0 }; // The number of STGs needed to store a chunk of the Q matrix. enum { STGS_PER_LOOP = fmha::Div_up::VALUE }; // The number of STGs needed to store a chunk of the Q matrix in total. enum { STGS = STGS_PER_LOOP * LOOPS }; // Ctor. template inline __device__ Gmem_tile_o(const Params ¶ms, const BInfo &binfo, int tidx) : params_o_stride_in_bytes_(params.o_stride_in_bytes) , actual_seqlen_(binfo.actual_seqlen) , o_ptr_(reinterpret_cast(params.o_ptr)) { // Compute the position in the sequence (within the CTA for the moment). int row = tidx / THREADS_PER_ROW; // Compute the position of the thread in the row. int col = tidx % THREADS_PER_ROW; // Store the row as we need it to disable loads. row_ = row; // The row offset in the batched GEMM. int64_t row_offset = (int64_t)row * params.o_stride_in_bytes + binfo.bidx * BYTES_PER_ROW; // Assemble the final pointer. o_ptr_ += row_offset + col * BYTES_PER_STG; // Is that thread active on the last STG? if( HAS_INCOMPLETE_STG ) { is_active_for_last_stg_ = row + (STGS - 1) * ROWS_PER_STG < Cta_tile::M; } } // Store data to global memory. inline __device__ void store(const uint4 (&src)[STGS_PER_LOOP], int mi) { #pragma unroll for( int ii = 0; ii < STGS_PER_LOOP; ++ii ) { int jj = mi * STGS_PER_LOOP + ii; if( this->row_ + jj * ROWS_PER_STG >= this->actual_seqlen_ ) { break; } float x = reinterpret_cast(src[ii].x); float y = reinterpret_cast(src[ii].y); float z = reinterpret_cast(src[ii].z); float w = reinterpret_cast(src[ii].w); uint2 out = float4_to_half4(x, y, z, w); if( !HAS_INCOMPLETE_STG || (jj < STGS - 1 || this->is_active_for_last_stg_) ) { fmha::stg(this->o_ptr_ + jj * ROWS_PER_STG * this->params_o_stride_in_bytes_, out); } } } // Move the pointer to the next location. inline __device__ void move() { row_ += ROWS; o_ptr_ += (int64_t)ROWS * params_o_stride_in_bytes_; } // The stride between rows for the QKV matrice. int64_t params_o_stride_in_bytes_; // The pointer. char *o_ptr_; // Is the thread active for the last STG? int is_active_for_last_stg_; // Keep track of the row to disable loads. int row_; // The length of the sequence loaded by that memory tile. int actual_seqlen_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, int BYTES_PER_ELEMENT > struct Gmem_tile_mma_sd { // The mma tile. using Mma_tile = fmha::Hmma_tile; // Each STG stores 8 elements. enum { BYTES_PER_STG = BYTES_PER_ELEMENT * 8 }; // The number of MMAs in the M dimension. enum { MMAS_M = Mma_tile::MMAS_M }; // The number of MMAs in the N dimension. enum { MMAS_N = Mma_tile::MMAS_N }; // The number of rows computed per MMA per thread block. enum { M_PER_MMA_PER_CTA = Mma_tile::M_PER_MMA_PER_CTA }; // The number of cols computed per MMA per thread block. enum { N_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA }; // The number of threads per block. enum { THREADS_PER_CTA = Cta_tile::THREADS_PER_CTA }; // The size of each row in bytes. I.e. how many bytes are stored per STG. enum { BYTES_PER_ROW = THREADS_PER_CTA * BYTES_PER_STG }; // The fixed sequence length. enum { SEQLEN = Cta_tile::N }; // The distance between two blocks (in bytes). enum { BLOCK_STRIDE_BYTES = SEQLEN * SEQLEN * BYTES_PER_ELEMENT }; // The distance between elements stored per loop (in bytes). enum { LOOP_STRIDE_BYTES = MMAS_M * MMAS_N * BYTES_PER_ROW }; // The type of elements stored per STG. using Type = typename fmha::Uint_from_size_in_bytes::Type; // Ctor. template inline __device__ Gmem_tile_mma_sd(void *ptr, const Params ¶ms, const int tidx) : ptr_(static_cast(ptr)) { // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The block index. size_t bidx = bidb * params.h + bidh; // Set store location for each thread at the beginning of the loop ptr_ += bidx * BLOCK_STRIDE_BYTES + tidx * BYTES_PER_STG; } // Store to global memory. inline __device__ void store(const Type &data, const int mi, const int ni) { size_t offset = (mi * MMAS_N + ni) * BYTES_PER_ROW; fmha::stg(ptr_ + offset, data); } // Load from global memory. inline __device__ void load(Type &data, const int mi, const int ni) { size_t offset = (mi * MMAS_N + ni) * BYTES_PER_ROW; fmha::ldg(data, ptr_ + offset); } // Move to the next tile. inline __device__ void move() { ptr_ += LOOP_STRIDE_BYTES; } // The pointer in global memory. char *ptr_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, typename Base = Gmem_tile_mma_sd > struct Gmem_tile_mma_s : public Base { // The number of mmas in the vertical dimension. enum { M = Base::MMAS_M }; // The number of mmas in the horizontal dimension. enum { N = Base::MMAS_N }; // The type of the vectors stored by each STG. using Type = typename Base::Type; // Ctor. template< typename Params > inline __device__ Gmem_tile_mma_s(void *ptr, const Params ¶ms, const int tidx) : Base(ptr, params, tidx) { } // Store to global memory. template inline __device__ void store(const float (&softmax)[2 * M][4 * N], const Mask &mask) { #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { float tmp00 = softmax[2 * mi + 0][4 * ni + 0]; float tmp01 = softmax[2 * mi + 0][4 * ni + 1]; float tmp02 = softmax[2 * mi + 0][4 * ni + 2]; float tmp03 = softmax[2 * mi + 0][4 * ni + 3]; float tmp10 = softmax[2 * mi + 1][4 * ni + 0]; float tmp11 = softmax[2 * mi + 1][4 * ni + 1]; float tmp12 = softmax[2 * mi + 1][4 * ni + 2]; float tmp13 = softmax[2 * mi + 1][4 * ni + 3]; uint4 dst; dst.x = fmha::float2_to_half2(tmp00, tmp01); dst.y = fmha::float2_to_half2(tmp02, tmp03); dst.z = fmha::float2_to_half2(tmp10, tmp11); dst.w = fmha::float2_to_half2(tmp12, tmp13); if( mask.is_valid(mi, ni, 0, 0) ) { Base::store(dst, mi, ni); } } } } // Load from global memory. template inline __device__ void load(uint4 (®s)[M][N], const Mask &mask) { #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { regs[mi][ni] = make_uint4(0, 0, 0, 0); if( mask.is_valid(mi, ni, 0, 0) ) { Base::load(regs[mi][ni], mi, ni); } } } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The base class. typename Base = fmha::Gmem_tile_qkv > struct Gmem_tile_dout : public Base { // Ctor. template inline __device__ Gmem_tile_dout(const Params ¶ms, const BInfo &binfo, int tidx) : Base(params, 0, binfo, tidx) { this->qkv_ptr_ = reinterpret_cast(params.o_ptr); this->params_qkv_stride_in_bytes_ = params.o_stride_in_bytes; // needed for move // Compute the position of the thread in the row. int col = tidx % Base::THREADS_PER_ROW; // The row offset in the batched GEMM. For each seq element, we store O in that order. int64_t row_offset = (int64_t)this->row_ * params.o_stride_in_bytes + binfo.bidx * Base::BYTES_PER_ROW; // Assemble the final pointer. this->qkv_ptr_ += row_offset + col * Base::BYTES_PER_LDG; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Cta_tile, typename Base = fmha::Gmem_tile_o > struct Gmem_tile_dq : public Base { // Ctor. template inline __device__ Gmem_tile_dq(const Params ¶ms, const BInfo &binfo, int tidx) : Base(params, binfo, tidx) { this->o_ptr_ = reinterpret_cast(params.dqkv_ptr); this->params_o_stride_in_bytes_ = params.qkv_stride_in_bytes; // needed for move // Compute the position of the thread in the row. int col = tidx % Base::THREADS_PER_ROW; // The row offset in the batched GEMM. For each seq element, we store O in that order. int64_t row_offset = (int64_t)this->row_ * params.qkv_stride_in_bytes + (binfo.sum_s * 3 * binfo.h + binfo.bidh) * Base::BYTES_PER_ROW; // Assemble the final pointer. this->o_ptr_ += row_offset + col * Base::BYTES_PER_STG; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/kernel_traits.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once //////////////////////////////////////////////////////////////////////////////////////////////////// template struct FMHA_kernel_traits { // The CTA description for the 1st GEMM. using Cta_tile_p = fmha::Cta_tile_extd; // The CTA description for the 2nd GEMM. using Cta_tile_o = fmha::Cta_tile_extd; // Do we use one buffer for K and V. enum { SHARE_SMEM_FOR_K_AND_V = (FLAGS & 0x8u) != 0u }; // The global memory tile to load Q. using Gmem_tile_q = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle Q. using Smem_tile_q = fmha::Smem_tile_a; // The global memory tile to load K. using Gmem_tile_k = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle K. using Smem_tile_k = fmha::Smem_tile_b; // The global memory tile to load V. using Gmem_tile_v = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle V. using Smem_tile_v = fmha::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = fmha::Gmem_tile_o; // The shared memory tile for O. using Smem_tile_o = fmha::Smem_tile_o; // The global memory tile to load/store S. using Gmem_tile_s = fmha::Gmem_tile_mma_s; // The shared memory tile to transpose S. using Smem_tile_st = fmha::Smem_tile_mma_transposed; using Gmem_tile_do = fmha::Gmem_tile_dout; // Make sure the number of threads match. static_assert((int)Gmem_tile_o::THREADS_PER_ROW == (int)Smem_tile_o::THREADS_PER_ROW, ""); // The number of threads. enum { THREADS = Cta_tile_p::THREADS_PER_CTA }; // Make sure the number of threads matches both CTAs. static_assert((int)THREADS == (int)Cta_tile_o::THREADS_PER_CTA, ""); // The amount of shared memory needed to load Q and K. enum { BYTES_PER_SMEM_QK = Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE }; // The extra amount of shared memory needed to load V. enum { BYTES_PER_SMEM_V = SHARE_SMEM_FOR_K_AND_V ? 0u : Smem_tile_v::BYTES_PER_TILE }; // The amount of shared memory needed for Q, K and V.. enum { BYTES_PER_SMEM_QKV = BYTES_PER_SMEM_QK + BYTES_PER_SMEM_V }; // The amount of shared memory needed to load Q and store O. enum { BYTES_PER_SMEM_QO = Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE }; // The amount of shared memory needed for Q, K, V and O. enum { BYTES_PER_SMEM = fmha::Max::VALUE }; // Make sure we have enough shared memory. static_assert(Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE <= BYTES_PER_SMEM, ""); }; //////////////////////////////////////////////////////////////////////////////////////////////////// ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/mask.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { template struct Mask { using Mma_tile = fmha::Hmma_tile; template __device__ Mask(const Params ¶ms, const BInfo &blockInfo, int tidx) { actual_seqlen = blockInfo.actual_seqlen; const int warp = tidx / Cta_tile::THREADS_PER_WARP; const int lane = tidx % Cta_tile::THREADS_PER_WARP; static_assert(Cta_tile::WARPS_K == 1, ""); // find the warp in the Cta tile const int warp_n = (warp / Cta_tile::WARPS_M); const int warp_m = (warp % Cta_tile::WARPS_M); // decompose warp into 8x4 tile const int quad = lane / 4; const int tid = (lane % 4) * 2; row = warp_m * 16 + quad; col = warp_n * 16 + tid; } inline __device__ bool is_valid(const int mi, const int ni, const int ii, const int jj) const { // ii and jj iterate over the 2x4 fragment const bool col_valid = (ni * Mma_tile::N_PER_MMA_PER_CTA + col + (jj & 2) * 4 + (jj & 1)) < actual_seqlen; //&& (row + mi * Mma_tile::M_PER_MMA_PER_CTA + ii * 8) < actual_seqlen; return col_valid; // return row_valid && col_valid; } inline __device__ void load(int it) { row_offset = it * Cta_tile::M + row; } int row_offset; int row; int col; int actual_seqlen; }; } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/smem_tile.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The description of the tile computed by this CTA. typename Cta_tile, // The number of rows in the 2D shared memory buffer. int M_, // The number of cols. int N_, // The size in bits of each element. int BITS_PER_ELEMENT_, // The number of bytes per STS. int BYTES_PER_STS_ = 16, // The number of buffers. (Used in multistage and double buffer cases.) int BUFFERS_PER_TILE_ = 1, // Do we enable the fast path for LDS.128 and friends. int ENABLE_LDS_FAST_PATH_ = 0, // The number of rows that are used for the XOR swizzling to allow fast STS/LDS. int ROWS_PER_XOR_PATTERN_ = 8, // The number of cols that are used for the XOR swizzling to allow fast STS/LDS. int COLS_PER_XOR_PATTERN_ = 1, // Use or not predicates bool USE_PREDICATES_ = true > struct Smem_tile_without_skews { // The size in bits of each element. enum { BITS_PER_ELEMENT = BITS_PER_ELEMENT_ }; // The size in bytes of a single STS. enum { BYTES_PER_STS = BYTES_PER_STS_ }; // The number of elements per STS. enum { ELEMENTS_PER_STS = BYTES_PER_STS * 8 / BITS_PER_ELEMENT }; // To support arbitrary N, we pad some values to a power-of-2. enum { N_WITH_PADDING = Next_power_of_two::VALUE }; // The number of bytes per row without packing of rows. enum { BYTES_PER_ROW_BEFORE_PACKING = N_WITH_PADDING * BITS_PER_ELEMENT / 8 }; // The number of bytes per row -- we want at least 128B per row. enum { BYTES_PER_ROW = Max::VALUE }; // The number of rows in shared memory (two rows may be packed into a single one). enum { ROWS = M_ * BYTES_PER_ROW_BEFORE_PACKING / BYTES_PER_ROW }; // The number of threads per row. enum { THREADS_PER_ROW_UNBOUNDED = BYTES_PER_ROW / BYTES_PER_STS }; // The number of threads per row. enum { THREADS_PER_ROW = Min::VALUE }; // The number of STS per row. enum { STS_PER_ROW = BYTES_PER_ROW / THREADS_PER_ROW / BYTES_PER_STS }; // It must be at least one. static_assert(STS_PER_ROW >= 1, ""); // The number of rows written with a single STS. enum { ROWS_PER_STS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Make sure we write to at least one row per STS. Thanks Dr. Obvious ;) static_assert(ROWS_PER_STS >= 1, ""); // The number of STS needed to store all rows. enum { STS_PER_COL = Div_up::VALUE }; // The number of STS in total. enum { STS = STS_PER_COL * STS_PER_ROW }; // The size of one buffer in bytes in shared memory. enum { BYTES_PER_BUFFER = STS * BYTES_PER_STS * Cta_tile::THREADS_PER_CTA }; // The number of buffers. enum { BUFFERS_PER_TILE = BUFFERS_PER_TILE_ }; // The size in bytes of total buffers. enum { BYTES_PER_TILE = BYTES_PER_BUFFER * BUFFERS_PER_TILE }; // The boundary for smem_read_offset and smem_write_offset increment. enum { BYTES_PER_TILE_INC_BOUNDARY = BYTES_PER_TILE - BYTES_PER_BUFFER }; // Do we enable the LDS.128 fast path? enum { ENABLE_LDS_FAST_PATH = ENABLE_LDS_FAST_PATH_ }; static_assert(ENABLE_LDS_FAST_PATH == 0); // The number of rows that are used for the XOR swizzling to allow fast STS/LDS. enum { ROWS_PER_XOR_PATTERN = ROWS_PER_XOR_PATTERN_ }; // The number of cols that are used for the XOR swizzling to allow fast STS/LDS. enum { COLS_PER_XOR_PATTERN = COLS_PER_XOR_PATTERN_ * 16 / BYTES_PER_STS }; // Use or not predicates enum { USE_PREDICATES = USE_PREDICATES_ }; // The type of elements that are stored in shared memory by each thread. using Store_type = typename Uint_from_size_in_bytes::Type; // Ctor. inline __device__ Smem_tile_without_skews(void *smem, int tidx) : smem_(__nvvm_get_smem_pointer(smem)) { // The row written by a thread. See doc/mma_smem_layout.xlsx. int smem_write_row = tidx / THREADS_PER_ROW; // The XOR pattern. int smem_write_xor = smem_write_row % ROWS_PER_XOR_PATTERN * COLS_PER_XOR_PATTERN; // Compute the column and apply the XOR pattern. int smem_write_col = (tidx % THREADS_PER_ROW) ^ smem_write_xor; // The offset. this->smem_write_offset_ = smem_write_row*BYTES_PER_ROW + smem_write_col*BYTES_PER_STS; // TODO: Why not merge it with the read offset? this->smem_read_buffer_ = __shfl_sync(0xffffffff, 0, 0); this->smem_write_buffer_ = __shfl_sync(0xffffffff, 0, 0); } // Compute the store pointers. template< int N > inline __device__ void compute_store_pointers(uint32_t (&ptrs)[N]) { #pragma unroll for( int ii = 0; ii < N; ++ii ) { // Decompose the STS into row/col. int row = ii / STS_PER_ROW; int col = ii % STS_PER_ROW; // Assemble the offset. int offset = smem_write_offset_ + row*ROWS_PER_STS*BYTES_PER_ROW; // Take the column into account. if( STS_PER_ROW > 1 ) { offset += col*THREADS_PER_ROW*BYTES_PER_STS; } // Apply the XOR pattern if needed. if( ROWS_PER_STS < ROWS_PER_XOR_PATTERN ) { const int m = row * ROWS_PER_STS % ROWS_PER_XOR_PATTERN; offset ^= m * COLS_PER_XOR_PATTERN * BYTES_PER_STS; } // Assemble the final pointer :) ptrs[ii] = smem_ + offset + smem_write_buffer_; } } inline __device__ void debug_reset() { for( int buffer = 0; buffer < BYTES_PER_TILE; buffer += BYTES_PER_BUFFER) { for( int row = 0; row < ROWS; ++row ) { for( int col = 0; col < BYTES_PER_ROW; col += 4 ) { if( threadIdx.x == 0 ) { uint32_t val = 0x0; sts(val, smem_ + row*BYTES_PER_ROW + col + buffer); } } } } } // Print the content of the tile (only for debug ;)). inline __device__ void debug_print() const { for( int buffer = 0; buffer < BYTES_PER_TILE; buffer += BYTES_PER_BUFFER) { for( int row = 0; row < ROWS; ++row ) { for( int col = 0; col < BYTES_PER_ROW; col += 4 ) { if( threadIdx.x == 0 ) { uint32_t val; lds(val, smem_ + row*BYTES_PER_ROW + col + buffer); printf("block=(x=%2d, y=%2d, z=%2d) (smem_=%2d, buffer=%2d, row=%2d, byte=%4d)=0x%08x\n", blockIdx.x, blockIdx.y, blockIdx.z, smem_, buffer, row, col, val); } } } } } // Move the read offset to next buffer. inline __device__ void move_to_next_read_buffer() { if( BUFFERS_PER_TILE > 1 && smem_read_buffer_ >= BYTES_PER_TILE_INC_BOUNDARY ) { this->smem_read_buffer_ -= BYTES_PER_TILE_INC_BOUNDARY; } else if( BUFFERS_PER_TILE > 1 ) { this->smem_read_buffer_ += BYTES_PER_BUFFER; } } // Move the read offset to next buffer. TODO: Remove this member function!!! inline __device__ void move_next_read_buffer() { this->move_to_next_read_buffer(); } // Move the read offset to next N buffer (circular-buffer). inline __device__ void move_to_next_read_buffer(int N) { if( BUFFERS_PER_TILE > 1 ) { this->smem_read_buffer_ += N * BYTES_PER_BUFFER; this->smem_read_buffer_ -= smem_read_buffer_ >= BYTES_PER_TILE ? BYTES_PER_TILE : 0; } } // Move the read offset to next N buffer (circular-buffer). TODO: Remove this member function!!! inline __device__ void move_next_read_buffer(int N) { this->move_to_next_read_buffer(N); } // Move the write offset to next buffer. inline __device__ void move_to_next_write_buffer() { if( BUFFERS_PER_TILE > 1 && smem_write_buffer_ >= BYTES_PER_TILE_INC_BOUNDARY ) { this->smem_write_buffer_ -= BYTES_PER_TILE_INC_BOUNDARY; } else if( BUFFERS_PER_TILE > 1 ) { this->smem_write_buffer_ += BYTES_PER_BUFFER; } } // Move the write offset to next buffer. TODO: Remove that member function! inline __device__ void move_next_write_buffer() { this->move_to_next_write_buffer(); } // Move the read offset. inline __device__ void move_read_offset(int delta) { this->smem_read_offset_ += delta; } // Move the write offset. inline __device__ void move_write_offset(int delta) { this->smem_write_offset_ += delta; } // Store to the tile in shared memory. template< int N > inline __device__ void store(const Store_type (&data)[N], uint64_t = 0) { uint32_t smem_ptrs[N]; this->compute_store_pointers(smem_ptrs); sts(smem_ptrs, data); } // Store to the tile in shared memory. template< int N, int M > inline __device__ void store(const Store_type (&data)[N], uint32_t (&preds)[M], uint64_t = 0) { uint32_t smem_ptrs[N]; this->compute_store_pointers(smem_ptrs); sts(smem_ptrs, data, preds); } // Store to the tile in shared memory. template< int N > inline __device__ void store(const Store_type (&data)[N], uint32_t preds, uint64_t = 0) { this->store(data, preds); } // Store to the tile in shared memory. template< int N > inline __device__ void store(const void* (&gmem_ptrs)[N], uint32_t preds, uint64_t = 0) { uint32_t tmp[1] = { preds }; this->store(gmem_ptrs, tmp); } // The shared memory pointer. uint32_t smem_; // The read offset. Reserve 4 offsets if needed. int smem_read_offset_; // The write offset. int smem_write_offset_; // The buffer base offset for read. int smem_read_buffer_; // The buffer base offset for write. int smem_write_buffer_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The layout of the tile. typename Layout, // The size of the STS. int BYTES_PER_STS = 16, // The number of buffers per tile. int BUFFERS_PER_TILE = 1, // Use or not predicates bool USE_PREDICATES = true > struct Smem_tile_a { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K, int MMAS_K_WITH_PADDING > struct Compute_reset_mask { // The potential mask. enum { HALF = MMAS_K_WITH_PADDING / 2 }; // The remainder. enum { MOD = MMAS_K % HALF }; // The final value. enum { VALUE = (MMAS_K == MOD ? 0 : HALF) | Compute_reset_mask::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K_WITH_PADDING > struct Compute_reset_mask<0, MMAS_K_WITH_PADDING> { enum { VALUE = 0 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int MMAS_K > struct Compute_reset_mask { enum { VALUE = MMAS_K - 1 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_a { // The size in bits. enum { N_IN_BITS = N * fmha::BITS_PER_ELEMENT_A }; // The number of rows. enum { VALUE = N_IN_BITS <= 256 ? 2 : (N_IN_BITS <= 512 ? 4 : 8) }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_row_a : public Rows_per_xor_pattern_a { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_row_a::VALUE > struct Smem_tile_row_a : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_a; // When we use padding to reach a power of two, special care has to be taken. using Cta_tile_with_padding = Cta_tile_with_k_with_padding; // The number of MMAs. using Mma_tile_with_padding = fmha::Hmma_tile; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // Ctor. inline __device__ Smem_tile_row_a(void *smem, int tidx) : Base(smem, tidx) { // For documentation on the layout, see doc/mma_smem_layout.xlsx. // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(WARPS_M == 1); static_assert(WARPS_N == 4 || WARPS_N == 8); static_assert(WARPS_K == 1); static_assert(Base::ROWS_PER_XOR_PATTERN == 8); // The row and column read by the thread. int smem_read_row = (tidx & 0x0f); int smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Load from shared memory. inline __device__ void load(Fragment (&a)[Mma_tile::MMAS_M], int ki) { #pragma unroll for( int mi = 0; mi < Mma_tile::MMAS_M; ++mi ) { // Jump by as many matrix rows as needed (a row in smem may pack multiple matrix rows). int offset = mi * Mma_tile::M_PER_MMA_PER_CTA * Base::BYTES_PER_ROW_BEFORE_PACKING; // Load using LDSM.M88.4. uint4 tmp; ldsm(tmp, this->smem_ + this->smem_read_offset_ + this->smem_read_buffer_ + offset); // Store the value into the fragment. a[mi].reg(0) = tmp.x; a[mi].reg(1) = tmp.y; a[mi].reg(2) = tmp.z; a[mi].reg(3) = tmp.w; } // Move the offset to the next possition. See doc/mma_smem_layout.xlsx. static_assert(Mma_tile_with_padding::MMAS_K < 64, "Not implemented"); if( Mma_tile_with_padding::MMAS_K >= 32 && ki % 16 == 15 ) { this->smem_read_offset_ ^= 31 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 16 && ki % 8 == 7 ) { this->smem_read_offset_ ^= 15 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 8 && ki % 4 == 3 ) { this->smem_read_offset_ ^= 7 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 4 && ki % 2 == 1 ) { this->smem_read_offset_ ^= 3 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= 1 * BYTES_PER_LDS * 2; } } // Reset the read offset. inline __device__ void reset_read_offset() { // The number of MMAs in the K dimension. enum { MMAS_K = Mma_tile::MMAS_K }; // The number of MMAs in the K dimension when we include padding. enum { MMAS_K_WITH_PADDING = Mma_tile_with_padding::MMAS_K }; // Assemble the mask. enum { MASK = Compute_reset_mask::VALUE }; // Reset the read offset. this->smem_read_offset_ ^= MASK * BYTES_PER_LDS * 2; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_a : public Smem_tile_row_a { // The base class. using Base = Smem_tile_row_a; // Ctor. inline __device__ Smem_tile_a(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The layout of the tile. typename Layout, // The size of the STS. int BYTES_PER_STS = 16, // The number of buffers per tile. int BUFFERS_PER_TILE = 1, // Use or not predicates bool USE_PREDICATES = true > struct Smem_tile_b { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_b { // The size in bits. enum { N_IN_BITS = N * fmha::BITS_PER_ELEMENT_B }; // The number of rows. enum { VALUE = N_IN_BITS <= 256 ? 2 : (N_IN_BITS <= 512 ? 4 : 8) }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_col_b : public Rows_per_xor_pattern_b { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_col_b::VALUE > struct Smem_tile_col_b : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_b< Col>; // When we use padding to reach a power of two, special care has to be taken. using Cta_tile_with_padding = Cta_tile_with_k_with_padding< Cta_tile>; // The number of MMAs. using Mma_tile_with_padding = fmha::Hmma_tile; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // The number of STS per thread enum { STS_PER_THREAD_ = Base::ROWS * Base::THREADS_PER_ROW / Cta_tile::THREADS_PER_CTA }; // The number of STS per thread must be at least 1. enum { STS_PER_THREAD = Max<1, STS_PER_THREAD_>::VALUE }; // Ctor. inline __device__ Smem_tile_col_b(void *smem, int tidx) : Base(smem, tidx) { // For documentation on the layout, see doc/mma_smem_layout.xlsx. // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(Base::ROWS_PER_XOR_PATTERN == 8); static_assert(WARPS_M == 1); static_assert(WARPS_N == 4 || WARPS_N == 8); static_assert(WARPS_K == 1); // The masks to select the warps. const int WARP_MASK_N = Warp_masks::N; // The divisor for the warps. const int WARP_DIV_N = WARPS_M * 1 * Cta_tile::THREADS_PER_WARP; // The row and column read by the thread. int smem_read_row = (tidx & WARP_MASK_N) / WARP_DIV_N * Mma_tile::N_PER_MMA + (tidx & 0x07) + (tidx & 0x10) / 2; int smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & 0x08) / 8; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Jump by as many matrix rows as needed (a row in smem may pack multiple matrix rows). int offset = ni * Mma_tile::N_PER_MMA_PER_CTA * Base::BYTES_PER_ROW_BEFORE_PACKING; // Load using LDSM.M88.4. uint4 tmp; ldsm(tmp, this->smem_ + this->smem_read_offset_ + this->smem_read_buffer_ + offset); // Store the value into the fragment. b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; } // Move the offset to the next possition. See doc/mma_smem_layout.xlsx. static_assert(Mma_tile_with_padding::MMAS_K < 64, "Not implemented"); if( Mma_tile_with_padding::MMAS_K >= 32 && ki % 16 == 15 ) { this->smem_read_offset_ ^= 31 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 16 && ki % 8 == 7 ) { this->smem_read_offset_ ^= 15 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 8 && ki % 4 == 3 ) { this->smem_read_offset_ ^= 7 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 4 && ki % 2 == 1 ) { this->smem_read_offset_ ^= 3 * BYTES_PER_LDS * 2; } else if( Mma_tile_with_padding::MMAS_K >= 2 ) { this->smem_read_offset_ ^= 1 * BYTES_PER_LDS * 2; } } // Reset the read offset. inline __device__ void reset_read_offset() { // The number of MMAs in the K dimension. enum { MMAS_K = Mma_tile::MMAS_K }; // The number of MMAs in the K dimension when we include padding. enum { MMAS_K_WITH_PADDING = Mma_tile_with_padding::MMAS_K }; // Assemble the mask. enum { MASK = Compute_reset_mask::VALUE }; // Reset the read offset. this->smem_read_offset_ ^= MASK * BYTES_PER_LDS * 2; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_b< Cta_tile, Col, BYTES_PER_STS, BUFFERS_PER_TILE > : public Smem_tile_col_b { // The base class. using Base = Smem_tile_col_b< Cta_tile, BYTES_PER_STS, BUFFERS_PER_TILE>; // Ctor. inline __device__ Smem_tile_b(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > struct Rows_per_xor_pattern_row_b : public Rows_per_xor_pattern_b< N> { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE, // How many rows to use for the XOR pattern to avoid bank conflicts? int ROWS_PER_XOR_PATTERN_ = Rows_per_xor_pattern_row_b::VALUE, // How many cols to use for the XOR pattern to avoid bank conflicts? int COLS_PER_XOR_PATTERN_ = 1 > struct Smem_tile_row_b : public Smem_tile_without_skews { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The base class. using Base = Smem_tile_without_skews; // The fragment. using Fragment = Fragment_b; // Can we use LDSM? No if the data type is 32-bit large. enum { USE_LDSMT = fmha::BITS_PER_ELEMENT_B == 16 }; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = USE_LDSMT ? 16 : 4 }; // The number of elements per LDS. enum { ELEMENTS_PER_LDS = BYTES_PER_LDS * 8 / fmha::BITS_PER_ELEMENT_B }; // The number of STS per thread enum { STS_PER_THREAD_ = Base::ROWS * Base::THREADS_PER_ROW / Cta_tile::THREADS_PER_CTA }; // The number of STS per thread must be at least 1. enum { STS_PER_THREAD = Max<1, STS_PER_THREAD_>::VALUE }; // Ctor. inline __device__ Smem_tile_row_b(void *smem, int tidx) : Base(smem, tidx) { // The number of warps. const int WARPS_M = Cta_tile::WARPS_M; const int WARPS_N = Cta_tile::WARPS_N; const int WARPS_K = Cta_tile::WARPS_K; static_assert(WARPS_K == 1); static_assert(WARPS_M == 4 || WARPS_M == 8); static_assert(WARPS_N == 1); // The masks to select the warps. const int WARP_MASK_N = Warp_masks::N; const int WARP_MASK_K = Warp_masks::K; // The divisor for the warps. const int WARP_DIV_N = WARPS_M * 1 * Cta_tile::THREADS_PER_WARP; const int WARP_DIV_K = WARPS_M * WARPS_N * Cta_tile::THREADS_PER_WARP; // The row/col read by the thread. int smem_read_row, smem_read_col; static_assert(USE_LDSMT); static_assert(Base::ROWS_PER_XOR_PATTERN == 8); smem_read_row = (tidx & WARP_MASK_K) / WARP_DIV_K * Mma_tile::MMAS_K * 16 + (tidx & 0x07) + (tidx & 0x08); smem_read_col = (tidx & 0x07); smem_read_col ^= (tidx & WARP_MASK_N) / WARP_DIV_N * 2 + (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = smem_read_row*Base::BYTES_PER_ROW + smem_read_col*BYTES_PER_LDS; // Fill zeroes for group conv } // Rewind smem_read_offset for last LDS phase in main loop. inline __device__ void reverse_smem_read_offset(int ki = 0) { // The size of each element in bits. const int BITS_PER_ELT = fmha::BITS_PER_ELEMENT_B; // The size in bytes of the data needed to compute an MMA per CTA. const int BYTES_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA * BITS_PER_ELT / 8; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Undo the pointer increment for the next ni. // Should match the load function below for ki = 0. if( BYTES_PER_MMA_PER_CTA >= 128 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } else if( BYTES_PER_MMA_PER_CTA == 64 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Reset smem_read_offset for odd MMAS_N > 1 (npo2 kernels) if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 && Mma_tile::MMAS_N % 2 == 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { // The size of each element in bits. const int BITS_PER_ELT = fmha::BITS_PER_ELEMENT_B; // The size in bytes of the data needed to compute an MMA per CTA. const int BYTES_PER_MMA_PER_CTA = Mma_tile::N_PER_MMA_PER_CTA * BITS_PER_ELT / 8; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Prepare the offset. int offset = ki * Base::ROWS_PER_XOR_PATTERN * 2 * Base::BYTES_PER_ROW; if ( BYTES_PER_MMA_PER_CTA == 32 ) { offset += this->smem_read_offset_; } else if ( BYTES_PER_MMA_PER_CTA == 64 ) { offset += this->smem_read_offset_ + (ni/2) * BYTES_PER_MMA_PER_CTA * 2; } else { offset += this->smem_read_offset_ + (ni ) * BYTES_PER_MMA_PER_CTA; } // Load the data using LDSM.MT88.2. uint32_t ptr = this->smem_ + this->smem_read_buffer_ + offset; uint4 tmp; if( USE_LDSMT ) { ldsmt(tmp, ptr); } else { lds(tmp.x, (ptr ) + 0*Base::BYTES_PER_ROW); lds(tmp.y, (ptr ) + 4*Base::BYTES_PER_ROW); lds(tmp.z, (ptr ^ 32) + 0*Base::BYTES_PER_ROW); lds(tmp.w, (ptr ^ 32) + 4*Base::BYTES_PER_ROW); } // Store those values in the fragment. b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; // Move the pointer for the next ni. I expect the compiler to not recompute those. if( BYTES_PER_MMA_PER_CTA >= 128 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } else if( BYTES_PER_MMA_PER_CTA == 64 ) { // Nothing to do! } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else if( BYTES_PER_MMA_PER_CTA == 32 && Mma_tile::MMAS_N == 2 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * 2; } } // Reset smem_read_offset for odd MMAS_N > 1 (npo2 kernels) if( BYTES_PER_MMA_PER_CTA == 64 && Mma_tile::MMAS_N > 1 && Mma_tile::MMAS_N % 2 == 1 ) { this->smem_read_offset_ ^= BYTES_PER_MMA_PER_CTA; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< // The dimensions of the tile computed by the CTA. typename Cta_tile, // The size of the STS. int BYTES_PER_STS, // The number of buffers per tile. int BUFFERS_PER_TILE > struct Smem_tile_b : public Smem_tile_row_b { // The base class. using Base = Smem_tile_row_b; // Ctor. inline __device__ Smem_tile_b(void *smem, int tidx) : Base(smem, tidx) { } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_v : public fmha::Smem_tile_without_skews { // The base class. using Base = Smem_tile_without_skews; // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The fragment. using Fragment = Fragment_b< fmha::Col>; // The size of a single LDS in bytes. enum { BYTES_PER_LDS = 16 }; // Ctor. inline __device__ Smem_tile_v(void *smem, int tidx) : Base(smem, tidx) { // The row/col read by the thread. int read_row, read_col; static_assert(Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 1 && (Cta_tile::WARPS_K == 4 || Cta_tile::WARPS_K == 8)); read_row = (tidx & 0xe0) / 2 + (tidx & 0x0f); read_col = (tidx & 0x07); read_col ^= (tidx & 0x10) / 16; // The shared memory offset. this->smem_read_offset_ = read_row * Base::BYTES_PER_ROW + read_col * BYTES_PER_LDS; } // Load from shared memory. inline __device__ void load(Fragment (&b)[Mma_tile::MMAS_N], int ki) { #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // Jump by 16 * #warps row. int row = ki * 16 * Cta_tile::WARPS_K; // Load the data using LDSM.MT88.2. uint4 tmp; fmha::ldsmt(tmp, this->smem_ + this->smem_read_offset_ + row * Base::BYTES_PER_ROW); b[ni].reg(0) = tmp.x; b[ni].reg(1) = tmp.y; b[ni].reg(2) = tmp.z; b[ni].reg(3) = tmp.w; // Move the pointer for the next ni. I expect the compiler to not recompute those. if( Mma_tile::MMAS_N == 4 ) { this->smem_read_offset_ ^= BYTES_PER_LDS * (ni % 2 == 0 ? 2 : 6); } else { assert(false); // Not implemented! } } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_o { // The MMA tile. using Mma_tile = fmha::Hmma_tile; // The accumulators. using Accumulator = fmha::Fragment_accumulator; // The accumulators. using Data_type = typename Accumulator::Data_type; // The size of each element. enum { BYTES_PER_ELEMENT = sizeof(Data_type) }; // The size of each STS. enum { BYTES_PER_STS = 8 }; // The size of each row in shared memory. enum { BYTES_PER_ROW = Cta_tile::N * Cta_tile::WARPS_K * BYTES_PER_ELEMENT }; // The size of each LDS. enum { BYTES_PER_LDS = 16 }; enum { THREADS_PER_ROW = 16 }; // The number of rows. enum { ROWS = Cta_tile::M }; // The number of "rows" to process per loop iteration (in the "epilogue"). enum { ROWS_PER_LOOP = ROWS <= 64 ? ROWS : (int)Mma_tile::M_PER_MMA_PER_CTA }; // The number of outer loops. enum { LOOPS = ROWS / ROWS_PER_LOOP }; // Make sure it matches our expectations. static_assert(LOOPS == 1 || LOOPS == (int)Mma_tile::MMAS_M, ""); // The number of rows loaded per LDS. enum { ROWS_PER_LDS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; // Do we have to guard against partial writes/reads. enum { HAS_INCOMPLETE_LDS = ROWS_PER_LOOP % ROWS_PER_LDS != 0 }; // The total number of LDS per loop. enum { LDS_PER_LOOP = fmha::Div_up::VALUE }; // The amount of shared memory. enum { BYTES_PER_TILE = ROWS_PER_LOOP * BYTES_PER_ROW }; // The write pointer. uint32_t smem_write_, smem_read_; // Is the thread active for the last LDS of the series? int is_active_for_last_lds_; static_assert(BYTES_PER_ROW == 64 * 4 * Cta_tile::WARPS_K); static_assert(LOOPS == 1 || LOOPS == (int)Mma_tile::MMAS_M, ""); // Ctor. inline __device__ Smem_tile_o(void *smem, int tidx) { // Get a 32-bit value for the shared memory address. uint32_t smem_ = __nvvm_get_smem_pointer(smem); static_assert(Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 1 && (Cta_tile::WARPS_K == 4 || Cta_tile::WARPS_K == 8)); int write_row = (tidx & 0x1c) / 4; int write_col = (tidx); // Assemble the write pointer. smem_write_ = smem_ + write_row * BYTES_PER_ROW + write_col * BYTES_PER_STS; // The element read by each thread. int read_row = tidx / THREADS_PER_ROW; int read_col = tidx % THREADS_PER_ROW; // Take the XOR pattern into account for the column. read_col ^= 2 * (read_row & 0x7); // Assemble the read pointer. this->smem_read_ = smem_ + read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; // Is that thread active on the last LDS? if( HAS_INCOMPLETE_LDS ) { this->is_active_for_last_lds_ = read_row + (LDS_PER_LOOP - 1) * ROWS_PER_LDS < Cta_tile::M; } } // Load the output fragments. inline __device__ void load(uint4 (&out)[LDS_PER_LOOP]) const { #pragma unroll for( int ii = 0; ii < LDS_PER_LOOP; ++ii ) { // Load the elements before the reduction (split-K). uint4 tmp[Cta_tile::WARPS_K]; #pragma unroll for( int jj = 0; jj < Cta_tile::WARPS_K; ++jj ) { int imm = ii * ROWS_PER_LDS * BYTES_PER_ROW + jj * Cta_tile::N * BYTES_PER_ELEMENT; if( !HAS_INCOMPLETE_LDS || (ii < LDS_PER_LOOP - 1 || this->is_active_for_last_lds_) ) { fmha::lds(tmp[jj], this->smem_read_ + imm); } } // Perform the reduction. out[ii] = tmp[0]; #pragma unroll for( int jj = 1; jj < Cta_tile::WARPS_K; ++jj ) { out[ii] = fmha::fadd4(out[ii], tmp[jj]); } } } // Store the accumulators. template inline __device__ void store(const Accumulator (&acc)[M][N], int mi) { enum { M_PER_MMA = Mma_tile::M_PER_MMA_PER_CTA }; #pragma unroll for( int ni = 0; ni < Mma_tile::MMAS_N; ++ni ) { // The number of MMAs that are stored per loop iteration. enum { MMAS_M_PER_LOOP = Mma_tile::MMAS_M / LOOPS }; // Store 1st column of the different MMAs. #pragma unroll for( int mj = 0; mj < MMAS_M_PER_LOOP; ++mj ) { // Precompute the immediates to jump between rows. int row_0 = (mj * M_PER_MMA + 0) * BYTES_PER_ROW; int row_1 = (mj * M_PER_MMA + 8) * BYTES_PER_ROW; uint2 tmp0, tmp1; tmp0.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(0); tmp0.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(1); tmp1.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(2); tmp1.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(3); // Store. fmha::sts(this->smem_write_ + row_0, tmp0); fmha::sts(this->smem_write_ + row_1, tmp1); } // Swizzle the write pointer using a XOR of 16B. this->smem_write_ ^= 32; // Store 2nd column of the different MMAs. #pragma unroll for( int mj = 0; mj < MMAS_M_PER_LOOP; ++mj ) { // Precompute the immediates to jump between rows. int row_0 = (mj * M_PER_MMA + 0) * BYTES_PER_ROW; int row_1 = (mj * M_PER_MMA + 8) * BYTES_PER_ROW; uint2 tmp0, tmp1; tmp0.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(4); tmp0.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(5); tmp1.x = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(6); tmp1.y = acc[mi * MMAS_M_PER_LOOP + mj][ni].reg(7); // Store. fmha::sts(this->smem_write_ + row_0, tmp0); fmha::sts(this->smem_write_ + row_1, tmp1); } // Cancel the previous XOR of 1 + swizzle the write pointer using a XOR of 32B or 64B. this->smem_write_ ^= (ni & 1) ? 7 * 32 : 3 * 32; } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Smem_tile_mma { using Mma_tile = fmha::Hmma_tile; using Fragment = fmha::Fragment_a; enum { COLS = Cta_tile::N }; enum { BYTES_PER_ELT = 2 }; enum { BYTES_PER_STS = 4 }; enum { BYTES_PER_ROW = COLS * BYTES_PER_ELT }; // TODO enum { BYTES_PER_TILE = Cta_tile::M * BYTES_PER_ROW }; enum { WARPS_M = Cta_tile::WARPS_M }; enum { WARPS_N = Cta_tile::WARPS_N }; enum { WARPS_K = Cta_tile::WARPS_K }; static_assert(WARPS_K == 1); inline __device__ Smem_tile_mma(char *smem, int tidx) { smem_ = __nvvm_get_smem_pointer(smem); int write_col, write_row; static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8) || (WARPS_M == 4 || WARPS_N == 8) || WARPS_N == 1); if( WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8) ) { write_row = (tidx & 0x1c) / 4; write_col = (tidx & 0xe0) / 4 + (tidx & 0x03); } else { write_row = (tidx & 0xe0) / 2 + (tidx & 0x1c) / 4; write_col = (tidx & 0x03); } write_col ^= (write_row & 0x07) * 4; write_offset_ = write_row * BYTES_PER_ROW + write_col * BYTES_PER_STS; } template inline __device__ void store(const uint4 (®s)[M][N]) { static_assert(COLS == Cta_tile::N); for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = write_offset_ + mi * WARPS_M * 16 * BYTES_PER_ROW + ni * WARPS_N * 16 * BYTES_PER_ELT; fmha::sts(smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].x); fmha::sts(smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].z); offset ^= 4 * BYTES_PER_STS; fmha::sts(smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].y); fmha::sts(smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].w); } } } uint32_t smem_; uint32_t write_offset_; uint32_t warp_m; uint32_t warp_n; uint32_t lane; }; template< typename Cta_tile, typename Base = Smem_tile_mma< Cta_tile>> struct Smem_tile_mma_transposed : public Base { enum { BYTES_PER_LDS = 16 }; enum { BYTES_PER_ROW = Base::BYTES_PER_ROW }; enum { BYTES_PER_ELT = Base::BYTES_PER_ELT }; enum { WARPS_M = Base::WARPS_M }; enum { WARPS_N = Base::WARPS_N }; static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8)); using Fragment = typename Base::Fragment; inline __device__ Smem_tile_mma_transposed(char *smem, int tidx) : Base(smem, tidx) { static_assert(WARPS_M == 1 && (WARPS_N == 4 || WARPS_N == 8)); int read_row, read_col; read_row = (tidx & 0x0f); read_col = (tidx & 0xe0) / 16 + (tidx & 0x1c) / 16; read_col ^= (read_row & 0x07); read_offset_ = read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; } template inline __device__ void load(Fragment (&frag)[M][N]) { static_assert(Base::COLS == Cta_tile::N); for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = read_offset_ + mi * WARPS_M * 16 * BYTES_PER_ROW + ni * WARPS_N * 16 * BYTES_PER_ELT; uint4 dst; fmha::ldsmt(dst, this->smem_ + offset); frag[mi][ni].reg(0) = dst.x; frag[mi][ni].reg(1) = dst.z; // Fragment A regs col major! frag[mi][ni].reg(2) = dst.y; frag[mi][ni].reg(3) = dst.w; } } } uint32_t read_offset_; }; template< typename Cta_tile, typename Base = Smem_tile_mma< Cta_tile>> struct Smem_tile_mma_epilogue : public Base { enum { BYTES_PER_LDS = 16 }; enum { BYTES_PER_ROW = Base::BYTES_PER_ROW }; enum { BYTES_PER_ELT = Base::BYTES_PER_ELT }; enum { THREADS_PER_ROW = BYTES_PER_ROW / BYTES_PER_LDS }; static_assert(THREADS_PER_ROW * BYTES_PER_LDS == BYTES_PER_ROW); enum { ROWS_PER_LDS = Cta_tile::THREADS_PER_CTA / THREADS_PER_ROW }; enum { NUM_LDS = Cta_tile::M / ROWS_PER_LDS }; static_assert(NUM_LDS * ROWS_PER_LDS == Cta_tile::M); enum { WARPS_M = Base::WARPS_M }; enum { WARPS_N = Base::WARPS_N }; static_assert((WARPS_M == 4 || WARPS_N == 8) || WARPS_N == 1); using Acc = fmha::Fragment_accumulator; inline __device__ Smem_tile_mma_epilogue(char *smem, int tidx) : Base(smem, tidx) { const int read_row = tidx / THREADS_PER_ROW; int read_col = tidx % THREADS_PER_ROW; read_col ^= (read_row & 0x07); read_offset_ = read_row * BYTES_PER_ROW + read_col * BYTES_PER_LDS; } inline __device__ void load(uint4 (&data)[NUM_LDS]) { for( int ii = 0; ii < NUM_LDS; ii++ ) { size_t offset = read_offset_ + ii * ROWS_PER_LDS * BYTES_PER_ROW; fmha::lds(data[ii], this->smem_ + offset); } } template inline __device__ void store(const Acc (&acc)[M][N]){ #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { // 1st row - 4 elements per row. float tmp00 = acc[mi][ni].elt(0); float tmp01 = acc[mi][ni].elt(1); float tmp02 = acc[mi][ni].elt(4); float tmp03 = acc[mi][ni].elt(5); // 2nd row - 4 elements per row. float tmp10 = acc[mi][ni].elt(2); float tmp11 = acc[mi][ni].elt(3); float tmp12 = acc[mi][ni].elt(6); float tmp13 = acc[mi][ni].elt(7); uint32_t x = fmha::float2_to_half2(tmp00, tmp01); uint32_t y = fmha::float2_to_half2(tmp02, tmp03); uint32_t z = fmha::float2_to_half2(tmp10, tmp11); uint32_t w = fmha::float2_to_half2(tmp12, tmp13); size_t offset = (this->write_offset_ ^ (ni * 32)) + mi * WARPS_M * 16 * BYTES_PER_ROW; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, x); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, z); offset ^= 4 * Base::BYTES_PER_STS; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, y); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, w); } } } template inline __device__ void store(const uint4 (®s)[M][N]) { for( int mi = 0; mi < M; mi++ ) { for( int ni = 0; ni < N; ni++ ) { size_t offset = (this->write_offset_ ^ (ni * 32)) + mi * WARPS_M * 16 * BYTES_PER_ROW; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].x); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].z); offset ^= 4 * Base::BYTES_PER_STS; fmha::sts(this->smem_ + offset + 0 * BYTES_PER_ROW, regs[mi][ni].y); fmha::sts(this->smem_ + offset + 8 * BYTES_PER_ROW, regs[mi][ni].w); } } } uint32_t read_offset_; }; } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/softmax.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// struct Sum_ { enum { IS_SUM = 1 }; static inline __device__ float apply(float x, float y) { return x + y; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Max_ { enum { IS_SUM = 0 }; static inline __device__ float apply(float x, float y) { return x > y ? x : y; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ float apply_exp_(float x, float max) { return __expf(x - max); } //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Softmax_base { // The Mma tile. using Mma_tile = fmha::Hmma_tile; // The number of MMAs in M/N dimensions. enum { MMAS_M = Mma_tile::MMAS_M }; enum { MMAS_N = Mma_tile::MMAS_N }; // The number of groups of warp such that we have at most 4 warps writing consecutive elements. enum { GROUPS = fmha::Div_up::VALUE }; // The number of elements that we are going to store per row. enum { ELEMENTS_PER_ROW = Cta_tile::WARPS_N / GROUPS }; // The number of rows. enum { ROWS = Cta_tile::M * GROUPS }; // The total number of elements. enum { ELEMENTS = ROWS * ELEMENTS_PER_ROW }; // Ctor. template inline __device__ Softmax_base(const Params ¶ms, void *smem, int bidb, int tidx) : // packed_mask_ptr_(reinterpret_cast(params.packed_mask_ptr)), smem_(reinterpret_cast(smem)), tidx_(tidx) { // Move to the 1st mask loaded by the thread+ tidx; // packed_mask_ptr_ += bidb * params.packed_mask_stride_in_bytes + tidx * sizeof(uint32_t); // Extract the position in the warp. int warp = tidx / Cta_tile::THREADS_PER_WARP; int lane = tidx % Cta_tile::THREADS_PER_WARP; // Decompose the warp index into M and N. int warp_m = warp % Cta_tile::WARPS_M; int warp_n = warp / Cta_tile::WARPS_M; // Decompose the warp-n index into group/position-inside-the-group. int warp_g = warp_n / ELEMENTS_PER_ROW; int warp_i = warp_n % ELEMENTS_PER_ROW; // The location written by the threads. int write_row = warp_g * (ROWS / GROUPS) + warp_m * Mma_tile::M_PER_MMA + lane / 4; int write_col = warp_i; // Assemble the write pointer. smem_write_ = &smem_[write_row * ELEMENTS_PER_ROW + write_col]; // Assemble the read pointer. smem_read_ = &smem_[warp_m * Mma_tile::M_PER_MMA + lane / 4]; } template inline __device__ void apply_mask(const Mask &mask) { #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ii = 0; ii < 2; ++ii ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { #pragma unroll for( int jj = 0; jj < 4; ++jj ) { if( !mask.is_valid(mi, ni, ii, jj) ) { elt_[2 * mi + ii][4 * ni + jj] = -INFINITY; } } } } } } // Apply the exp to all the elements. inline __device__ void apply_exp(const float (&max)[MMAS_M * 2]) { #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N * 4; ++ni ) { elt_[mi][ni] = apply_exp_(elt_[mi][ni], max[mi]); } } } // Do a CTA-wide reduction. template inline __device__ void reduce_1x4(float (&dst)[MMAS_M * 2]) { #if defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) if( Functor::IS_SUM ) { // Apply the summation inside the thread. float tmp[MMAS_M * 2][2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { tmp[mi][0] = 0.f; tmp[mi][1] = 0.f; #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { tmp[mi][0] += elt_[mi][4 * ni + 0]; tmp[mi][0] += elt_[mi][4 * ni + 1]; tmp[mi][1] += elt_[mi][4 * ni + 2]; tmp[mi][1] += elt_[mi][4 * ni + 3]; } dst[mi] = tmp[mi][0] + tmp[mi][1]; } } else #endif // defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) { // Apply the functor for each row inside a thread. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = elt_[mi][0]; #pragma unroll for( int ni = 1; ni < MMAS_N * 4; ++ni ) { dst[mi] = Functor::apply(dst[mi], elt_[mi][ni]); } } } // Apply the functor for each row inside each group of 4 threads. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 1)); __syncwarp(); dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 2)); __syncwarp(); } // Store the different values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { if( tidx_ % 4 == 0 ) { smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 0) * ELEMENTS_PER_ROW] = dst[2 * mi + 0]; smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 8) * ELEMENTS_PER_ROW] = dst[2 * mi + 1]; } } // Make sure the values are in shared memory. __syncthreads(); // Load 8 values (one for each warp). The /8 corresponds to /(4*2) where 4 is from the // float4. float4 tmp[1]; if( tidx_ < Cta_tile::M ) { tmp[0] = reinterpret_cast(&smem_[0 * ELEMENTS / 2])[tidx_]; } // Compute the reduction of those 8 values in a binary-tree fashion. tmp[0].x = Functor::apply(tmp[0].x, tmp[0].y); tmp[0].z = Functor::apply(tmp[0].z, tmp[0].w); tmp[0].x = Functor::apply(tmp[0].x, tmp[0].z); // Make sure we can write to shared memory. __syncthreads(); // Store the value back to shared memory. if( tidx_ < Cta_tile::M ) { smem_[tidx_] = tmp[0].x; } // Make sure the data is in shared memory. __syncthreads(); // Finally read the values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { dst[2 * mi + 0] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 0]; dst[2 * mi + 1] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 8]; } } // Do a CTA-wide reduction. template inline __device__ void reduce_1x8(float (&dst)[MMAS_M * 2]) { #if defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) if( Functor::IS_SUM ) { // Apply the summation inside the thread. float tmp[MMAS_M * 2][2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { tmp[mi][0] = 0.f; tmp[mi][1] = 0.f; #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { tmp[mi][0] += elt_[mi][4 * ni + 0]; tmp[mi][0] += elt_[mi][4 * ni + 1]; tmp[mi][1] += elt_[mi][4 * ni + 2]; tmp[mi][1] += elt_[mi][4 * ni + 3]; } dst[mi] = tmp[mi][0] + tmp[mi][1]; } } else #endif // defined(USE_SAME_SUM_ORDER_IN_SOFTMAX_AS_REF_CODE) { // Apply the functor for each row inside a thread. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = elt_[mi][0]; #pragma unroll for( int ni = 1; ni < MMAS_N * 4; ++ni ) { dst[mi] = Functor::apply(dst[mi], elt_[mi][ni]); } } } // Apply the functor for each row inside each group of 4 threads. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 1)); __syncwarp(); dst[mi] = Functor::apply(dst[mi], __shfl_xor_sync(uint32_t(-1), dst[mi], 2)); __syncwarp(); } // Store the different values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { if( tidx_ % 4 == 0 ) { smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 0) * ELEMENTS_PER_ROW] = dst[2 * mi + 0]; smem_write_[(mi * Mma_tile::M_PER_MMA_PER_CTA + 8) * ELEMENTS_PER_ROW] = dst[2 * mi + 1]; } } // Make sure the values are in shared memory. __syncthreads(); // Load 8 values (one for each warp). The /8 corresponds to /(4*2) where 4 is from the // float4. float4 tmp[2]; if( tidx_ < Cta_tile::M ) { tmp[0] = reinterpret_cast(&smem_[0 * ELEMENTS / 2])[tidx_]; tmp[1] = reinterpret_cast(&smem_[1 * ELEMENTS / 2])[tidx_]; } // Compute the reduction of those 8 values in a binary-tree fashion. tmp[0].x = Functor::apply(tmp[0].x, tmp[0].y); tmp[0].z = Functor::apply(tmp[0].z, tmp[0].w); tmp[1].x = Functor::apply(tmp[1].x, tmp[1].y); tmp[1].z = Functor::apply(tmp[1].z, tmp[1].w); tmp[0].x = Functor::apply(tmp[0].x, tmp[0].z); tmp[1].x = Functor::apply(tmp[1].x, tmp[1].z); tmp[0].x = Functor::apply(tmp[0].x, tmp[1].x); // Make sure we can write to shared memory. __syncthreads(); // Store the value back to shared memory. if( tidx_ < Cta_tile::M ) { smem_[tidx_] = tmp[0].x; } // Make sure the data is in shared memory. __syncthreads(); // Finally read the values. #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { dst[2 * mi + 0] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 0]; dst[2 * mi + 1] = smem_read_[mi * Mma_tile::M_PER_MMA_PER_CTA + 8]; } } // Do a CTA-wide reduction. template inline __device__ void reduce(float (&dst)[MMAS_M * 2]) { static_assert(Cta_tile::WARPS_M == 1 && (Cta_tile::WARPS_N == 4 || Cta_tile::WARPS_N == 8)); if( Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 4 ) { reduce_1x4(dst); } else if( Cta_tile::WARPS_M == 1 && Cta_tile::WARPS_N == 8 ) { reduce_1x8(dst); } else { assert(false); } // Make sure we are done reading from shared memory. __syncthreads(); } // Scale all the elements. inline __device__ void scale(const float (&sum)[MMAS_M * 2]) { // Precompute the inverse sum to normalize. Without -use_fast_math, it makes a huge deal. float inv_sum[MMAS_M * 2]; #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { inv_sum[mi] = (sum[mi] == 0.f || sum[mi] != sum[mi]) ? 1.f : 1.f / sum[mi]; } // Update the values. #pragma unroll for( int mi = 0; mi < MMAS_M * 2; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N * 4; ++ni ) { elt_[mi][ni] *= inv_sum[mi]; } } } // The pointer to the mask. const char *packed_mask_ptr_; // Shared memory for the CTA-wide reduction. float *smem_, *smem_write_, *smem_read_; // The current thread index. int tidx_; // The elements. float elt_[MMAS_M * 2][MMAS_N * 4]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Softmax : public Softmax_base { // The base class. using Base = Softmax_base; // The fragment. using Fragment_a = fmha::Fragment_a; static_assert(Fragment_a::NUM_REGS == 4); // The MMAs. enum { MMAS_M = Base::MMAS_M }; enum { MMAS_N = Base::MMAS_N }; // The accumulators. using Accumulator = fmha::Fragment_accumulator; using Accumulator_out = Fragment; static_assert(Accumulator_out::NUM_REGS == 4); static_assert(std::is_same::value); // Ctor. template inline __device__ Softmax(const Params ¶ms, void *smem, int bidb, int tidx) : Base(params, smem, bidb, tidx), params_scale_bmm1_(params.scale_bmm1) { } // Store the tile after softmax. template inline __device__ void store(Gmem_tile &gmem_tile) { Accumulator_out acc[MMAS_M][MMAS_N]; #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { // The elements. float tmp_00 = this->elt_[2 * mi + 0][4 * ni + 0]; float tmp_01 = this->elt_[2 * mi + 0][4 * ni + 1]; float tmp_02 = this->elt_[2 * mi + 0][4 * ni + 2]; float tmp_03 = this->elt_[2 * mi + 0][4 * ni + 3]; float tmp_10 = this->elt_[2 * mi + 1][4 * ni + 0]; float tmp_11 = this->elt_[2 * mi + 1][4 * ni + 1]; float tmp_12 = this->elt_[2 * mi + 1][4 * ni + 2]; float tmp_13 = this->elt_[2 * mi + 1][4 * ni + 3]; // Transform to accumulators. acc[mi][ni].reg(0) = fmha::float2_to_half2(tmp_00, tmp_01); acc[mi][ni].reg(1) = fmha::float2_to_half2(tmp_10, tmp_11); acc[mi][ni].reg(2) = fmha::float2_to_half2(tmp_02, tmp_03); acc[mi][ni].reg(3) = fmha::float2_to_half2(tmp_12, tmp_13); } } // Delegate to the gmem tile to store. gmem_tile.store(acc); } // Pack the data to a fragment for the next GEMM. template inline __device__ void pack(Fragment_a (&dst)[K][M]) const { #pragma unroll for( int mi = 0; mi < M; ++mi ) { #pragma unroll for( int ki = 0; ki < K; ++ki ) { // 1st row - 4 elements per row. float tmp_00 = this->elt_[2 * mi + 0][4 * ki + 0]; float tmp_01 = this->elt_[2 * mi + 0][4 * ki + 1]; float tmp_02 = this->elt_[2 * mi + 0][4 * ki + 2]; float tmp_03 = this->elt_[2 * mi + 0][4 * ki + 3]; // 2nd row - 4 elements per row. float tmp_10 = this->elt_[2 * mi + 1][4 * ki + 0]; float tmp_11 = this->elt_[2 * mi + 1][4 * ki + 1]; float tmp_12 = this->elt_[2 * mi + 1][4 * ki + 2]; float tmp_13 = this->elt_[2 * mi + 1][4 * ki + 3]; // Pack to 4 registers. dst[ki][mi].reg(0) = fmha::float2_to_half2(tmp_00, tmp_01); dst[ki][mi].reg(1) = fmha::float2_to_half2(tmp_10, tmp_11); dst[ki][mi].reg(2) = fmha::float2_to_half2(tmp_02, tmp_03); dst[ki][mi].reg(3) = fmha::float2_to_half2(tmp_12, tmp_13); } } } // Scale FP32 fragments inline __device__ void unpack(const Accumulator (&acc)[MMAS_M][MMAS_N]) { const float scalef = reinterpret_cast(this->params_scale_bmm1_); #pragma unroll for( int mi = 0; mi < MMAS_M; ++mi ) { #pragma unroll for( int ni = 0; ni < MMAS_N; ++ni ) { // 1st row - 4 elements per row. this->elt_[2 * mi + 0][4 * ni + 0] = acc[mi][ni].elt(0) * scalef; this->elt_[2 * mi + 0][4 * ni + 1] = acc[mi][ni].elt(1) * scalef; this->elt_[2 * mi + 0][4 * ni + 2] = acc[mi][ni].elt(4) * scalef; this->elt_[2 * mi + 0][4 * ni + 3] = acc[mi][ni].elt(5) * scalef; // 2nd row - 4 elements per row. this->elt_[2 * mi + 1][4 * ni + 0] = acc[mi][ni].elt(2) * scalef; this->elt_[2 * mi + 1][4 * ni + 1] = acc[mi][ni].elt(3) * scalef; this->elt_[2 * mi + 1][4 * ni + 2] = acc[mi][ni].elt(6) * scalef; this->elt_[2 * mi + 1][4 * ni + 3] = acc[mi][ni].elt(7) * scalef; } } } const uint32_t params_scale_bmm1_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha/utils.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include extern "C" __device__ uint32_t __nvvm_get_smem_pointer(void *ptr); //////////////////////////////////////////////////////////////////////////////////////////////////// namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// struct Row {}; struct Col {}; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, bool = (M & (M-1)) == 0 > struct Next_power_of_two { }; template< int M > struct Next_power_of_two< M, true > { enum { VALUE = M }; }; template<> struct Next_power_of_two< 3, false> { enum { VALUE = 4 }; }; template<> struct Next_power_of_two< 5, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 6, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 7, false> { enum { VALUE = 8 }; }; template<> struct Next_power_of_two< 9, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 10, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 11, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 12, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 13, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 14, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 15, false> { enum { VALUE = 16 }; }; template<> struct Next_power_of_two< 24, false> { enum { VALUE = 32 }; }; template<> struct Next_power_of_two< 48, false> { enum { VALUE = 64 }; }; template<> struct Next_power_of_two< 80, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two< 96, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two<112, false> { enum { VALUE = 128 }; }; template<> struct Next_power_of_two<144, false> { enum { VALUE = 256 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, bool = (N & (N-1)) == 0 > struct Prev_power_of_two { }; template< int N > struct Prev_power_of_two< N, true > { enum { VALUE = N }; }; template<> struct Prev_power_of_two< 3, false> { enum { VALUE = 2 }; }; template<> struct Prev_power_of_two< 5, false> { enum { VALUE = 4 }; }; template<> struct Prev_power_of_two< 6, false> { enum { VALUE = 4 }; }; template<> struct Prev_power_of_two< 7, false> { enum { VALUE = 4 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, int N > struct Div_up { enum { VALUE = (M + N-1) / N }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B > struct Max { enum { VALUE = A >= B ? A : B }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B, int C > struct Max_3 { enum { VALUE = Max::VALUE, C>::VALUE }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int A, int B > struct Min { enum { VALUE = A <= B ? A : B }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int SIZE_IN_BYTES > struct Uint_from_size_in_bytes { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<1> { using Type = uint8_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<2> { using Type = uint16_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<4> { using Type = uint32_t; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<8> { using Type = uint2; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Uint_from_size_in_bytes<16> { using Type = uint4; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int WARPS_M, int WARPS_N, int WARPS_K > struct Warp_masks { }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Warp_masks<8, 1, 1> { enum { M = 0xe0, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<4, 2, 1> { enum { M = 0x60, N = 0x80, K = 0x00 }; }; template<> struct Warp_masks<4, 1, 2> { enum { M = 0x60, N = 0x00, K = 0x80 }; }; template<> struct Warp_masks<4, 1, 1> { enum { M = 0x60, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<2, 4, 1> { enum { M = 0x20, N = 0xc0, K = 0x00 }; }; template<> struct Warp_masks<2, 2, 2> { enum { M = 0x20, N = 0x40, K = 0x80 }; }; template<> struct Warp_masks<2, 2, 1> { enum { M = 0x20, N = 0x40, K = 0x00 }; }; template<> struct Warp_masks<2, 1, 2> { enum { M = 0x20, N = 0x00, K = 0x40 }; }; template<> struct Warp_masks<2, 1, 1> { enum { M = 0x20, N = 0x00, K = 0x00 }; }; template<> struct Warp_masks<1, 8, 1> { enum { M = 0x00, N = 0xe0, K = 0x00 }; }; template<> struct Warp_masks<1, 4, 2> { enum { M = 0x00, N = 0x60, K = 0x80 }; }; template<> struct Warp_masks<1, 4, 1> { enum { M = 0x00, N = 0x60, K = 0x00 }; }; template<> struct Warp_masks<1, 2, 2> { enum { M = 0x00, N = 0x20, K = 0x40 }; }; template<> struct Warp_masks<1, 2, 1> { enum { M = 0x00, N = 0x20, K = 0x00 }; }; template<> struct Warp_masks<1, 1, 4> { enum { M = 0x00, N = 0x00, K = 0x60 }; }; template<> struct Warp_masks<1, 1, 2> { enum { M = 0x00, N = 0x00, K = 0x20 }; }; template<> struct Warp_masks<1, 1, 1> { enum { M = 0x00, N = 0x00, K = 0x00 }; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename T > inline __device__ __host__ T div_up(T m, T n) { return (m + n-1) / n; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline int clz(int x) { for( int i = 31; i >= 0; --i ) { if( (1 << i) & x ) { return 31 - i; } } return 32; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline int find_log_2(int x, bool round_up = false) { int a = 31 - clz(x); if( round_up ) { a += (x & (x-1)) ? 1 : 0; } return a; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hadd2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("add.f16x2 %0, %1, %2;\n" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hmin2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("min.f16x2 %0, %1, %2;" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hmul2(uint32_t a, uint32_t b) { uint32_t c; asm volatile("mul.f16x2 %0, %1, %2;\n" : "=r"(c) : "r"(a), "r"(b)); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hmul4(uint2 a, uint2 b) { uint2 c; c.x = hmul2(a.x, b.x); c.y = hmul2(a.y, b.y); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hmul8(uint4 a, uint4 b) { uint4 c; c.x = hmul2(a.x, b.x); c.y = hmul2(a.y, b.y); c.z = hmul2(a.z, b.z); c.w = hmul2(a.w, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hmul8(uint32_t a, uint4 b) { uint4 c; c.x = hmul2(a, b.x); c.y = hmul2(a, b.y); c.z = hmul2(a, b.z); c.w = hmul2(a, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hrelu2(uint32_t x, uint32_t lb = 0) { uint32_t res; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile( "max.f16x2 %0, %1, %2;\n" : "=r"(res) : "r"(x), "r"(lb)); #else const uint32_t zero = 0u; asm volatile( \ "{\n" \ "\t .reg .f16x2 sela;\n" \ "\t set.gtu.u32.f16x2 sela, %1, %2;\n" \ "\t and.b32 %0, sela, %1;\n" "}\n" : "=r"(res) : "r"(x), "r"(zero)); #endif return res; } static inline __device__ uint32_t habs2(uint32_t x) { uint32_t res; asm volatile( "abs.f16x2 %0, %1;\n" : "=r"(res) : "r"(x)); return res; } //////////////////////////////////////////////////////////////////////////////////////////////////// // template< typename T > static inline __device__ T clamp(T x, T lb, T ub) { return x < lb ? lb : (x > ub ? ub : x); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t clamp_to_zero(uint16_t x) { uint16_t mask; asm volatile("set.gtu %0, %1, 0;" : "=h"(mask) : "h"(x)); return mask & x; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t float_to_half(float f) { uint16_t h; asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(h) : "f"(f)); return h; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float2_to_half2(float a, float b) { uint32_t c; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile("cvt.rn.f16x2.f32 %0, %1, %2;\n" : "=r"(c) : "f"(b), "f"(a)); #else uint16_t lo = float_to_half(a); uint16_t hi = float_to_half(b); asm volatile("mov.b32 %0, {%1, %2};\n" : "=r"(c) : "h"(lo), "h"(hi)); #endif return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float_to_half2(float a) { return float2_to_half2(a,a); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t float2_to_half2(const float2 &f) { return float2_to_half2(f.x, f.y); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 float4_to_half4(float x, float y, float z, float w) { uint2 d; d.x = float2_to_half2(x, y); d.y = float2_to_half2(z, w); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hfma2(uint32_t a, uint32_t b, uint32_t c) { uint32_t d; asm volatile("fma.rn.f16x2 %0, %1, %2, %3;\n" : "=r"(d) : "r"(a), "r"(b), "r"(c)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hfma2_relu(uint32_t a, uint32_t b, uint32_t c) { uint32_t d; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile("fma.rn.f16x2.relu %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c)); #else d = hrelu2(hfma2(a, b, c)); #endif return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t h0_h0(uint32_t x) { uint32_t y; asm volatile("{.reg .f16 lo, hi; mov.b32 {lo, hi}, %1; mov.b32 %0, {lo, lo};}\n" : "=r"(y) : "r"(x)); return y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float h0_to_float(uint32_t h2) { float f; asm volatile("{\n" \ ".reg .f16 lo, hi;\n" \ "mov.b32 {lo, hi}, %1;\n" \ "cvt.f32.f16 %0, lo;\n" \ "}\n" : "=f"(f) : "r"(h2)); return f; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t h1_h1(uint32_t x) { uint32_t y; asm volatile("{.reg .f16 lo, hi; mov.b32 {lo, hi}, %1; mov.b32 %0, {hi, hi};}\n" : "=r"(y) : "r"(x)); return y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hadd(uint16_t a, uint16_t b) { uint16_t d; asm volatile("add.f16 %0, %1, %2;" : "=h"(d) : "h"(a), "h"(b)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint32_t hadd(uint32_t a, uint32_t b) { return hadd2(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hadd4(uint2 a, uint2 b) { uint2 c; c.x = hadd2(a.x, b.x); c.y = hadd2(a.y, b.y); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint2 hadd(uint2 a, uint2 b) { return hadd4(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hadd8(uint4 a, uint4 b) { uint4 c; c.x = hadd2(a.x, b.x); c.y = hadd2(a.y, b.y); c.z = hadd2(a.z, b.z); c.w = hadd2(a.w, b.w); return c; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 fadd4(uint4 a, uint4 b) { float4 c; c.x = reinterpret_cast(a.x) + reinterpret_cast(b.x); c.y = reinterpret_cast(a.y) + reinterpret_cast(b.y); c.z = reinterpret_cast(a.z) + reinterpret_cast(b.z); c.w = reinterpret_cast(a.w) + reinterpret_cast(b.w); return reinterpret_cast(c); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint4 hadd(uint4 a, uint4 b) { return hadd8(a, b); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float half_to_float(uint16_t h) { float f; asm volatile("cvt.f32.f16 %0, %1;\n" : "=f"(f) : "h"(h)); return f; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float2 half2_to_float2(uint32_t x) { uint16_t lo, hi; asm volatile("mov.b32 {%0, %1}, %2;\n" : "=h"(lo), "=h"(hi) : "r"(x)); return make_float2(half_to_float(lo), half_to_float(hi)); } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ void half2_to_float2(float &x, float &y, uint32_t h) { float2 tmp = half2_to_float2(h); x = tmp.x; y = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hfma(uint16_t a, uint16_t b, uint16_t c) { uint16_t d; asm volatile("fma.rn.f16 %0, %1, %2, %3;" : "=h"(d) : "h"(a), "h"(b), "h"(c)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ uint16_t hmul(uint16_t a, uint16_t b) { uint16_t d; asm volatile("mul.f16 %0, %1, %2;" : "=h"(d) : "h"(a), "h"(b)); return d; } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline __device__ float sigmoid(float x) { return 1.f / (1.f + expf(-x)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint16_t &dst) { dst = uint16_t(0); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint32_t &dst) { dst = 0u; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint2 &dst) { dst = make_uint2(0u, 0u); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void clear(uint4 &dst) { dst = make_uint4(0u, 0u, 0u, 0u); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // P R E D I C A T E P A C K I N G // //////////////////////////////////////////////////////////////////////////////////////////////////// enum { BYTES_PER_REG = 4, PREDS_PER_BYTE = 4, PREDS_PER_REG = BYTES_PER_REG * PREDS_PER_BYTE }; //////////////////////////////////////////////////////////////////////////////////////////////////// // // G E N E R I C P R E D I C A T E D L D G S T S // //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M, typename Functor > inline __device__ void load_(Functor &fct, const uint32_t (&preds)[M]) { // The number of complete bytes (where we use all the predicates in a byte). enum { COMPLETE = N / PREDS_PER_BYTE }; // Make sure we did allocate enough predicates. static_assert(Div_up::VALUE <= M, ""); // The remainder. enum { REMAINDER = N - COMPLETE * PREDS_PER_BYTE }; // Make sure we got the math right and the remainder is between 0 and 3. static_assert(REMAINDER >= 0 && REMAINDER <= 3, ""); // The mask to extract the predicates. enum { COMPLETE_MASK = (1 << PREDS_PER_BYTE) - 1 }; // Clear the fetch registers. #pragma unroll for( int ii = 0; ii < N; ++ii ) { fct.clear(ii); } // Run complete steps. bool p[PREDS_PER_BYTE]; #pragma unroll for( int ii = 0; ii < COMPLETE; ++ii ) { // The predicate. uint32_t reg = preds[ii / BYTES_PER_REG]; // Extract the predicates. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { uint32_t mask = 1u << (ii % BYTES_PER_REG * 8 + jj); p[jj] = (reg & mask) != 0u; } // Issue the loads. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { fct.load(ii * PREDS_PER_BYTE + jj, p[jj]); } } // Skip the rest of the code if we do not have a remainder. if( REMAINDER > 0 ) { // The mask to extract the predicates. enum { REMAINDER_MASK = (1 << REMAINDER) - 1 }; // The predicate register. uint32_t reg = preds[COMPLETE / BYTES_PER_REG]; // Extract the predicates. #pragma unroll for( int jj = 0; jj < PREDS_PER_BYTE; ++jj ) { uint32_t mask = 1u << (COMPLETE % BYTES_PER_REG * 8 + jj); p[jj] = (reg & mask) != 0u; } // Issue the loads. #pragma unroll for( int ii = 0; ii < REMAINDER; ++ii ) { fct.load(COMPLETE * PREDS_PER_BYTE + ii, p[ii]); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int M, typename Functor > inline __device__ void load_(Functor &fct, uint32_t preds) { uint32_t tmp[1] = { preds }; load_(fct, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D G // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint8_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint16_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint32_t &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint2 &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldg(uint4 &dst, const void *ptr) { dst = *reinterpret_cast(ptr); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N > struct Ldg_functor { // Ctor. inline __device__ Ldg_functor(Data_type (&fetch)[N], const void* (&ptrs)[N]) : fetch_(fetch), ptrs_(ptrs) { } // Clear the element. inline __device__ void clear(int ii) { fmha::clear(fetch_[ii]); } // Trigger the loads. inline __device__ void load(int ii, bool p) { if( p ) { ldg(fetch_[ii], ptrs_[ii]); } } // The fetch registers. Data_type (&fetch_)[N]; // The pointers. const void* (&ptrs_)[N]; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N, int M > inline __device__ void ldg_(Data_type (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { Ldg_functor fct(fetch, ptrs); load_(fct, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint8_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint16_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint32_t (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint2 (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N, int M > inline __device__ void ldg(uint4 (&fetch)[N], const void* (&ptrs)[N], uint32_t (&preds)[M]) { ldg_(fetch, ptrs, preds); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D S // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint16_t &dst, uint32_t ptr) { asm volatile("ld.shared.b16 %0, [%1];\n" : "=h"(dst) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint32_t &dst, uint32_t ptr) { asm volatile("ld.shared.b32 %0, [%1];\n" : "=r"(dst) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint2 &dst, uint32_t ptr) { asm volatile("ld.shared.v2.b32 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void lds(uint4 &dst, uint32_t ptr) { asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x) , "=r"(dst.y) , "=r"(dst.z) , "=r"(dst.w) : "r"(ptr)); } //////////////////////////////////////////////////////////////////////////////////////////////////// // // L D S M // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint32_t &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x1.shared.b16 {%0}, [%1];\n" : "=r"(dst) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint32_t &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x1.trans.shared.b16 {%0}, [%1];\n" : "=r"(dst) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint2 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x2.shared.b16 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint2 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x2.trans.shared.b16 {%0, %1}, [%2];\n" : "=r"(dst.x), "=r"(dst.y) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsm(uint4 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x), "=r"(dst.y), "=r"(dst.z), "=r"(dst.w) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void ldsmt(uint4 &dst, uint32_t ptr) { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 730 asm volatile("ldmatrix.sync.aligned.m8n8.x4.trans.shared.b16 {%0, %1, %2, %3}, [%4];\n" : "=r"(dst.x), "=r"(dst.y), "=r"(dst.z), "=r"(dst.w) : "r"(ptr)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// // // S T G // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint8_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint16_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint32_t val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint2 val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void stg(void *ptr, uint4 val) { *reinterpret_cast(ptr) = val; } //////////////////////////////////////////////////////////////////////////////////////////////////// // // S T S // //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint16_t val) { asm volatile("st.shared.b16 [%0], %1;\n" : : "r"(ptr), "h"(val)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint32_t val) { asm volatile("st.shared.b32 [%0], %1;\n" : : "r"(ptr), "r"(val)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint2 val) { asm volatile("st.shared.v2.b32 [%0], {%1, %2};\n" : : "r"(ptr) , "r"(val.x) , "r"(val.y)); } //////////////////////////////////////////////////////////////////////////////////////////////////// inline __device__ void sts(uint32_t ptr, uint4 val) { asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};\n" : : "r"(ptr) , "r"(val.x) , "r"(val.y) , "r"(val.z) , "r"(val.w)); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Data_type, int N > inline __device__ void sts_(uint32_t (&ptrs)[N], const Data_type (&data)[N]) { #pragma unroll for( int ii = 0; ii < N; ++ii ) { sts(ptrs[ii], data[ii]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint16_t (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint32_t (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint2 (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > inline __device__ void sts(uint32_t (&ptrs)[N], const uint4 (&data)[N]) { sts_(ptrs, data); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include constexpr int TOTAL_DIM = 0; constexpr int THREE_DIM = 1; constexpr int H_DIM = 2; constexpr int D_DIM = 3; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Qkv_params { // The QKV matrices. void *qkv_ptr; // The stride between rows of the Q, K and V matrices. size_t qkv_stride_in_bytes; // The number of heads. int h; }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Fused_multihead_attention_fprop_params : public Qkv_params { // The dQKV matrices. void *dqkv_ptr; // Temporary for dKV. void *dkv_ptr; // The O matrix (output). void *o_ptr; // The stride between rows of O. int64_t o_stride_in_bytes; // The pointer to the S matrix, overwritten by the dP matrix (bwd). void *s_ptr; // The stride between rows of the S matrix. int64_t s_stride_in_bytes; // The dimensions. int b, s, d; // The scaling factors for the kernel. uint32_t scale_bmm1, scale_softmax, scale_bmm2; // array of length b+1 holding starting offset of each sequence. int *cu_seqlens; // The dropout probability (probability of keeping an activation). float p_dropout; // Scale factor of 1 / (1 - p_dropout). float rp_dropout; // Scale factor of 1 / (1 - p_dropout), in half2. uint32_t scale_dropout; // Random state. at::PhiloxCudaState philox_args; }; //////////////////////////////////////////////////////////////////////////////////////////////////// void run_fmha_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream); void run_fmha_dgrad_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_dgrad_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream); void run_fmha_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const bool is_training, const int num_chunks, cudaStream_t stream); void run_fmha_dgrad_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const int num_chunks, cudaStream_t stream); void fmha_run_noloop_reduce(void *out, const void *in, const int *cu_seqlens, const int hidden_size, const int batch_size, const int total, const int num_chunks, cudaStream_t stream); ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_128_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 128, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_128_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 128 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_128_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_128_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_256_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 256, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_256_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 256 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_256_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_256_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_384_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" using Kernel_traits = FMHA_kernel_traits< 384, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_384_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } void run_fmha_dgrad_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 384 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_384_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_384_64_sm80_kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_fp16_512_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_dgrad_kernel_1xN_reload.h" #include "fmha_dgrad_kernel_1xN_reload_nl.h" using Kernel_traits = FMHA_kernel_traits< 512, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_dgrad_fp16_512_64_sm80_kernel(Fused_multihead_attention_fprop_params params) { fmha::compute_dv_1xN(params); fmha::compute_dq_dk_1xN(params); } template __global__ void fmha_dgrad_fp16_512_64_sm80_nl_kernel(Fused_multihead_attention_fprop_params params){ fmha::compute_dv_1xN_nl(params); fmha::compute_dq_dk_1xN_nl(params); } void run_fmha_dgrad_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed< Kernel_traits::Cta_tile_p>; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 512 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute( fmha_dgrad_fp16_512_64_sm80_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); fmha_dgrad_fp16_512_64_sm80_kernel<<>>(params); } void run_fmha_dgrad_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const int num_chunks, cudaStream_t stream) { constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; using Smem_tile_s = fmha::Smem_tile_mma_transposed; constexpr int smem_size_s = Smem_tile_s::BYTES_PER_TILE; static_assert(smem_size_s == 16 * 512 * 2); static_assert(smem_size_o == 16 * 64 * 4 * Kernel_traits::Cta_tile_p::WARPS_N); constexpr int smem_size_dv = smem_size_s + 2 * smem_size_q + smem_size_v + smem_size_softmax; constexpr int smem_size_dq_dk = smem_size_s + smem_size_o + smem_size_q + smem_size_v; constexpr int smem_size = std::max(smem_size_dv, smem_size_dq_dk); auto kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<2>; if( num_chunks == 2 ) { kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<2>; }else if( num_chunks == 3 ) { kernel = fmha_dgrad_fp16_512_64_sm80_nl_kernel<3>; } else { assert(false && "Unsupperted number of chunks"); } if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b, num_chunks); kernel<<>>(params); FMHA_CHECK_CUDA(cudaPeekAtLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_kernel_1xN_reload.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void compute_dv_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dv = fmha::Cta_tile_extd; static_assert(Cta_tile_dv::M == 512 || Cta_tile_dv::M == 384 || Cta_tile_dv::M == 256 || Cta_tile_dv::M == 128); static_assert(Cta_tile_dv::N == 64); static_assert(Cta_tile_dv::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dv = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. // using Smem_tile_q = typename Kernel_traits::Smem_tile_q; using Smem_tile_q = fmha::Smem_tile_a; // The shared memory tile to reload Q as fragment b. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dV. using Gmem_tile_dv = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle dV. using Smem_tile_dv = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dv::NUM_LDS == Gmem_tile_dv::LDGS); static_assert(Smem_tile_dv::THREADS_PER_ROW == Gmem_tile_dv::THREADS_PER_ROW); using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; using Gmem_tile_do = typename Kernel_traits::Gmem_tile_do; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_do gmem_q(params, binfo, tidx); // treating dout as Q // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 2, binfo, tidx); // treating V as K // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dv::MMAS_N]; static_assert(Smem_tile_qt::Fragment::NUM_REGS == 4); static_assert(Mma_tile_dv::MMAS_K == 1); smem_qt.load(frag_qt[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[2][Mma_tile_p::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax( params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_st::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dv[Mma_tile_dv::MMAS_M][Mma_tile_dv::MMAS_N]; fmha::Clear_accumulator::apply(acc_dv); enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Load over the entire sequence length. for( int l = 0; l < STEPS; l++ ) { const int loop = l * Cta_tile_p::M; if( loop >= binfo.actual_seqlen ) break; // Load S uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Store s * dmask to smem for transpose smem_s.store(s_regs); // Declare the accumulators for the 1st gemm. // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Trigger the load for the next Q values. We're using double buffering, so reading qt is safe if( l < STEPS - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); float s_mat[2 * M][4 * N]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 0], s_mat[2 * mi + 0][4 * ni + 1], dst.x); fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 2], s_mat[2 * mi + 0][4 * ni + 3], dst.y); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 0], s_mat[2 * mi + 1][4 * ni + 1], dst.z); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 2], s_mat[2 * mi + 1][4 * ni + 3], dst.w); } } #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { float & s_dmask = s_mat[2 * mi + ii][4 * ni + jj]; const bool drop = reinterpret_cast(s_dmask) & 0x80000000; const float d_s = drop ? 0.f : softmax.elt_[2 * mi + ii][4 * ni + jj] * params.rp_dropout; s_dmask = fabsf(s_dmask); softmax.elt_[2 * mi + ii][4 * ni + jj] = d_s * fabsf(s_dmask); } } } } float p_sum[2 * M]; softmax.template reduce(p_sum); const float scalef = reinterpret_cast(params.scale_softmax); #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { softmax.elt_[2 * mi + ii][4 * ni + jj] -= p_sum[2 * mi + ii] * (s_mat[2 * mi + ii][4 * ni + jj]) ; softmax.elt_[2 * mi + ii][4 * ni + jj] *= scalef; } } } } typename Smem_tile_st::Fragment frag_s[Mma_tile_dv::MMAS_K][Mma_tile_dv::MMAS_M]; smem_s.load(frag_s); for( int ki = 0; ki < Mma_tile_dv::MMAS_K; ki++ ) { for( int mi = 0; mi < Mma_tile_dv::MMAS_M; mi++ ) { for( int ii = 0; ii < Smem_tile_st::Fragment::NUM_REGS; ii++ ) { frag_s[ki][mi].reg(ii) = fmha::hmul2(frag_s[ki][mi].reg(ii), params.scale_dropout); frag_s[ki][mi].reg(ii) = fmha::hrelu2(frag_s[ki][mi].reg(ii)); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); #pragma unroll for( int ki = 1; ki < Mma_tile_dv::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dv::MMAS_K; fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure we are reading from the correct buffer. smem_q.move_to_next_read_buffer(); smem_qt.move_to_next_read_buffer(); // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); smem_k.load(frag_k[0], 0); smem_qt.load(frag_qt[0], 0); } // Outer loop over the sequence length. // Epilogue swizzle for dV Smem_tile_dv smem_dv(&smem_[Kernel_traits::Smem_tile_q::BYTES_PER_TILE], tidx); smem_dv.store(acc_dv); __syncthreads(); uint4 dv_out[Smem_tile_dv::NUM_LDS]; smem_dv.load(dv_out); Qkv_params dv_params; dv_params.qkv_ptr = params.dqkv_ptr; dv_params.qkv_stride_in_bytes = params.qkv_stride_in_bytes; dv_params.h = params.h; Gmem_tile_dv gmem_dv(dv_params, 2, binfo, tidx); gmem_dv.store(dv_out); } template inline __device__ void compute_dq_dk_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dk = fmha::Cta_tile_extd; static_assert(Cta_tile_dk::M == 512 || Cta_tile_dk::M == 384 || Cta_tile_dk::M == 256 || Cta_tile_dk::M == 128); static_assert(Cta_tile_dk::N == 64); static_assert(Cta_tile_dk::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; using Mma_tile_o = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dk = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_v; // K is used like V in fprop // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. // using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; using Gmem_tile_o = fmha::Gmem_tile_dq; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dK. using Gmem_tile_dk = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle dK. using Smem_tile_dk = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dk::NUM_LDS == Gmem_tile_dk::LDGS); static_assert(Smem_tile_dk::THREADS_PER_ROW == Gmem_tile_dk::THREADS_PER_ROW); // The shared memory tile to reload Q transposed. using Smem_tile_qt = fmha::Smem_tile_b; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; static_assert(M == Mma_tile_o::MMAS_M); static_assert(N == Mma_tile_o::MMAS_K); // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Load dP uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); gmem_s.move(); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dk::MMAS_N]; smem_qt.load(frag_qt[0], 0); typename Smem_tile_k::Fragment frag_k[2][Mma_tile_o::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; enum { THREADS_PER_ROW = 32 }; enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dk[Mma_tile_dk::MMAS_M][Mma_tile_dk::MMAS_N]; fmha::Clear_accumulator::apply(acc_dk); // Load over the entire sequence length. for( int l=0;l= binfo.actual_seqlen ) break; // Pack dP as Fragment_a fmha::Fragment_a frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; frag_p[ni][mi].reg(0) = dst.x; // row 0, cols 0,1 frag_p[ni][mi].reg(1) = dst.z; // row 8, cols 0,1 frag_p[ni][mi].reg(2) = dst.y; // row 0, cols 8,9 frag_p[ni][mi].reg(3) = dst.w; // row 8, cols 8,9 } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. dQ = dP x dK #pragma unroll for( int ki = 1; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_o::MMAS_K; fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Store dP to smem for transpose smem_s.store(s_regs); if(l < STEPS - 1) { // Load next part of S gmem_s.load(s_regs, mask); gmem_s.move(); smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); typename Smem_tile_st::Fragment frag_s[Mma_tile_dk::MMAS_K][Mma_tile_dk::MMAS_M]; smem_s.load(frag_s); #pragma unroll for( int ki = 1; ki < Mma_tile_dk::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dk::MMAS_K; fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if( l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_qt.load(frag_qt[0], 0); smem_k.load(frag_k[0], 0); } // Outer loop over the sequence length. // Epilogue swizzle for dK Smem_tile_dk smem_dk(&smem_[0], tidx); smem_dk.store(acc_dk); __syncthreads(); uint4 dk_out[Smem_tile_dk::NUM_LDS]; smem_dk.load(dk_out); Qkv_params dk_params; dk_params.qkv_ptr = params.dqkv_ptr; dk_params.qkv_stride_in_bytes = params.qkv_stride_in_bytes; dk_params.h = params.h; Gmem_tile_dk gmem_dk(dk_params, 1, binfo, tidx); gmem_dk.store(dk_out); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_dgrad_kernel_1xN_reload_nl.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void compute_dv_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dv = fmha::Cta_tile_extd; static_assert(Cta_tile_dv::M == 512 || Cta_tile_dv::M == 384 || Cta_tile_dv::M == 256 || Cta_tile_dv::M == 128); static_assert(Cta_tile_dv::N == 64); static_assert(Cta_tile_dv::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dv = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = fmha::Smem_tile_a; // The shared memory tile to reload Q as fragment b. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store dV. using Gmem_tile_dv = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle dV. using Smem_tile_dv = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dv::NUM_LDS == Gmem_tile_dv::LDGS); static_assert(Smem_tile_dv::THREADS_PER_ROW == Gmem_tile_dv::THREADS_PER_ROW); using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Smem_tile_st = typename Kernel_traits::Smem_tile_st; using Gmem_tile_do = typename Kernel_traits::Gmem_tile_do; // Shared memory. extern __shared__ char smem_[]; // The block index for the chunk. const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_do gmem_q(params, binfo, tidx); // treating dout as Q // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); Smem_tile_qt smem_qt(&smem_[0], tidx); Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 2, binfo, tidx); // treating V as K // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); using Noloop = Noloop_traits; Noloop nl_traits(bidc); nl_traits.move_all(gmem_q, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dv::MMAS_N]; static_assert(Smem_tile_qt::Fragment::NUM_REGS == 4); static_assert(Mma_tile_dv::MMAS_K == 1); smem_qt.load(frag_qt[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[2][Mma_tile_p::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax( params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_st::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dv[Mma_tile_dv::MMAS_M][Mma_tile_dv::MMAS_N]; fmha::Clear_accumulator::apply(acc_dv); // Load over the entire sequence length. for(int l = 0; l < nl_traits.num_steps_;l++) { const int loop = nl_traits.offset_loop_count(l); if( loop >= binfo.actual_seqlen ) break; uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } smem_s.store(s_regs); // Declare the accumulators for the 1st gemm. // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1) & 1]); } // Trigger the load for the next Q values. We're using double buffering, so reading qt is safe if(l < nl_traits.num_steps_ - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); float s_mat[2 * M][4 * N]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 0], s_mat[2 * mi + 0][4 * ni + 1], dst.x); fmha::half2_to_float2(s_mat[2 * mi + 0][4 * ni + 2], s_mat[2 * mi + 0][4 * ni + 3], dst.y); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 0], s_mat[2 * mi + 1][4 * ni + 1], dst.z); fmha::half2_to_float2(s_mat[2 * mi + 1][4 * ni + 2], s_mat[2 * mi + 1][4 * ni + 3], dst.w); } } #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { float & s_dmask = s_mat[2 * mi + ii][4 * ni + jj]; const bool drop = reinterpret_cast(s_dmask) & 0x80000000; const float d_s= drop ? 0.f : softmax.elt_[2 * mi + ii][4 * ni + jj] * params.rp_dropout; s_dmask = fabsf(s_dmask); softmax.elt_[2 * mi + ii][4 * ni + jj] = d_s * (s_dmask); } } } } float p_sum[2 * M]; softmax.template reduce(p_sum); const float scalef = reinterpret_cast(params.scale_softmax); #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { #pragma unroll for( int jj = 0; jj < 4; jj++ ) { softmax.elt_[2 * mi + ii][4 * ni + jj] -= p_sum[2 * mi + ii] * (s_mat[2 * mi + ii][4 * ni + jj]) ; softmax.elt_[2 * mi + ii][4 * ni + jj] *= scalef; } } } } typename Smem_tile_st::Fragment frag_s[Mma_tile_dv::MMAS_K][Mma_tile_dv::MMAS_M]; smem_s.load(frag_s); for( int ki = 0; ki < Mma_tile_dv::MMAS_K; ki++ ) { for( int mi = 0; mi < Mma_tile_dv::MMAS_M; mi++ ) { for( int ii = 0; ii < Smem_tile_st::Fragment::NUM_REGS; ii++ ) { frag_s[ki][mi].reg(ii) = fmha::hmul2(frag_s[ki][mi].reg(ii), params.scale_dropout); frag_s[ki][mi].reg(ii) = fmha::hrelu2(frag_s[ki][mi].reg(ii)); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); static_assert(Mma_tile_dv::MMAS_K == 1); // DEBUG #pragma unroll for( int ki = 1; ki < Mma_tile_dv::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dv::MMAS_K; fmha::gemm(acc_dv, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < nl_traits.num_steps_ - 1) { gmem_q.commit(smem_q); } // Make sure we are reading from the correct buffer. smem_q.move_to_next_read_buffer(); smem_qt.move_to_next_read_buffer(); // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); smem_k.load(frag_k[0], 0); smem_qt.load(frag_qt[0], 0); } // Outer loop over the sequence length. // Epilogue for dV = (S * D)' * dout'. We're fully exposed to this! // Epilogue swizzle for dV Smem_tile_dv smem_dv(&smem_[Kernel_traits::Smem_tile_q::BYTES_PER_TILE], tidx); smem_dv.store(acc_dv); __syncthreads(); uint4 dv_out[Smem_tile_dv::NUM_LDS]; smem_dv.load(dv_out); Qkv_params dv_params; dv_params.qkv_ptr = params.dkv_ptr; dv_params.qkv_stride_in_bytes = params.h * 2 * CHUNKS * params.d * sizeof(half); dv_params.h = params.h; Gmem_tile_dv gmem_dv(dv_params, nl_traits.get_idx_dv(), binfo, tidx); gmem_dv.store(dv_out); } template inline __device__ void compute_dq_dk_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_dk = fmha::Cta_tile_extd; static_assert(Cta_tile_dk::M == 512 || Cta_tile_dk::M == 384 || Cta_tile_dk::M == 256 || Cta_tile_dk::M == 128); static_assert(Cta_tile_dk::N == 64); static_assert(Cta_tile_dk::K == 16); // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; using Mma_tile_o = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_dk = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_v; // K is used like V in fprop // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = Gmem_tile_dq; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store dK. using Gmem_tile_dk = fmha::Gmem_tile_qkv; // The shared memory tile to swizzle dK. using Smem_tile_dk = fmha::Smem_tile_mma_epilogue; static_assert(Smem_tile_dk::NUM_LDS == Gmem_tile_dk::LDGS); static_assert(Smem_tile_dk::THREADS_PER_ROW == Gmem_tile_dk::THREADS_PER_ROW); // The shared memory tile to reload Q transposed. using Smem_tile_qt = fmha::Smem_tile_b; // The global memory tile to load dP, stored in S using Gmem_tile_s = Gmem_tile_mma_s; // The shared memory tile to transpose dP. using Smem_tile_st = Smem_tile_mma_transposed; using Noloop = Noloop_traits; enum { M = Mma_tile_p::MMAS_M }; enum { N = Mma_tile_p::MMAS_N }; static_assert(M == Mma_tile_o::MMAS_M); static_assert(N == Mma_tile_o::MMAS_K); // Shared memory. extern __shared__ char smem_[]; const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q (as B). Smem_tile_qt smem_qt(&smem_[0], tidx); // Allocate the global memory tile loader for dP. Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Allocate the shared memory tile loader for dP. Smem_tile_st smem_s(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE], tidx); Noloop nl_traits(bidc); nl_traits.move_all(gmem_q, gmem_o, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_qt); // Trigger the loads for K. gmem_k.load(smem_k); uint4 s_regs[M][N]; gmem_s.load(s_regs, mask); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_qt); gmem_k.commit(smem_k); // Make sure the data is in shared memory. __syncthreads(); typename Smem_tile_qt::Fragment frag_qt[2][Mma_tile_dk::MMAS_N]; smem_qt.load(frag_qt[0], 0); typename Smem_tile_k::Fragment frag_k[2][Mma_tile_o::MMAS_N]; smem_k.load(frag_k[0], 0); enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; enum { THREADS_PER_ROW = 32 }; // Declare the accumulators for the 2nd gemm. fmha::Fragment_accumulator acc_dk[Mma_tile_dk::MMAS_M][Mma_tile_dk::MMAS_N]; fmha::Clear_accumulator::apply(acc_dk); // Load over the entire sequence length. for(int l=0;l < nl_traits.num_steps_; l++) { // Pack dP as Fragment_a fmha::Fragment_a frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; #pragma unroll for( int mi = 0; mi < M; mi++ ) { #pragma unroll for( int ni = 0; ni < N; ni++ ) { uint4 &dst = s_regs[mi][ni]; frag_p[ni][mi].reg(0) = dst.x; frag_p[ni][mi].reg(1) = dst.z; frag_p[ni][mi].reg(2) = dst.y; frag_p[ni][mi].reg(3) = dst.w; } } smem_s.store(s_regs); if(l < nl_traits.num_steps_- 1) { // Load next part of S gmem_s.move(); gmem_s.load(s_regs, mask); // Trigger the load for the next Q values. smem_qt.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_qt); } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. dQ = dP x dK #pragma unroll for( int ki = 1; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_k.load(frag_k[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_o::MMAS_K; fmha::gemm(acc_o, frag_p[ki - 1], frag_k[(ki - 1) & 1]); } static_assert(Gmem_tile_o::LOOPS == 1); //DEBUG // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); typename Smem_tile_st::Fragment frag_s[Mma_tile_dk::MMAS_K][Mma_tile_dk::MMAS_M]; smem_s.load(frag_s); static_assert(Mma_tile_dk::MMAS_K == 1); // DEBUG #pragma unroll for( int ki = 1; ki < Mma_tile_dk::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_qt.load(frag_qt[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Do the final stage of math. { int ki = Mma_tile_dk::MMAS_K; fmha::gemm(acc_dk, frag_s[(ki - 1)], frag_qt[(ki - 1) & 1]); } // Commit the values for Q into shared memory. if(l < nl_traits.num_steps_- 1) { gmem_q.commit(smem_qt); __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_qt.load(frag_qt[0], 0); smem_k.load(frag_k[0], 0); } } // Outer loop over the sequence length. // Epilogue for dK = dP' * dq. We're fully exposed to this! // Epilogue swizzle for dK Smem_tile_dk smem_dk(&smem_[0], tidx); smem_dk.store(acc_dk); __syncthreads(); uint4 dk_out[Smem_tile_dk::NUM_LDS]; smem_dk.load(dk_out); Qkv_params dk_params; dk_params.qkv_ptr = params.dkv_ptr; dk_params.qkv_stride_in_bytes = params.h * 2 * CHUNKS * params.d * sizeof(half); dk_params.h = params.h; Gmem_tile_dk gmem_dk(dk_params, nl_traits.get_idx_dk(), binfo, tidx); gmem_dk.store(dk_out); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_128_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" using Kernel_traits = FMHA_kernel_traits< 128, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_128_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_128_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_128_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_128_64_sm80_train_kernel : &fmha_fprop_fp16_128_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_256_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" using Kernel_traits = FMHA_kernel_traits< 256, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_256_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_256_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_256_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_256_64_sm80_train_kernel : &fmha_fprop_fp16_256_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_384_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN_reload_v.h" using Kernel_traits = FMHA_kernel_traits< 384, 64, 16, 1, 4, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_384_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_384_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } void run_fmha_fp16_384_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_384_64_sm80_train_kernel : &fmha_fprop_fp16_384_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_v + smem_size_o + smem_size_softmax; if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_fp16_512_64_kernel.sm80.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" #include "fmha_fprop_kernel_1xN.h" #include "fmha_fprop_kernel_1xN_nl.h" using Kernel_traits = FMHA_kernel_traits< 512, 64, 16, 1, 8, 0x08u>; extern "C" __global__ void fmha_fprop_fp16_512_64_sm80_train_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } extern "C" __global__ void fmha_fprop_fp16_512_64_sm80_predict_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN(params); } template __global__ void fmha_fprop_fp16_512_64_sm80_train_nl_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN_nl(params); } template __global__ void fmha_fprop_fp16_512_64_sm80_predict_nl_kernel(Fused_multihead_attention_fprop_params params) { fmha::device_1xN_nl(params); } void run_fmha_fp16_512_64_sm80(const Fused_multihead_attention_fprop_params ¶ms, bool is_training, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_kernel : &fmha_fprop_fp16_512_64_sm80_predict_kernel; constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b); kernel<<>>(params); } void run_fmha_fp16_512_64_sm80_nl(const Fused_multihead_attention_fprop_params ¶ms, const bool is_training, const int num_chunks, cudaStream_t stream) { auto kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<2> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<2>; if( num_chunks == 2 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<2> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<2>; } else if( num_chunks == 3 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<3> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<3>; } else if( num_chunks == 4 ) { kernel = is_training ? &fmha_fprop_fp16_512_64_sm80_train_nl_kernel<4> : &fmha_fprop_fp16_512_64_sm80_predict_nl_kernel<4>; } else { assert(false && "Unsupported num_chunks"); } constexpr int smem_size_softmax = Kernel_traits::Cta_tile_p::M * Kernel_traits::Cta_tile_p::WARPS_N * sizeof(float); constexpr int smem_size_q = Kernel_traits::Smem_tile_q::BYTES_PER_TILE; constexpr int smem_size_v = Kernel_traits::Smem_tile_v::BYTES_PER_TILE; constexpr int smem_size_o = Kernel_traits::Smem_tile_o::BYTES_PER_TILE; constexpr int smem_size = smem_size_q + std::max(smem_size_v, smem_size_o + smem_size_softmax); if( smem_size >= 48 * 1024 ) { FMHA_CHECK_CUDA(cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, smem_size)); } dim3 grid(params.h, params.b, num_chunks); kernel<<>>(params); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); // Make sure the data is in shared memory. __syncthreads(); } // Load the fragments for V. We keep the data in registers during the entire kernel. typename Smem_tile_v::Fragment frag_v[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { smem_v.load(frag_v[ki], ki); } enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax< Cta_tile_p, Kernel_traits>; Softmax softmax(params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); enum { THREADS_PER_ROW = 32 }; enum { STEPS = Cta_tile_p::N / Cta_tile_p::M }; // Load over the entire sequence length. for( int l = 0; l < STEPS; l++ ) { const int loop = l * Cta_tile_p::M; if( loop >= binfo.actual_seqlen ) break; // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Load the mask for that iteration. mask.load(l); // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V && l == 0 ) { // if we share K and V, it could be that V was not fully read yet but we write into smem for reduction __syncthreads(); } // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from // pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } // Trigger the load for the next Q values. if(l < STEPS - 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } using Frag_p = fmha::Fragment_a< fmha::Row>; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { fmha::gemm(acc_o, frag_p[ki], frag_v[ki]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if(l < STEPS - 1) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); // Trigger the loads for the values of Q for the next iteration. smem_q.load(frag_q[0], 0); } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN_nl.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN_nl(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; // The global memory tile to store S/D. using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; using Noloop = Noloop_traits; // Shared memory. extern __shared__ char smem_[]; const int bidc = blockIdx.z; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; Noloop nl_traits(bidc); const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); fmha::Mask mask(params, binfo, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[0], tidx); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_q::BYTES_PER_TILE], tidx); Gmem_tile_s gmem_s(params.s_ptr, params, tidx); nl_traits.move_all(gmem_q, gmem_o, gmem_s); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[2][Mma_tile_p::MMAS_M]; smem_q.load(frag_q[0], 0); // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); // Make sure the data is in shared memory. __syncthreads(); } // Load the fragments for V. We keep the data in registers during the entire kernel. typename Smem_tile_v::Fragment frag_v[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { smem_v.load(frag_v[ki], ki); } enum { BITS_PER_ELT_S = sizeof(fmha::A_type) * 8 }; // Create the object to do the softmax. using Softmax = fmha::Softmax; Softmax softmax(params, &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); // The number of threads per row. enum { THREADS_PER_ROW = 32 }; // Load over the entire sequence length. for(int l = 0; l < nl_traits.num_steps_;l++) { // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); // Do this part of P^T = (Q * K^T)^T. #pragma unroll for( int ki = 1; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[ki & 1], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Do the final stage of math. { int ki = Mma_tile_p::MMAS_K; fmha::gemm(acc_p, frag_q[(ki - 1) & 1], frag_k[(ki - 1)]); } // Trigger the load for the next Q values. if( l < nl_traits.num_steps_- 1) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } // Load the mask for that iteration. mask.load(nl_traits.loop_offset_ + l); // Convert from the accumulator type to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V && l == 0 ) { // if we share K and V, it could be that V was not fully read yet but we write into smem for reduction __syncthreads(); } // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } using Frag_p = fmha::Fragment_a; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); // Do this part of O = P^T * V^T. #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { fmha::gemm(acc_o, frag_p[ki], frag_v[ki]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Make sure the data was read from shared memory. if( ii < Gmem_tile_o::LOOPS - 1 ) { __syncthreads(); } // Output the values. gmem_o.store(out, ii); } // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if( l < nl_traits.num_steps_- 1) { gmem_q.commit(smem_q); __syncthreads(); smem_q.load(frag_q[0], 0); } } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_fprop_kernel_1xN_reload_v.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include "fmha_kernel.h" #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template inline __device__ void device_1xN(const Params ¶ms) { // The description of the CTA tile for the 1st batched GEMM. using Cta_tile_p = typename Kernel_traits::Cta_tile_p; // The description of the CTA tile for the 2nd batched GEMM. using Cta_tile_o = typename Kernel_traits::Cta_tile_o; // The MMA tile for the 1st GEMM. using Mma_tile_p = fmha::Hmma_tile; // The MMA tile for the 2nd GEMM. using Mma_tile_o = fmha::Hmma_tile; // The global memory tile to load Q. using Gmem_tile_q = typename Kernel_traits::Gmem_tile_q; // The shared memory tile to swizzle Q. using Smem_tile_q = typename Kernel_traits::Smem_tile_q; // The global memory tile to load K. using Gmem_tile_k = typename Kernel_traits::Gmem_tile_k; // The shared memory tile to swizzle K. using Smem_tile_k = typename Kernel_traits::Smem_tile_k; // The global memory tile to load V. using Gmem_tile_v = typename Kernel_traits::Gmem_tile_v; // The shared memory tile to swizzle V. using Smem_tile_v = typename Kernel_traits::Smem_tile_v; // The global memory tile to store O. using Gmem_tile_o = typename Kernel_traits::Gmem_tile_o; // The shared memory tile to swizzle O. using Smem_tile_o = typename Kernel_traits::Smem_tile_o; using Gmem_tile_s = typename Kernel_traits::Gmem_tile_s; // Shared memory. extern __shared__ char smem_[]; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.x; // The thread index. const int tidx = threadIdx.x; const BlockInfoPadded binfo(params, bidb, bidh, tidx); if( binfo.stop_early() ) return; Mask mask(params, binfo, tidx); auto seeds = at::cuda::philox::unpack(params.philox_args); Philox ph(std::get<0>(seeds), binfo.tidx_global, std::get<1>(seeds)); static_assert(2 * Mma_tile_p::MMAS_M * 4 * Mma_tile_p::MMAS_N <= 64); // Allocate the global memory tile loader for K. Gmem_tile_k gmem_k(params, 1, binfo, tidx); // Allocate the shared memory tile loader for K. Smem_tile_k smem_k(&smem_[0], tidx); // Allocate the global memory tile loader for V. Gmem_tile_v gmem_v(params, 2, binfo, tidx); // The base pointer of smem_v; char *smem_v_ = nullptr; if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { smem_v_ = &smem_[0]; } else { smem_v_ = &smem_[Smem_tile_q::BYTES_PER_TILE + Smem_tile_k::BYTES_PER_TILE]; } static_assert(Kernel_traits::SHARE_SMEM_FOR_K_AND_V); static_assert(Smem_tile_k::BYTES_PER_TILE == Smem_tile_v::BYTES_PER_TILE); // Allocate the shared memory tile loader for V. We use the same as K so be careful!!! Smem_tile_v smem_v(smem_v_, tidx); // Allocate the global memory tile loader for Q. Gmem_tile_q gmem_q(params, 0, binfo, tidx); // Allocate the shared memory tile loader for Q. Smem_tile_q smem_q(&smem_[Smem_tile_v::BYTES_PER_TILE], tidx); // Allocate the global memory tile loader for O. Gmem_tile_o gmem_o(params, binfo, tidx); // Allocate the shared memory tile loader for O. We use the same as K so be careful!!! Smem_tile_o smem_o(&smem_[Smem_tile_v::BYTES_PER_TILE], tidx); // Trigger the loads for Q. gmem_q.load(smem_q); // Trigger the loads for K. gmem_k.load(smem_k); // Trigger the loads for K. gmem_v.load(smem_v); // Commit the data for Q and K to shared memory. gmem_q.commit(smem_q); gmem_k.commit(smem_k); // Commit the data for V to shared memory. if( !Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { gmem_v.commit(smem_v); } // Make sure the data is in shared memory. __syncthreads(); // Load the fragments for Q. typename Smem_tile_q::Fragment frag_q[1][Mma_tile_p::MMAS_M]; // Load the fragments for K. We keep the data in registers during the entire kernel. typename Smem_tile_k::Fragment frag_k[Mma_tile_p::MMAS_K][Mma_tile_p::MMAS_N]; #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { smem_k.load(frag_k[ki], ki); } // Commit the data for V to shared memory if it has not been done already. if( Kernel_traits::SHARE_SMEM_FOR_K_AND_V ) { // Make sure we are done loading the fragments for K. __syncthreads(); // Commit the data to shared memory for V. gmem_v.commit(smem_v); } enum { BITS_PER_ELT_S = sizeof(typename fmha::A_type) * 8 }; Gmem_tile_s gmem_s(params.s_ptr, params, tidx); // Create the object to do the softmax. using Softmax = fmha::Softmax< Cta_tile_p, Kernel_traits>; Softmax softmax(params, &smem_[Smem_tile_v::BYTES_PER_TILE + Smem_tile_o::BYTES_PER_TILE], bidb, tidx); constexpr int SMEM_BYTES_SOFTMAX = Softmax::ELEMENTS * sizeof(float); static_assert(SMEM_BYTES_SOFTMAX == Cta_tile_p::M * Cta_tile_p::WARPS_N * sizeof(float)); enum { THREADS_PER_ROW = 32 }; const float pinv = 1.f / params.p_dropout; // Load over the entire sequence length. for( int loop = 0, outer = 0; loop < Cta_tile_p::N; loop += Cta_tile_p::M, outer++ ) { if( loop >= binfo.actual_seqlen ) break; // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_p[Mma_tile_p::MMAS_M][Mma_tile_p::MMAS_N]; fmha::Clear_accumulator::apply(acc_p); #pragma unroll for( int ki = 0; ki < Mma_tile_p::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of Q values. smem_q.load(frag_q[0], ki); // Do the math for the values already in registers. fmha::gemm(acc_p, frag_q[0], frag_k[ki]); } // Load the mask for that iteration. mask.load(outer); // Convert from the accumulator typ e to FP32 for Softmax. softmax.unpack(acc_p); // Apply the mask. softmax.apply_mask(mask); static_assert(2 * Mma_tile_p::MMAS_M * 4 * Mma_tile_p::MMAS_N <= 64); // Compute the max. float p_max[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_max); // Make sure we are done reading shared memory. __syncthreads(); // Compute the exponential value. softmax.apply_exp(p_max); // Compute the sum. float p_sum[Mma_tile_p::MMAS_M * 2]; softmax.template reduce(p_sum); // Finalize softmax on the accumulators of P^T. softmax.scale(p_sum); __syncthreads(); if( Is_training ) { auto encode_dropout = [](bool keep, float val) { return keep ? val : -val; }; #pragma unroll for( int mi = 0; mi < Mma_tile_p::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < 2; ii++ ) { #pragma unroll for( int ni = 0; ni < Mma_tile_p::MMAS_N; ni++ ) { float4 tmp = uniform4(ph()); // We encode the dropout pattern in the sign bit of the non-negative softmax to distinguish from // pre-existing zeros softmax.elt_[2 * mi + ii][4 * ni + 0] = encode_dropout(tmp.x <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 0]); softmax.elt_[2 * mi + ii][4 * ni + 1] = encode_dropout(tmp.y <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 1]); softmax.elt_[2 * mi + ii][4 * ni + 2] = encode_dropout(tmp.z <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 2]); softmax.elt_[2 * mi + ii][4 * ni + 3] = encode_dropout(tmp.w <= params.p_dropout, softmax.elt_[2 * mi + ii][4 * ni + 3]); } } } gmem_s.store(softmax.elt_, mask); gmem_s.move(); } // Trigger the load for the next Q values. if( loop + Cta_tile_p::M < Cta_tile_p::N ) { smem_q.move_to_next_write_buffer(); gmem_q.move(); gmem_q.load(smem_q); } typename Smem_tile_v::Fragment frag_v[1][Mma_tile_o::MMAS_N]; using Frag_p = fmha::Fragment_a< fmha::Row>; Frag_p frag_p[Mma_tile_o::MMAS_K][Mma_tile_o::MMAS_M]; softmax.pack(frag_p); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ki++ ) { #pragma unroll for( int mi = 0; mi < Mma_tile_o::MMAS_M; mi++ ) { #pragma unroll for( int ii = 0; ii < Frag_p::NUM_REGS; ii++ ) { //"Apply" the dropout. frag_p[ki][mi].reg(ii) = fmha::hmul2(frag_p[ki][mi].reg(ii), params.scale_dropout); frag_p[ki][mi].reg(ii) = fmha::hrelu2(frag_p[ki][mi].reg(ii)); } } } // Declare the accumulators for the 1st gemm. fmha::Fragment_accumulator acc_o[Mma_tile_o::MMAS_M][Mma_tile_o::MMAS_N]; fmha::Clear_accumulator::apply(acc_o); #pragma unroll for( int ki = 0; ki < Mma_tile_o::MMAS_K; ++ki ) { // Trigger the load from shared memory for the next series of V values. smem_v.load(frag_v[0], ki); // Do the math for the values already in registers. fmha::gemm(acc_o, frag_p[ki], frag_v[0]); } // Loop over MMAS_M. #pragma unroll for( int ii = 0; ii < Gmem_tile_o::LOOPS; ++ii ) { // Swizzle the elements and do the final reduction. smem_o.store(acc_o, ii); // Make sure the data is in shared memory. __syncthreads(); // Load from shared memory. uint4 out[Gmem_tile_o::STGS_PER_LOOP]; smem_o.load(out); // Always sync after last iter: shared smem_q and smem_o! __syncthreads(); // Output the values. gmem_o.store(out, ii); } // same smem as o // Move to the next part of the output. gmem_o.move(); // Commit the values for Q into shared memory. if( loop + Cta_tile_p::M < Cta_tile_p::N ) { gmem_q.commit(smem_q); } // Make sure the data is in shared memory. __syncthreads(); } // Outer loop over the sequence length. } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_kernel.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include #include #include namespace fmha { //////////////////////////////////////////////////////////////////////////////////////////////////// template struct BlockInfoPadded { template __device__ BlockInfoPadded(const Params ¶ms, const int bidb, const int bidh, const int tidx) : bidb(bidb), bidh(bidh), h(params.h) { // The block index. sum_s = params.cu_seqlens[bidb]; actual_seqlen = params.cu_seqlens[bidb + 1] - sum_s; bidx = sum_s * params.h + bidh; tidx_global = (bidb * params.h + bidh) * THREADS_PER_CTA + tidx; } __device__ bool stop_early() const { return actual_seqlen == 0; } int actual_seqlen; int bidx; int sum_s; int bidh; int bidb; int tidx_global; int h; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Noloop_traits{ // Interpretation of Cta_tile dims, i.e. Cta_tile_p: enum{ STEP = Cta_tile::M }; enum{ SEQLEN = Cta_tile::N }; // The size of the subsequence this CTA is processing enum { SUBSEQ = SEQLEN / CHUNKS }; static_assert(SUBSEQ * CHUNKS == SEQLEN); // The number of steps to process the subsequence enum { NUM_STEPS = SUBSEQ / STEP }; static_assert(NUM_STEPS * Cta_tile::M == SUBSEQ); inline __device__ Noloop_traits(const int bidc) : loop_offset_(NUM_STEPS * bidc) , bidc_(bidc) { } template inline __device__ void move_all(Tiles & ... tiles) const { using expand_type = int[]; for( int s = 0; s < loop_offset_; s++ ) { expand_type{ (tiles.move(), 0)... }; } } inline __device__ int get_idx_dk() const { //return bidc_; return bidc_ * 2 + 0; } inline __device__ int get_idx_dv() const { //return CHUNKS + bidc_; return bidc_ * 2 + 1; } inline __device__ int offset_loop_count(const int l) { // convert loop counter to position in the outer sequence return (loop_offset_ + l) * STEP; } const int loop_offset_; const uint32_t bidc_; const int num_steps_ = NUM_STEPS; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template struct Noloop_traits<3, Cta_tile>{ // Interpretation of Cta_tile dims, i.e. Cta_tile_p: enum{ STEP = Cta_tile::M }; enum{ SEQLEN = Cta_tile::N }; static_assert(STEP == 16 && SEQLEN == 512); inline __device__ Noloop_traits(const int bidc) : bidc_(bidc) , num_steps_(bidc < 2 ? 11 : 10) , loop_offset_(bidc * 11) { } template inline __device__ void move_all(Tiles & ... tiles) const { using expand_type = int[]; for( int s = 0; s < loop_offset_; s++ ) { expand_type{ (tiles.move(), 0)... }; } } inline __device__ int get_idx_dk() const { //return bidc_; return bidc_ * 2 + 0; } inline __device__ int get_idx_dv() const { //return CHUNKS + bidc_; return bidc_ * 2 + 1; } inline __device__ int offset_loop_count(const int l) { // convert loop counter to position in the outer sequence return (loop_offset_ + l) * STEP; } const int loop_offset_; const uint32_t bidc_; const int num_steps_; }; //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace fmha ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_noloop_reduce.cu ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #include "fmha.h" inline __device__ float4 ldg128(const void *ptr) { return *static_cast(ptr); } inline __device__ void stg128(void *ptr, const float4 &data) { *static_cast(ptr) = data; } template __global__ __launch_bounds__(THREADS) void fmha_noloop_reduce_kernel(void *__restrict__ out, const void *__restrict__ in, const int *__restrict__ cu_seqlens, const int batch_size) { enum { BYTES_PER_LDG = 16 }; enum { NUM_ELTS = BYTES_PER_LDG / sizeof(T) }; // One CTA hidden vector for K and V enum { BYTES_PER_ROW = HIDDEN_SIZE * sizeof(T) * 2 }; // The stride in bytes in dQKV enum { OUT_STRIDE_BYTES = 3 * HIDDEN_SIZE * sizeof(T) }; // The offset in bytes in dQKV to the dKV part for non-interleaved heads enum { OUT_OFFSET_KV_BYTES = HIDDEN_SIZE * sizeof(T) }; static_assert(BYTES_PER_ROW == HIDDEN_SIZE * 2 * sizeof(T)); // Size in bytes of the input tile enum { BYTES_PER_TILE = CHUNKS * BYTES_PER_ROW }; enum { BYTES_PER_CTA = THREADS * BYTES_PER_LDG }; enum { LDGS = BYTES_PER_ROW / BYTES_PER_CTA }; static_assert(BYTES_PER_CTA * LDGS == BYTES_PER_ROW); union Vec_t { float4 raw; T elt[NUM_ELTS]; }; // ZERO-OUT invalid positions in dQKV const int total = cu_seqlens[batch_size]; if(blockIdx.x >= total){ enum { BYTES_PER_QKV_ROW = 3 * HIDDEN_SIZE * sizeof(T) }; enum { STGS = BYTES_PER_QKV_ROW / BYTES_PER_LDG }; const float4 zeros = make_float4(0.f, 0.f, 0.f, 0.f); char *base_ptr = static_cast(out) + blockIdx.x * OUT_STRIDE_BYTES; for(int tidx = threadIdx.x; tidx < STGS; tidx += THREADS){ stg128(base_ptr + tidx * BYTES_PER_LDG, zeros); } return; } // SETUP const int offset_in = blockIdx.x * BYTES_PER_TILE + threadIdx.x * BYTES_PER_LDG; const char *ptr_in = static_cast(in) + offset_in; const int offset_out = blockIdx.x * OUT_STRIDE_BYTES + threadIdx.x * BYTES_PER_LDG; char *ptr_out = static_cast(out) + OUT_OFFSET_KV_BYTES + offset_out; // LOAD Vec_t local_in[CHUNKS][LDGS]; #pragma unroll for( int c = 0; c < CHUNKS; c++ ) { #pragma unroll for( int l = 0; l < LDGS; l++ ) { int offset = c * BYTES_PER_ROW + l * BYTES_PER_CTA; local_in[c][l].raw = ldg128(ptr_in + offset); } } // UNPACK float acc[LDGS][NUM_ELTS]; #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { acc[l][e] = float(local_in[0][l].elt[e]); } } // COMPUTE #pragma unroll for( int c = 1; c < CHUNKS; c++ ) { #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { acc[l][e] += float(local_in[c][l].elt[e]); } } } // PACK Vec_t local_out[LDGS]; #pragma unroll for( int l = 0; l < LDGS; l++ ) { #pragma unroll for( int e = 0; e < NUM_ELTS; e++ ) { local_out[l].elt[e] = T(acc[l][e]); } } // STORE #pragma unroll for( int l = 0; l < LDGS; l++ ) { const int offset = l * BYTES_PER_CTA; stg128(ptr_out + offset, local_out[l].raw); } } void fmha_run_noloop_reduce(void *out, const void *in, const int *cu_seqlens, const int hidden_size, const int batch_size, const int total, const int num_chunks, cudaStream_t stream) { const int blocks = total; if(hidden_size == 1024){ constexpr int HIDDEN_SIZE = 1024; constexpr int THREADS = 256; if( num_chunks == 2 ) { fmha_noloop_reduce_kernel<<>>(out, in, cu_seqlens, batch_size); } else if( num_chunks == 3 ) { fmha_noloop_reduce_kernel<<>>(out, in, cu_seqlens, batch_size); } else { assert(false && "Unsupported num_chunks"); } }else{ assert(false && "Unsupported hidden_size"); } FMHA_CHECK_CUDA(cudaPeekAtLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/fmha/src/fmha_utils.h ================================================ /****************************************************************************** * Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ******************************************************************************/ #pragma once #include #include #include #include #include //////////////////////////////////////////////////////////////////////////////////////////////////// #define FMHA_CHECK_CUDA( call ) \ do { \ cudaError_t status_ = call; \ if( status_ != cudaSuccess ) { \ fprintf( stderr, \ "CUDA error (%s:%d): %s\n", \ __FILE__, \ __LINE__, \ cudaGetErrorString( status_ ) ); \ exit( 1 ); \ } \ } while( 0 ) //////////////////////////////////////////////////////////////////////////////////////////////////// enum Data_type { DATA_TYPE_FP16, DATA_TYPE_FP32, DATA_TYPE_INT32, DATA_TYPE_INT8 }; //////////////////////////////////////////////////////////////////////////////////////////////////// static inline void set_alpha( uint32_t &alpha, float norm, Data_type dtype ) { if( dtype == DATA_TYPE_FP16 ) { half x = __float2half_rn( norm ); uint16_t h = reinterpret_cast( x ); ushort2 h2 = { h, h }; alpha = reinterpret_cast( h2 ); } else if( dtype == DATA_TYPE_FP32 ) { alpha = reinterpret_cast( norm ); } else if( dtype == DATA_TYPE_INT32 ) { int32_t inorm = static_cast( norm ); alpha = reinterpret_cast( inorm ); } else { assert( false ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// static inline size_t get_size_in_bytes( size_t n, Data_type dtype ) { switch( dtype ) { case DATA_TYPE_FP32: return n * 4; case DATA_TYPE_FP16: return n * 2; case DATA_TYPE_INT32: return n * 4; case DATA_TYPE_INT8: return n; default: assert( false ); return 0; } } //////////////////////////////////////////////////////////////////////////////////////////////////// ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/batch_norm.cu ================================================ #include #include #include #include "THC/THC.h" #include "batch_norm.h" #include #include "compat.h" #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) static size_t round_up_to_multiple(size_t x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; } // TODO: Stop manually allocating CUDA memory; allocate an ATen byte // tensor instead. struct Workspace { Workspace(size_t size) : size(size), data(NULL) { data = THCudaMalloc(at::globalContext().lazyInitCUDA(), size); } Workspace(const Workspace&) = delete; Workspace(Workspace&&) = default; Workspace& operator=(Workspace&&) = default; ~Workspace() { if (data) { THCudaFree(at::globalContext().lazyInitCUDA(), data); } } size_t size; void* data; }; // Return {y} at::Tensor nhwc_bn_fwd_train( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwd(stream, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return y; } at::Tensor nhwc_bn_fwd_eval( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon, const bool fuse_relu) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(nullptr); workspace.push_back(nullptr); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwdInference(stream, fuse_relu); return y; } std::vector nhwc_bn_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { // shape const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // outputs at::Tensor x_grad, scale_grad, bias_grad; // Allocate outputs x_grad = at::empty_like(x); scale_grad = at::empty_like(scale); bias_grad = at::empty_like(bias); // Create wrapper NhwcBatchNorm *bn = new NhwcBatchNorm(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), x_grad.DATA_PTR(), nullptr, dy.DATA_PTR()); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {scale_grad.DATA_PTR(), bias_grad.DATA_PTR()}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 3; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[2]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 3; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-3]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); bn->dgrad(stream, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return std::vector{x_grad, scale_grad, bias_grad}; } int nhwc_bn_fwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNorm::smem_driven_fwd_occupancy(device_id, 2); } int nhwc_bn_bwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNorm::smem_driven_bwd_occupancy(device_id, 2); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/batch_norm.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm.h * \brief CUDA NHWC Batch Normalization code * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ #include #include #include #include #include "nhwc_batch_norm_kernel.h" #include "cuda_utils.h" #define VERBOSE_DEFAULT false class NhwcBatchNorm { public: NhwcBatchNorm() { name_ = "nhwc_batchnorm"; createTensorDescriptor(&X_tensor_desc_); createTensorDescriptor(&Y_tensor_desc_); } ~NhwcBatchNorm() { destroyTensorDescriptor(X_tensor_desc_); destroyTensorDescriptor(Y_tensor_desc_); } void die() { std::cerr << "batchnorm not initialized" << std::endl; exit(-1); } void fwd(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void dgrad(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void fwdInference(cudaStream_t stream, bool use_relu); dim3 calc_fwd_grid(int *loop, const int grid_dim_x); dim3 calc_bwd_grid(int *loop, const int grid_dim_x); void setInputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w, int bn_group) { m_ = n * h * w; int m_bn_adjusted = m_ * bn_group; c_ = c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. svar_inv_count_ = 1.f / m_bn_adjusted; // factor to scale sum of squared errors to get running variance. Should be 1/(nhw-1). int divisor = m_bn_adjusted - 1; // nhw == 1 is unlikely, but by setting the rvar_inv_count_ == 1.f, we avoid running var infs. rvar_inv_count_ = divisor == 0 ? 1.f : 1.f / divisor; setTensorDescriptor(X_tensor_desc_, format, data_type, n, c, h, w); } void setOutputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w) { setTensorDescriptor(Y_tensor_desc_, format, data_type, n, c, h, w); } const std::vector numWorkspaceBytes() const; void setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes); void setInputOutputPointers(void* X, void* dX, void* Y, void *dY) { X_ = X; dX_ = dX; Y_ = Y; dY_ = dY; } // Sets the pointers for the scale and weight (in that order) data and derivative buffers. void setWeightPointers(const std::vector& weight_pointers, const std::vector& deriv_pointers) { assert(weight_pointers.size() == 2); assert(deriv_pointers.size() == 2); scale_ = static_cast(weight_pointers[0]); bias_ = static_cast(weight_pointers[1]); dscale_ = static_cast(deriv_pointers[0]); dbias_ = static_cast(deriv_pointers[1]); } // Sets the pointers for the population mean and variance buffers, in that order. void setParameterPointers(const std::vector& param_pointers) { assert(param_pointers.size() == 2); population_mean_ = static_cast(param_pointers[0]); population_variance_ = static_cast(param_pointers[1]); } void setConstants(const double exp_avg_factor, const double eps) { exp_avg_factor_ = exp_avg_factor; eps_ = eps; } void processCudnnStatus(const cudnnStatus_t& status, const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { if (status != CUDNN_STATUS_SUCCESS) LOG(FATAL) << string << " " << cudnnGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudnnGetErrorString(status); } void checkCudaStatus(const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { cudaError_t status = cudaGetLastError(); if (status != cudaSuccess) LOG(FATAL) << string << " " << cudaGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudaGetErrorString(status); } size_t size_retired_ctas(int grid_y) const { // Note that the value of max_grid_y to handle known GPUs is about 160. const int max_grid_y = 1024; if (grid_y > max_grid_y) LOG(INFO) << "GPU capabilities exceeds assumptions."; const int retired_cta_bytes = max_grid_y * 2 * sizeof(int); // Since the region will be initialized once and used for many kernels, // the idea is to return an ample size that will cover all uses. return retired_cta_bytes; } cudnnTensorDescriptor_t X_tensor_desc_ = nullptr; cudnnTensorDescriptor_t Y_tensor_desc_ = nullptr; void* X_ = nullptr; void* dX_ = nullptr; void* Y_ = nullptr; void* dY_ = nullptr; // Learned scale and bias weights. float* scale_ = nullptr; float* dscale_ = nullptr; float* bias_ = nullptr; float* dbias_ = nullptr; // Computed population mean and variance parameters. float* population_mean_ = nullptr; float* population_variance_ = nullptr; // Workspace buffers for minibatch mean and variance (computed in fwd, needed by bwd). float* minibatch_mean_ = nullptr; float* minibatch_variance_ = nullptr; int m_ = 0; // Number of values per channel that BN is normalizing. int c_ = 0; // Number of channels over which BN is normalizing. float svar_inv_count_ = 0.f; // factor to scale sum of squared errors to get saved variance float rvar_inv_count_ = 0.f; // factor to scale sum of squared errors to get running variance double exp_avg_factor_ = 0.; double eps_ = 0.; std::string name_; private: void setTensorDescriptor(cudnnTensorDescriptor_t descriptor, cudnnTensorFormat_t format, cudnnDataType_t data_type, int n, int c, int h, int w) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnSetTensor4dDescriptor(descriptor, format, data_type, n, c, h, w); processCudnnStatus(status, "set tensor descriptor"); } void createTensorDescriptor(cudnnTensorDescriptor_t *descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnCreateTensorDescriptor(descriptor); processCudnnStatus(status, "create tensor_descriptor"); } void destroyTensorDescriptor(cudnnTensorDescriptor_t descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnDestroyTensorDescriptor(descriptor); processCudnnStatus(status, "destroy tensor_descriptor"); } protected: float *partial_sums_ = nullptr; int *partial_counts_ = nullptr; int *retired_ctas_ = nullptr; void _setFwdParams(NhwcBatchNormFwdParams *params) const; void _setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const; void _setBwdParams(NhwcBatchNormBwdParams *params) const; // @todo: ability to configure these? // Kernel params static const int USE_ONLINE_APPROACH = 1; static const int THREADS_PER_CTA = 512; static const int THREADS_PER_PIXEL = 16; static const int C_ELEMENTS_PER_CTA = 64; static const int ELEMENTS_PER_LDG = C_ELEMENTS_PER_CTA / THREADS_PER_PIXEL; static const int MAX_SMEM_WITHOUT_OPT_IN = 48 * 1024; typedef uint16_t StorageType; //typedef float StorageType; // increasing this to 6 causes spills in fwd kernel! static const int PIXELS_PER_THREAD_IN_REGISTERS_FWD = 5; static const int PIXELS_PER_THREAD_IN_REGISTERS_BWD = 3; static const int PIXELS_PER_THREAD_IN_SMEM_FWD = 10; static const int PIXELS_PER_THREAD_IN_SMEM_BWD = 5; static const int PIXELS_PER_THREAD_FWD = PIXELS_PER_THREAD_IN_REGISTERS_FWD + \ PIXELS_PER_THREAD_IN_SMEM_FWD; static const int PIXELS_PER_THREAD_BWD = PIXELS_PER_THREAD_IN_REGISTERS_BWD + \ PIXELS_PER_THREAD_IN_SMEM_BWD; static const int PIXELS_PER_THREAD_FWD_INFERENCE = 4; // Derived params static const size_t SMEM_SIZE_FWD = PIXELS_PER_THREAD_IN_SMEM_FWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*sizeof(StorageType); static const size_t SMEM_SIZE_BWD = PIXELS_PER_THREAD_IN_SMEM_BWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*2*sizeof(StorageType); static const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; static const int PIXELS_PER_CTA_FWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD; static const int PIXELS_PER_CTA_BWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_BWD; static const int PIXELS_PER_CTA_FWD_INFERENCE = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD_INFERENCE; // max grid.y in case of group bn is limited by exchange buffer size static const int MAX_GBN_BLOCK_Y = 256; // Helper function to launch the forward kernel. // We calculate (based on smem usage) the achievable occupancy and make sure we run a kernel // version that was compiled with that occupancy in its launch bounds. This way, we avoid // needless register spills. void _fwdKernelLauncher(cudaStream_t stream, NhwcBatchNormFwdParams params, dim3 grid_dim, int outer_loops, bool use_relu, const int occupancy, const bool coop) { #define LAUNCH_FWD_KERNEL(OUTER_LOOPS, USE_RELU, USE_ADD_RELU, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_FWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto fwd_func = nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(fwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " fwd ser coop kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using FWD_FUNC = decltype(nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } else { \ cudaLaunchKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } \ checkCudaStatus(name_ + " fwd ser coop kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1 && use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, true, false, 2, coop); else LAUNCH_FWD_KERNEL(1, true, false, 1, coop); } else if (outer_loops == 1 && !use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, false, false, 2, coop); else LAUNCH_FWD_KERNEL(1, false, false, 1, coop); } else if (use_relu) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, true, false, 2, coop); else LAUNCH_FWD_KERNEL(0, true, false, 1, coop); } else { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, false, false, 2, coop); else LAUNCH_FWD_KERNEL(0, false, false, 1, coop); } #undef LAUNCH_FWD_KERNEL } // Helper function to launch the backward kernel. void _bwdKernelLauncher(cudaStream_t stream, NhwcBatchNormBwdParams params, dim3 grid_dim, int outer_loops, bool use_relu, const int occupancy, const bool coop) { #define LAUNCH_BWD_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto bwd_func = nhwc_batch_norm_bwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " bwd coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_FUNC = decltype(nhwc_batch_norm_bwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd coop serial kernel"); \ } while (0) #define LAUNCH_BWD_RELU_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << "Nhwc batchnorm kernel smem too big."; \ auto bwd_relu_func = nhwc_batch_norm_bwd_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_relu_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " bwd-relu coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_RELU_FUNC = decltype(nhwc_batch_norm_bwd_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd-relu coop serial kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1 && use_relu) { if (occupancy >= 2) LAUNCH_BWD_RELU_KERNEL(1, 2, coop); else LAUNCH_BWD_RELU_KERNEL(1, 1, coop); } else if (outer_loops == 1 && !use_relu) { if (occupancy >= 2) LAUNCH_BWD_KERNEL(1, 2, coop); else LAUNCH_BWD_KERNEL(1, 1, coop); } else if (use_relu) { if (occupancy >= 2) LAUNCH_BWD_RELU_KERNEL(0, 2, coop); else LAUNCH_BWD_RELU_KERNEL(0, 1, coop); } else { if (occupancy >= 2) LAUNCH_BWD_KERNEL(0, 2, coop); else LAUNCH_BWD_KERNEL(0, 1, coop); } #undef LAUNCH_BWD_KERNEL } public: // Calculate the expected fwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_fwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int fwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int fwd_smem_bytes = SMEM_SIZE_FWD + fwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / fwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } // Calculate the expected bwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_bwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int bwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int bwd_smem_bytes = SMEM_SIZE_BWD + bwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / bwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } }; const std::vector NhwcBatchNorm::numWorkspaceBytes() const { assert(c_ > 0); // choose the max memory required between fwd/bwd passes int grid_x_fwd = div_up(m_, PIXELS_PER_CTA_FWD); int grid_x_bwd = div_up(m_, PIXELS_PER_CTA_BWD); int grid_x = max(grid_x_fwd, grid_x_bwd); int grid_y = div_up(c_, C_ELEMENTS_PER_CTA); const size_t num_mean_bytes = c_ * sizeof(float); const size_t num_variance_bytes = num_mean_bytes; const size_t size_sums = grid_y*grid_x*THREADS_PER_PIXEL*\ ELEMENTS_PER_LDG*2*sizeof(float); const size_t size_counts = grid_y*grid_x*sizeof(int); return {num_mean_bytes, num_variance_bytes, size_retired_ctas(grid_y), size_sums, size_counts}; } void NhwcBatchNorm::setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes) { assert(workspace.size() == 5); assert(num_workspace_bytes.size() == 5); minibatch_mean_ = static_cast(workspace[0]); minibatch_variance_ = static_cast(workspace[1]); retired_ctas_ = static_cast(workspace[2]); partial_sums_ = static_cast(workspace[3]); partial_counts_ = static_cast(workspace[4]); } void NhwcBatchNorm::_setFwdParams(NhwcBatchNormFwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = nullptr; params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_running_mean = population_mean_; params->gmem_running_var = population_variance_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->gmem_relu_bitmask = nullptr; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->rvar_inv_count = rvar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_counts = partial_counts_; params->gmem_retired_ctas = retired_ctas_; params->var_eps = eps_; params->outer_loops = 0; params->exp_avg_factor = static_cast(exp_avg_factor_); params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNorm::_setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = nullptr; params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_mean = population_mean_; params->gmem_var = population_variance_; params->nhw = m_; params->c = c_; params->var_eps = eps_; } void NhwcBatchNorm::_setBwdParams(NhwcBatchNormBwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dy = static_cast(dY_); params->gmem_dst = static_cast(dX_); params->gmem_dst1 = nullptr; params->gmem_relu_bitmask = nullptr; params->gmem_dscale = dscale_; params->gmem_dbias = dbias_; params->gmem_scale = scale_; params->gmem_bias = bias_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_retired_ctas = retired_ctas_; params->outer_loops = 0; params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNorm::fwdInference(cudaStream_t stream, bool use_relu) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr // && minibatch_mean_ != nullptr // && minibatch_variance_ != nullptr && population_mean_ != nullptr && population_variance_ != nullptr && X_ != nullptr // && dX_ != nullptr && Y_ != nullptr // && dY_ != nullptr // && dscale_ != nullptr // && dbias_ != nullptr && partial_sums_ != nullptr && partial_counts_ != nullptr; if (!ptrs_are_set) die(); dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD_INFERENCE); grid_dim.y = div_up(c_, C_ELEMENTS_PER_CTA); // @todo: maybe just move this inside initialize routine? NhwcBatchNormFwdInferenceParams params; _setFwdInferenceParams(¶ms); if (use_relu) { nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference-relu kernel"); } else { nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference kernel"); } } dim3 NhwcBatchNorm::calc_fwd_grid(int *loop, const int grid_dim_x) { dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD); int c_blks = div_up(c_, C_ELEMENTS_PER_CTA); unsigned int max_grid_x = grid_dim_x; if (grid_dim.x <= max_grid_x) { *loop = 1; if (max_grid_x / grid_dim.x > 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y> 1); dim3 grid_dim = calc_fwd_grid(¶ms.outer_loops, grid_dim_x); _fwdKernelLauncher(stream, params, grid_dim, params.outer_loops, use_relu, occupancy, coop); } void NhwcBatchNorm::dgrad(cudaStream_t stream, bool use_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && (bias_ != nullptr || !use_relu) && minibatch_mean_ != nullptr && minibatch_variance_ != nullptr // && population_mean_ != nullptr // && population_variance_ != nullptr && X_ != nullptr && dX_ != nullptr // && Y_ != nullptr && dY_ != nullptr && dscale_ != nullptr && dbias_ != nullptr; if (!ptrs_are_set) die(); // reset of retired_cta_count no longer needed NhwcBatchNormBwdParams params; _setBwdParams(¶ms); params.my_data = my_data; params.pair_datas[0] = pair_data; params.pair_datas[1] = pair_data2; params.pair_datas[2] = pair_data3; params.magic = magic; params.sync_iters = (bn_group==8)?3:(bn_group >> 1); params.wgrad_coeff = 1.0 / bn_group; dim3 grid_dim = calc_bwd_grid(¶ms.outer_loops, grid_dim_x); _bwdKernelLauncher(stream, params, grid_dim, params.outer_loops, use_relu, occupancy, coop); } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_H_ ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/batch_norm_add_relu.cu ================================================ #include #include #include #include "THC/THC.h" #include "batch_norm_add_relu.h" #include #include "compat.h" //FIXME move the common stuff to common h file #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) static size_t round_up_to_multiple(size_t x, int multiple) { return ((x + multiple - 1) / multiple) * multiple; } // TODO: Stop manually allocating CUDA memory; allocate an ATen byte // tensor instead. struct Workspace { Workspace(size_t size) : size(size), data(NULL) { data = THCudaMalloc(at::globalContext().lazyInitCUDA(), size); } Workspace(const Workspace&) = delete; Workspace(Workspace&&) = default; Workspace& operator=(Workspace&&) = default; ~Workspace() { if (data) { THCudaFree(at::globalContext().lazyInitCUDA(), data); } } size_t size; void* data; }; // Return {y} at::Tensor nhwc_bn_addrelu_fwd_train( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr, z.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); workspace.push_back(bitmask.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwd(stream, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return y; } at::Tensor nhwc_bn_addrelu_fwd_eval( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon) { const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // Allocate output tensor at::Tensor y = at::empty({N, H, W, C}, x.options()); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), nullptr, y.DATA_PTR(), nullptr, z.DATA_PTR(), nullptr); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {nullptr, nullptr}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(nullptr); workspace.push_back(nullptr); workspace.push_back(nullptr); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); // Don't fuse in ReLU for now at least bn->fwdInference(stream); return y; } std::vector nhwc_bn_addrelu_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void * my_data, void * pair_data, void * pair_data2, void * pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop) { // shape const int N = x.size(0); const int H = x.size(1); const int W = x.size(2); const int C = x.size(3); // generating new magic number and use that for sync int* magic = magic_tensor.DATA_PTR(); *magic = (*magic + 1) & 0xff; // outputs at::Tensor x_grad, z_grad, scale_grad, bias_grad; // Allocate outputs x_grad = at::empty_like(x); z_grad = at::empty_like(x); scale_grad = at::empty_like(scale); bias_grad = at::empty_like(bias); // Create wrapper NhwcBatchNormAddRelu *bn = new NhwcBatchNormAddRelu(); bn->setInputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W, bn_group); bn->setOutputDescriptor(CUDNN_TENSOR_NHWC, CUDNN_DATA_HALF, N, C, H, W); bn->setConstants(momentum, epsilon); // set pointers within the wrapper bn->setInputOutputPointers(x.DATA_PTR(), x_grad.DATA_PTR(), nullptr, dy.DATA_PTR(), nullptr, z_grad.DATA_PTR()); bn->setWeightPointers({scale.DATA_PTR(), bias.DATA_PTR()}, {scale_grad.DATA_PTR(), bias_grad.DATA_PTR()}); bn->setParameterPointers({running_mean.DATA_PTR(), running_inv_var.DATA_PTR()}); // deal with workspace(s) auto workspace_bytes = bn->numWorkspaceBytes(); // We'll create explicit tensors for the first 2 workspace ptrs, then allocate & offset // an allocated workspace for the others size_t total_workspace_bytes = 0; std::vector workspace_offsets; for (auto index = 4; index < workspace_bytes.size(); ++index) { total_workspace_bytes = round_up_to_multiple(total_workspace_bytes, 512); workspace_offsets.push_back(total_workspace_bytes); auto alloc_bytes = workspace_bytes[index]; total_workspace_bytes += alloc_bytes; } // Allocate the workspace Workspace ws(total_workspace_bytes); std::vector workspace; workspace.push_back(minibatch_mean.DATA_PTR()); workspace.push_back(minibatch_inv_var.DATA_PTR()); workspace.push_back(bitmask.DATA_PTR()); auto stream = at::cuda::getCurrentCUDAStream().stream(); const int retired_cta_bytes = workspace_bytes[3]; void* retired_ctas = ret_cta.DATA_PTR(); assert(ret_cta.size(0)>=retired_cta_bytes); workspace.push_back(retired_ctas); for (auto index = 4; index < workspace_bytes.size(); ++index) { void *ptr = reinterpret_cast(ws.data) + workspace_offsets[index-4]; workspace.push_back(ptr); } bn->setWorkspacePointers(workspace, workspace_bytes); bn->dgrad(stream, my_data, pair_data, pair_data2, pair_data3, bn_group, *magic, occupancy, grid_dim_x, coop); return std::vector{x_grad, z_grad, scale_grad, bias_grad}; } int nhwc_bn_addrelu_fwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNormAddRelu::smem_driven_fwd_occupancy(device_id, 2); } int nhwc_bn_addrelu_bwd_occupancy() { int device_id=-1; cudaGetDevice(&device_id); //max occupancy supported by the code is 2 return NhwcBatchNormAddRelu::smem_driven_bwd_occupancy(device_id, 2); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/batch_norm_add_relu.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm_add_relu.h * \brief CUDA NHWC Batch Normalization code with fused addition * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Maxim Milakov, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ #include #include #include #include #include "nhwc_batch_norm_kernel.h" #include "cuda_utils.h" #define VERBOSE_DEFAULT false class NhwcBatchNormAddRelu { public: NhwcBatchNormAddRelu() { name_ = "nhwc_batchnormaddrelu"; createTensorDescriptor(&X_tensor_desc_); createTensorDescriptor(&Y_tensor_desc_); } ~NhwcBatchNormAddRelu() { destroyTensorDescriptor(X_tensor_desc_); destroyTensorDescriptor(Y_tensor_desc_); } void die() { std::cerr << "batchnormaddrelu not initialized" << std::endl; exit(-1); } void fwd(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void dgrad(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop); void fwdInference(cudaStream_t stream); dim3 calc_fwd_grid(int *loop, const int grid_dim_x); dim3 calc_bwd_grid(int *loop, const int grid_dim_x); void setInputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w, int bn_group) { m_ = n * h * w; int m_bn_adjusted = m_ * bn_group; c_ = c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. svar_inv_count_ = 1.f / m_bn_adjusted; // factor to scale sum of squared errors to get running variance. Should be 1/(nhw-1). int divisor = m_bn_adjusted - 1; // nhw == 1 is unlikely, but by setting the rvar_inv_count_ == 1.f, we avoid running var infs. rvar_inv_count_ = divisor == 0 ? 1.f : 1.f / divisor; setTensorDescriptor(X_tensor_desc_, format, data_type, n, c, h, w); } void setOutputDescriptor(const cudnnTensorFormat_t format, const cudnnDataType_t data_type, int n, int c, int h, int w) { setTensorDescriptor(Y_tensor_desc_, format, data_type, n, c, h, w); } const std::vector numWorkspaceBytes() const; void setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes); void setInputOutputPointers(void* X, void* dX, void* Y, void *dY, void* addend, void* dAddend) { X_ = X; dX_ = dX; Y_ = Y; dY_ = dY; addend_ = addend; dAddend_ = dAddend; } // Sets the pointers for the scale and weight (in that order) data and derivative buffers. void setWeightPointers(const std::vector& weight_pointers, const std::vector& deriv_pointers) { assert(weight_pointers.size() == 2); assert(deriv_pointers.size() == 2); scale_ = static_cast(weight_pointers[0]); bias_ = static_cast(weight_pointers[1]); dscale_ = static_cast(deriv_pointers[0]); dbias_ = static_cast(deriv_pointers[1]); } // Sets the pointers for the population mean and variance buffers, in that order. void setParameterPointers(const std::vector& param_pointers) { assert(param_pointers.size() == 2); population_mean_ = static_cast(param_pointers[0]); population_variance_ = static_cast(param_pointers[1]); } void setConstants(const double exp_avg_factor, const double eps) { exp_avg_factor_ = exp_avg_factor; eps_ = eps; } void processCudnnStatus(const cudnnStatus_t& status, const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { if (status != CUDNN_STATUS_SUCCESS) LOG(FATAL) << string << " " << cudnnGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudnnGetErrorString(status); } void checkCudaStatus(const std::string& string = std::string(), bool verbose = VERBOSE_DEFAULT) { cudaError_t status = cudaGetLastError(); if (status != cudaSuccess) LOG(FATAL) << string << " " << cudaGetErrorString(status); else if (verbose) LOG(INFO) << string << " " << cudaGetErrorString(status); } size_t size_retired_ctas(int grid_y) const { // Note that the value of max_grid_y to handle known GPUs is about 160. const int max_grid_y = 1024; if (grid_y > max_grid_y) LOG(INFO) << "GPU capabilities exceeds assumptions."; const int retired_cta_bytes = max_grid_y * 2 * sizeof(int); // Since the region will be initialized once and used for many kernels, // the idea is to return an ample size that will cover all uses. return retired_cta_bytes; } cudnnTensorDescriptor_t X_tensor_desc_ = nullptr; cudnnTensorDescriptor_t Y_tensor_desc_ = nullptr; void* X_ = nullptr; void* dX_ = nullptr; void* Y_ = nullptr; void* dY_ = nullptr; void* addend_ = nullptr; void* dAddend_ = nullptr; // Learned scale and bias weights. float* scale_ = nullptr; float* dscale_ = nullptr; float* bias_ = nullptr; float* dbias_ = nullptr; // Computed population mean and variance parameters. float* population_mean_ = nullptr; float* population_variance_ = nullptr; // Workspace buffers for minibatch mean and variance (computed in fwd, needed by bwd). float* minibatch_mean_ = nullptr; float* minibatch_variance_ = nullptr; int m_ = 0; // Number of values per channel that BN is normalizing. int c_ = 0; // Number of channels over which BN is normalizing. float svar_inv_count_ = 0.f; // factor to scale sum of squared errors to get saved variance float rvar_inv_count_ = 0.f; // factor to scale sum of squared errors to get running variance double exp_avg_factor_ = 0.; double eps_ = 0.; std::string name_; private: void setTensorDescriptor(cudnnTensorDescriptor_t descriptor, cudnnTensorFormat_t format, cudnnDataType_t data_type, int n, int c, int h, int w) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnSetTensor4dDescriptor(descriptor, format, data_type, n, c, h, w); processCudnnStatus(status, "set tensor descriptor"); } void createTensorDescriptor(cudnnTensorDescriptor_t *descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnCreateTensorDescriptor(descriptor); processCudnnStatus(status, "create tensor_descriptor"); } void destroyTensorDescriptor(cudnnTensorDescriptor_t descriptor) { cudnnStatus_t status = CUDNN_STATUS_SUCCESS; status = cudnnDestroyTensorDescriptor(descriptor); processCudnnStatus(status, "destroy tensor_descriptor"); } protected: float *partial_sums_ = nullptr; int *partial_counts_ = nullptr; int *retired_ctas_ = nullptr; unsigned int *relu_bitmask_ = nullptr; void _setFwdParams(NhwcBatchNormFwdParams *params) const; void _setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const; void _setBwdParams(NhwcBatchNormBwdParams *params) const; // @todo: ability to configure these? // Kernel params static const int USE_ONLINE_APPROACH = 1; static const int THREADS_PER_CTA = 512; static const int THREADS_PER_PIXEL = 16; static const int C_ELEMENTS_PER_CTA = 64; static const int ELEMENTS_PER_LDG = C_ELEMENTS_PER_CTA / THREADS_PER_PIXEL; static const int MAX_SMEM_WITHOUT_OPT_IN = 48 * 1024; typedef uint16_t StorageType; // increasing this to 6 causes spills in fwd kernel! static const int PIXELS_PER_THREAD_IN_REGISTERS_FWD = 5; static const int PIXELS_PER_THREAD_IN_REGISTERS_BWD = 3; static const int PIXELS_PER_THREAD_IN_SMEM_FWD = 10; static const int PIXELS_PER_THREAD_IN_SMEM_BWD = 5; static const int PIXELS_PER_THREAD_FWD = PIXELS_PER_THREAD_IN_REGISTERS_FWD + \ PIXELS_PER_THREAD_IN_SMEM_FWD; static const int PIXELS_PER_THREAD_BWD = PIXELS_PER_THREAD_IN_REGISTERS_BWD + \ PIXELS_PER_THREAD_IN_SMEM_BWD; static const int PIXELS_PER_THREAD_FWD_INFERENCE = 4; // Derived params static const size_t SMEM_SIZE_FWD = PIXELS_PER_THREAD_IN_SMEM_FWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*sizeof(StorageType); static const size_t SMEM_SIZE_BWD = PIXELS_PER_THREAD_IN_SMEM_BWD*THREADS_PER_CTA*\ ELEMENTS_PER_LDG*2*sizeof(StorageType); static const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; static const int PIXELS_PER_CTA_FWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD; static const int PIXELS_PER_CTA_BWD = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_BWD; static const int PIXELS_PER_CTA_FWD_INFERENCE = THREADS_PER_CTA/THREADS_PER_PIXEL * \ PIXELS_PER_THREAD_FWD_INFERENCE; // max grid.y in case of group bn is limited by exchange buffer size static const int MAX_GBN_BLOCK_Y = 256; // Helper function to launch the forward kernel. // We calculate (based on smem usage) the achievable occupancy and make sure we run a kernel // version that was compiled with that occupancy in its launch bounds. This way, we avoid // needless register spills. void _fwdKernelLauncher(cudaStream_t stream, NhwcBatchNormFwdParams params, dim3 grid_dim, int outer_loops, const int occupancy, const bool coop) { #define LAUNCH_FWD_KERNEL(OUTER_LOOPS, USE_RELU, USE_ADD_RELU, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_FWD <= MAX_SMEM_WITHOUT_OPT_IN) << \ "Nhwc batchnormaddrelu kernel smem too big."; \ auto fwd_func = nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(fwd_func, cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + " fwd ser coop kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using FWD_FUNC = decltype(nhwc_batch_norm_fwd< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_FWD, \ PIXELS_PER_THREAD_IN_SMEM_FWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ USE_RELU, \ USE_ADD_RELU, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } else { \ cudaLaunchKernel(fwd_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_FWD, \ stream); \ } \ checkCudaStatus(name_ + " fwd ser coop kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1) { if (occupancy >= 2) LAUNCH_FWD_KERNEL(1, false, true, 2, coop); else LAUNCH_FWD_KERNEL(1, false, true, 1, coop); } else { if (occupancy >= 2) LAUNCH_FWD_KERNEL(0, false, true, 2, coop); else LAUNCH_FWD_KERNEL(0, false, true, 1, coop); } #undef LAUNCH_FWD_KERNEL } // Helper function to launch the backward kernel. void _bwdKernelLauncher(cudaStream_t stream, NhwcBatchNormBwdParams params, dim3 grid_dim, int outer_loops, const int occupancy, const bool coop) { #define LAUNCH_BWD_ADD_RELU_KERNEL(OUTER_LOOPS, COMPILED_FOR_OCCUPANCY, COOP) \ do { \ CHECK(SMEM_SIZE_BWD <= MAX_SMEM_WITHOUT_OPT_IN) << \ "Nhwc batchnormaddrelu kernel smem too big."; \ auto bwd_add_relu_func = nhwc_batch_norm_bwd_add_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>; \ if (COMPILED_FOR_OCCUPANCY > 1) { \ cudaFuncSetAttribute(bwd_add_relu_func, \ cudaFuncAttributePreferredSharedMemoryCarveout, 100); \ checkCudaStatus(name_ + \ " bwd-add-relu coop serial kernel (cudaFuncSetAttribute carveout)"); \ } \ void *params_ptr = static_cast(¶ms); \ using BWD_ADD_RELU_FUNC = decltype(nhwc_batch_norm_bwd_add_relu< \ StorageType, \ THREADS_PER_CTA, \ THREADS_PER_PIXEL, \ PIXELS_PER_THREAD_IN_REGISTERS_BWD, \ PIXELS_PER_THREAD_IN_SMEM_BWD, \ ELEMENTS_PER_LDG, \ USE_ONLINE_APPROACH, \ OUTER_LOOPS, \ COMPILED_FOR_OCCUPANCY>); \ if (COOP) { \ cudaLaunchCooperativeKernel(bwd_add_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } else { \ cudaLaunchKernel(bwd_add_relu_func, \ grid_dim, \ THREADS_PER_CTA, \ ¶ms_ptr, \ SMEM_SIZE_BWD, \ stream); \ } \ checkCudaStatus(name_ + " bwd-add-relu coop serial kernel"); \ } while (0) // Don't try for an occupancy > 2 as this will squeeze register use and create spills. if (outer_loops == 1) { if (occupancy >= 2) LAUNCH_BWD_ADD_RELU_KERNEL(1, 2, coop); else LAUNCH_BWD_ADD_RELU_KERNEL(1, 1, coop); } else { if (occupancy >= 2) LAUNCH_BWD_ADD_RELU_KERNEL(0, 2, coop); else LAUNCH_BWD_ADD_RELU_KERNEL(0, 1, coop); } #undef LAUNCH_BWD_KERNEL } public: // Calculate the expected fwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_fwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int fwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int fwd_smem_bytes = SMEM_SIZE_FWD + fwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / fwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } // Calculate the expected bwd kernel occupancy, as dictated by shared memory usage. static int smem_driven_bwd_occupancy(int device_id, const int max_cta_per_sm) { using namespace at::cuda::utils; int bwd_reduction_bytes = THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG*sizeof(float); int bwd_smem_bytes = SMEM_SIZE_BWD + bwd_reduction_bytes; int occupancy = MaxSharedMemoryPerMultiprocessor(device_id) / bwd_smem_bytes; return std::min(max_cta_per_sm, occupancy); } }; const std::vector NhwcBatchNormAddRelu::numWorkspaceBytes() const { assert(c_ > 0); // choose the max memory required between fwd/bwd passes int grid_x_fwd = div_up(m_, PIXELS_PER_CTA_FWD); int grid_x_bwd = div_up(m_, PIXELS_PER_CTA_BWD); int grid_x = max(grid_x_fwd, grid_x_bwd); int grid_y = div_up(c_, C_ELEMENTS_PER_CTA); const size_t num_mean_bytes = c_ * sizeof(float); const size_t num_variance_bytes = num_mean_bytes; int elems_per_group = ((m_ + 31) & ~31) * 2; int group_count = div_up(c_, C_ELEMENTS_PER_CTA); const size_t bitmask_bytes = elems_per_group * group_count * sizeof(unsigned int); const size_t size_sums = grid_y*grid_x*THREADS_PER_PIXEL*\ ELEMENTS_PER_LDG*2*sizeof(float); const size_t size_counts = grid_y*grid_x*sizeof(int); return {num_mean_bytes, num_variance_bytes, bitmask_bytes, size_retired_ctas(grid_y), size_sums, size_counts}; } void NhwcBatchNormAddRelu::setWorkspacePointers( const std::vector& workspace, const std::vector& num_workspace_bytes) { assert(workspace.size() == 6); assert(num_workspace_bytes.size() == 6); minibatch_mean_ = static_cast(workspace[0]); minibatch_variance_ = static_cast(workspace[1]); relu_bitmask_ = static_cast(workspace[2]); retired_ctas_ = static_cast(workspace[3]); partial_sums_ = static_cast(workspace[4]); partial_counts_ = static_cast(workspace[5]); } void NhwcBatchNormAddRelu::_setFwdParams(NhwcBatchNormFwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = static_cast(addend_); params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_running_mean = population_mean_; params->gmem_running_var = population_variance_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->gmem_relu_bitmask = relu_bitmask_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->rvar_inv_count = rvar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_counts = partial_counts_; params->gmem_retired_ctas = retired_ctas_; params->var_eps = eps_; params->outer_loops = 0; params->exp_avg_factor = static_cast(exp_avg_factor_); params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNormAddRelu::_setFwdInferenceParams(NhwcBatchNormFwdInferenceParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dst = static_cast(Y_); params->gmem_src1 = static_cast(addend_); params->gmem_bias = bias_; params->gmem_scale = scale_; params->gmem_mean = population_mean_; params->gmem_var = population_variance_; params->nhw = m_; params->c = c_; params->var_eps = eps_; } void NhwcBatchNormAddRelu::_setBwdParams(NhwcBatchNormBwdParams *params) const { params->gmem_src = static_cast(X_); params->gmem_dy = static_cast(dY_); params->gmem_dst = static_cast(dX_); params->gmem_dst1 = static_cast(dAddend_); params->gmem_relu_bitmask = relu_bitmask_; params->gmem_dscale = dscale_; params->gmem_dbias = dbias_; params->gmem_scale = scale_; params->gmem_bias = bias_; params->gmem_saved_mean = minibatch_mean_; params->gmem_saved_var = minibatch_variance_; params->nhw = m_; params->c = c_; params->svar_inv_count = svar_inv_count_; params->gmem_sums = partial_sums_; params->gmem_retired_ctas = retired_ctas_; params->outer_loops = 0; params->c_blks = div_up(c_, C_ELEMENTS_PER_CTA); } void NhwcBatchNormAddRelu::fwdInference(cudaStream_t stream) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr // && minibatch_mean_ != nullptr // && minibatch_variance_ != nullptr && population_mean_ != nullptr && population_variance_ != nullptr && X_ != nullptr // && dX_ != nullptr && Y_ != nullptr && addend_ != nullptr // && dY_ != nullptr // && dscale_ != nullptr // && dbias_ != nullptr && partial_sums_ != nullptr && partial_counts_ != nullptr; if (!ptrs_are_set) die(); dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD_INFERENCE); grid_dim.y = div_up(c_, C_ELEMENTS_PER_CTA); // @todo: maybe just move this inside initialize routine? NhwcBatchNormFwdInferenceParams params; _setFwdInferenceParams(¶ms); nhwc_batch_norm_fwd_inference <<>>(params); checkCudaStatus(name_ + " fwd_inference-relu kernel"); } dim3 NhwcBatchNormAddRelu::calc_fwd_grid(int *loop, const int grid_dim_x) { dim3 grid_dim; grid_dim.x = div_up(m_, PIXELS_PER_CTA_FWD); int c_blks = div_up(c_, C_ELEMENTS_PER_CTA); unsigned int max_grid_x = grid_dim_x; if (grid_dim.x <= max_grid_x) { *loop = 1; if (max_grid_x / grid_dim.x > 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y 1) { grid_dim.y = std::min(c_blks, static_cast(max_grid_x / grid_dim.x)); assert(grid_dim.y> 1); dim3 grid_dim = calc_fwd_grid(¶ms.outer_loops, grid_dim_x); _fwdKernelLauncher(stream, params, grid_dim, params.outer_loops, occupancy, coop); } void NhwcBatchNormAddRelu::dgrad(cudaStream_t stream, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const int magic, const int occupancy, const int grid_dim_x, const bool coop) { bool ptrs_are_set = X_tensor_desc_ != nullptr && Y_tensor_desc_ != nullptr && scale_ != nullptr && bias_ != nullptr && minibatch_mean_ != nullptr && minibatch_variance_ != nullptr && relu_bitmask_ != nullptr // && population_mean_ != nullptr // && population_variance_ != nullptr && X_ != nullptr && dX_ != nullptr // && Y_ != nullptr && dY_ != nullptr && dAddend_ != nullptr && dscale_ != nullptr && dbias_ != nullptr && retired_ctas_ != nullptr; if (!ptrs_are_set) die(); // reset of retired_cta_count no longer needed NhwcBatchNormBwdParams params; _setBwdParams(¶ms); params.my_data = my_data; params.pair_datas[0] = pair_data; params.pair_datas[1] = pair_data2; params.pair_datas[2] = pair_data3; params.magic = magic; params.sync_iters = (bn_group==8)?3:(bn_group >> 1); params.wgrad_coeff = 1.0 / bn_group; dim3 grid_dim = calc_bwd_grid(¶ms.outer_loops, grid_dim_x); _bwdKernelLauncher(stream, params, grid_dim, params.outer_loops, occupancy, coop); } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_ADD_RELU_H_ ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/cuda_utils.h ================================================ #include #ifndef CUDA_UTILS_H #define CUDA_UTILS_H namespace at { namespace cuda { namespace utils { static inline int MaxSharedMemoryPerMultiprocessor(int device_id) { return getDeviceProperties(device_id)->sharedMemPerMultiprocessor; } } } } #endif ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/interface.cpp ================================================ #include #include #include #include #include #include #include #include "ATen/Scalar.h" #ifndef VERSION_GE_1_1 #include "ATen/Type.h" #endif #include "ATen/Tensor.h" #include "ATen/Storage.h" #include "ATen/Generator.h" namespace py = pybind11; int64_t get_buffer_size( const int bn_sync_steps); void* get_data_ptr( const at::Tensor& data); void* get_remote_data_ptr( const at::Tensor& handle, const int64_t offset); void close_remote_data( const at::Tensor& handle); at::Tensor nhwc_bn_fwd_train( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_fwd_eval( const at::Tensor& x, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon, const bool fuse_relu); std::vector nhwc_bn_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& ret_cta, const float momentum, const float epsilon, const bool fuse_relu, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_addrelu_fwd_train( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); at::Tensor nhwc_bn_addrelu_fwd_eval( const at::Tensor& x, const at::Tensor& z, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& ret_cta, const int bn_group, const float momentum, const float epsilon); std::vector nhwc_bn_addrelu_bwd( const at::Tensor& x, const at::Tensor& dy, const at::Tensor& scale, const at::Tensor& bias, const at::Tensor& running_mean, const at::Tensor& running_inv_var, const at::Tensor& minibatch_mean, const at::Tensor& minibatch_inv_var, const at::Tensor& bitmask, const at::Tensor& ret_cta, const float momentum, const float epsilon, void* my_data, void* pair_data, void* pair_data2, void* pair_data3, const int bn_group, const at::Tensor& magic_tensor, const int occupancy, const int grid_dim_x, const bool coop); int nhwc_bn_fwd_occupancy(); int nhwc_bn_bwd_occupancy(); int nhwc_bn_addrelu_fwd_occupancy(); int nhwc_bn_addrelu_bwd_occupancy(); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("get_buffer_size", &get_buffer_size, "get_buffer_size"); m.def("get_data_ptr", &get_data_ptr, "get_data_ptr"); m.def("get_remote_data_ptr", &get_remote_data_ptr, "get_remote_data_ptr"); m.def("close_remote_data", &close_remote_data, "close_remote_data"); m.def("bn_fwd_nhwc", &nhwc_bn_fwd_train, "bn_fwd_nhwc"); m.def("bn_fwd_eval_nhwc", &nhwc_bn_fwd_eval, "bn_fwd_eval_nhwc"); m.def("bn_bwd_nhwc", &nhwc_bn_bwd, "bn_bwd_nhwc"); m.def("bn_fwd_nhwc_occupancy", &nhwc_bn_fwd_occupancy, "bn_fwd_nhwc_occupancy"); m.def("bn_bwd_nhwc_occupancy", &nhwc_bn_bwd_occupancy, "bn_bwd_nhwc_occupancy"); m.def("bn_addrelu_fwd_nhwc", &nhwc_bn_addrelu_fwd_train, "bn_addrelu_fwd_nhwc"); m.def("bn_addrelu_fwd_eval_nhwc", &nhwc_bn_addrelu_fwd_eval, "bn_addrelu_fwd_eval_nhwc"); m.def("bn_addrelu_bwd_nhwc", &nhwc_bn_addrelu_bwd, "bn_addrelu_bwd_nhwc"); m.def("bn_addrelu_fwd_nhwc_occupancy", &nhwc_bn_addrelu_fwd_occupancy, "bn_addrelu_fwd_nhwc_occupancy"); m.def("bn_addrelu_bwd_nhwc_occupancy", &nhwc_bn_addrelu_bwd_occupancy, "bn_addrelu_bwd_nhwc_occupancy"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/ipc.cu ================================================ #include #include #include #include "THC/THC.h" #include #include "compat.h" #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \ msg, cudaGetErrorString(__err), \ __FILE__, __LINE__); \ fprintf(stderr, "*** FAILED - ABORTING\n"); \ exit(1); \ } \ } while (0) template<> struct std::hash { size_t operator() (const cudaIpcMemHandle_t& handle) const { size_t hash = 0; uint8_t* ptr = (uint8_t*)&handle; assert(sizeof(uint8_t) == 1); for (int i=0; i struct std::equal_to { bool operator() (const cudaIpcMemHandle_t &lhs, const cudaIpcMemHandle_t &rhs) const { return (std::memcmp((void*) &lhs, (void*) &rhs, sizeof(cudaIpcMemHandle_t)) == 0); } }; namespace { namespace gpuipc { //from: src/operator/nn/cudnn/nhwc_batch_norm_kernel.h // The number of threads per pixel. const int THREADS_PER_PIXEL = 16; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The number of reducing ops, each uses its own space : mean, var, dscale, dbias const int REDUCE_OPS = 4; // Maximum block.y supported - limited due to buffer allocation const int MAX_BLOCK_Y = 256; const int MAX_OFFSET = REDUCE_OPS*MAX_BLOCK_Y; const int BYTES_PER_ELEM = 4; // Buffer size per sync step const int SINGLE_SYNC_BUFFER_BYTES = MAX_OFFSET*THREADS_PER_PIXEL*2*ELEMENTS_PER_LDG*BYTES_PER_ELEM; }; class IpcMemHandleRegistry { public: void* getPtr(const cudaIpcMemHandle_t& handle, int64_t offset) { if (registry_.count(handle) == 0) { registry_.insert(std::make_pair(handle, RegistryEntry())); registry_[handle].dev_ptr = ipcOpenMem(handle); } registry_[handle].ref_count++; return (((uint8_t*)registry_[handle].dev_ptr) + offset); } void releasePtr(const cudaIpcMemHandle_t& handle) { if (registry_.count(handle) == 0) { } if (--registry_[handle].ref_count == 0) { ipcCloseMem(registry_[handle].dev_ptr); registry_.erase(handle); } } struct RegistryEntry { void* dev_ptr; int ref_count; RegistryEntry() : dev_ptr(NULL) , ref_count(0) {} }; protected: std::unordered_map registry_; void* ipcOpenMem(const cudaIpcMemHandle_t& handle) { void *data; cudaIpcOpenMemHandle(&data, handle, cudaIpcMemLazyEnablePeerAccess); cudaCheckErrors("ipc init"); return data; } void ipcCloseMem(void* dev_ptr) { cudaIpcCloseMemHandle(dev_ptr); cudaCheckErrors("ipc close"); } }; } static IpcMemHandleRegistry ipc_mem_registry; int64_t get_buffer_size(const int bn_sync_steps) { return bn_sync_steps * gpuipc::SINGLE_SYNC_BUFFER_BYTES; } void* get_remote_data_ptr(const at::Tensor& handle, const int64_t offset) { cudaIpcMemHandle_t my_handle; memcpy((unsigned char *)(&my_handle), handle.DATA_PTR(), sizeof(my_handle)); return ipc_mem_registry.getPtr(my_handle, offset); } void close_remote_data(const at::Tensor& handle) { cudaIpcMemHandle_t my_handle; memcpy((unsigned char *)(&my_handle), handle.DATA_PTR(), sizeof(my_handle)); ipc_mem_registry.releasePtr(my_handle); } void* get_data_ptr( const at::Tensor& data) { return data.DATA_PTR(); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/groupbn/nhwc_batch_norm_kernel.h ================================================ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2018 by Contributors * \file nhwc_batch_norm_kernel.h * \brief CUDA NHWC Batch Normalization code * \author Shankara Rao Thejaswi Nanditale, Dick Carter, Maxim Milakov, Evgeni Krimer */ #ifndef MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ #define MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ #include #include #define DEVICE_FUNCTION static inline __device__ // CTA margin used by cooperative launch. Can be overridden by env var NHWC_BATCHNORM_LAUNCH_MARGIN. #define NHWC_BATCHNORM_LAUNCH_MARGIN_MIN 3 #define NHWC_BATCHNORM_LAUNCH_MARGIN_DEFAULT NHWC_BATCHNORM_LAUNCH_MARGIN_MIN //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename T, int ELEMENTS_PER_LDG > struct PackedStorage { enum { PACKED_ELEMENTS_PER_LDG = ELEMENTS_PER_LDG }; typedef T Type; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int ELEMENTS_PER_LDG > struct PackedStorage { enum { PACKED_ELEMENTS_PER_LDG = ELEMENTS_PER_LDG/2 }; typedef int Type; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void from_float(int (&dst)[N], const float (&src)[2*N]) { #pragma unroll for (int i = 0; i < N; ++i) { uint16_t lo, hi; asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(lo) : "f"(src[2*i+0])); asm volatile("cvt.rn.f16.f32 %0, %1;" : "=h"(hi) : "f"(src[2*i+1])); asm volatile("mov.b32 %0, {%1, %2};" : "=r"(dst[i]) : "h"(lo), "h"(hi)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void from_float(float (&dst)[N], const float (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = src[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void to_float(float (&dst)[2*N], int (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { uint16_t lo, hi; asm volatile("mov.b32 {%0, %1}, %2;" : "=h"(lo), "=h"(hi) : "r"(src[i])); asm volatile("cvt.f32.f16 %0, %1;" : "=f"(dst[2*i+0]) : "h"(lo)); asm volatile("cvt.f32.f16 %0, %1;" : "=f"(dst[2*i+1]) : "h"(hi)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void to_float(float (&dst)[N], float (&src)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = src[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg(int (&dst)[1], const uint16_t *gmem) { dst[0] = __ldg((const int*) gmem); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg_stream(int (&dst)[1], const uint16_t *gmem) { unsigned int tmp; asm volatile ("ld.global.cs.nc.s32 %0, [%1];" : "=r"(tmp) : "l" ((const uint *)gmem)); dst[0] = tmp; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg(int (&dst)[2], const uint16_t *gmem) { int2 tmp = __ldg((const int2*) gmem); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void ldg_stream(int (&dst)[2], const uint16_t *gmem) { int2 tmp; asm volatile ("ld.global.cs.nc.v2.s32 {%0,%1}, [%2];" : "=r"(tmp.x), "=r"(tmp.y) : "l"((const int2 *)gmem)); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void ldg(float (&dst)[N], const uint16_t *gmem) { int tmp[N/2]; ldg(tmp, gmem); to_float(dst, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void ldg_stream(float (&dst)[N], const uint16_t *gmem) { int tmp[N/2]; ldg_stream(tmp, gmem); to_float(dst, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg(uint16_t *gmem, int (&src)[1]) { reinterpret_cast(gmem)[0] = src[0]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg_stream(uint16_t *gmem, int (&src)[1]) { unsigned int tmp = src[0]; asm volatile ("st.global.cs.s32 [%0], %1;" :: "l"((uint *)gmem) , "r"(tmp)); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg(uint16_t *gmem, int (&src)[2]) { reinterpret_cast(gmem)[0] = make_int2(src[0], src[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void stg_stream(uint16_t *gmem, int (&src)[2]) { asm volatile ("st.global.cs.v2.s32 [%0], {%1,%2};" :: "l"((uint *)gmem) , "r"(src[0]), "r"( src[1])); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void stg(uint16_t *gmem, float (&src)[N]) { int tmp[N/2]; from_float(tmp, src); stg(gmem, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void stg_stream(uint16_t *gmem, float (&src)[N]) { int tmp[N/2]; from_float(tmp, src); stg_stream(gmem, tmp); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_gmem(float (&dst)[2], const float *gmem, int idx) { float2 tmp = __ldg(reinterpret_cast(&gmem[2*idx])); dst[0] = tmp.x; dst[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_gmem(float (&dst)[4], const float *gmem, int idx) { float4 tmp = __ldg(reinterpret_cast(&gmem[4*idx])); dst[0] = tmp.x; dst[1] = tmp.y; dst[2] = tmp.z; dst[3] = tmp.w; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(float (&x)[2], const float *smem, int idx) { float2 tmp = *(const float2*) &smem[2*idx]; x[0] = tmp.x; x[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(int (&x)[1], const int *smem, int idx) { x[0] = smem[idx]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(float (&x)[4], const float *smem, int idx) { float4 tmp = *(const float4*) &smem[4*idx]; x[0] = tmp.x; x[1] = tmp.y; x[2] = tmp.z; x[3] = tmp.w; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void read_from_smem(int (&x)[2], const int *smem, int idx) { int2 tmp = *(const int2*) &smem[2*idx]; x[0] = tmp.x; x[1] = tmp.y; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_gmem(float *gmem, int idx, const float (&src)[2]) { reinterpret_cast(&gmem[2*idx])[0] = make_float2(src[0], src[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_gmem(float *gmem, int idx, const float (&src)[4]) { reinterpret_cast(&gmem[4*idx])[0] = make_float4(src[0], src[1], src[2], src[3]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void scaled_write_to_gmem(float *gmem, int idx, const float (&src)[4], const float coeff) { reinterpret_cast(&gmem[4*idx])[0] = make_float4(src[0]*coeff, src[1]*coeff, src[2]*coeff, src[3]*coeff); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(float *smem, int idx, const float (&x)[2]) { reinterpret_cast(&smem[2*idx])[0] = make_float2(x[0], x[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(int *smem, int idx, const int (&x)[1]) { smem[idx] = x[0]; } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(float *smem, int idx, const float (&x)[4]) { reinterpret_cast(&smem[4*idx])[0] = make_float4(x[0], x[1], x[2], x[3]); } //////////////////////////////////////////////////////////////////////////////////////////////////// DEVICE_FUNCTION void write_to_smem(int *smem, int idx, const int (&x)[2]) { reinterpret_cast(&smem[2*idx])[0] = make_int2(x[0], x[1]); } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void zero_array(int (&dst)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = 0; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int N > DEVICE_FUNCTION void zero_array(float (&dst)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { dst[i] = 0.f; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void add(float (&x)[N], const float (&y)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] += y[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void multiply(float (&x)[N], const float (&y)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] *= y[i]; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void scale_(float (&x)[N], float scalar) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] *= scalar; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void normalize(float (&x)[N], const float (&bias)[N], const float (&scale)[N], const float (&m1)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] = bias[i] + scale[i] * (x[i] - m1[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION Storage relu(Storage in) { Storage zero = (Storage)0.f; return (in < zero)? zero : in; } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_activation(float (&x)[N]) { #pragma unroll for (int i = 0; i < N; ++i) { x[i] = relu(x[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA > DEVICE_FUNCTION void parallel_sums_16x2(float *smem, float (&x)[4], int nhw, void* params_my_data, void** params_pair_datas, int off, const int magic, const int sync_iters) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of threads per pixel. const int THREADS_PER_PIXEL = 16; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The number of reducing ops, each uses its own space : mean, var, dscale, dbias const int REDUCE_OPS = 4; // Maximum block.y supported - limited due to buffer allocation const int MAX_BLOCK_Y = 256; const int MAX_OFFSET = REDUCE_OPS*MAX_BLOCK_Y; // The warp decomposition. const int warp_id = threadIdx.x / THREADS_PER_WARP; const int lane_id = threadIdx.x % THREADS_PER_WARP; // total size of data per sync iter const int data_total = MAX_OFFSET*THREADS_PER_PIXEL*ELEMENTS_PER_LDG*2; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); } // The warp leaders, write to SMEM. if (lane_id < THREADS_PER_PIXEL) { write_to_smem(smem, warp_id*THREADS_PER_PIXEL + lane_id, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // The 1st warp does all the work. // We do the final reduction each half-warp sequentially reduces the final values. if (warp_id == 0) { read_from_smem(x, smem, threadIdx.x); #pragma unroll for (int offset = 1; offset < WARPS_PER_CTA/(THREADS_PER_WARP / THREADS_PER_PIXEL); ++offset) { float y[ELEMENTS_PER_LDG]; // Read the mean and variance from the other pixel. read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_WARP); // Compute the updated sum. add(x, y); } for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); } // Make sure the data was read from SMEM. __syncwarp(); // Store the final values. if (threadIdx.x < THREADS_PER_PIXEL) { // probably could do it earlier, before sync for (int sync_iter=0; sync_iter < sync_iters; ++sync_iter) { //float* params_pair_data = (reinterpret_cast(params_pair_datas))[sync_iter]; void* params_pair_data = params_pair_datas[sync_iter]; // skip the space consumed by previous sync iterations const int xbuf_offset = sync_iter*data_total; // data starts after flags, but have to skip previous const int data_offset = xbuf_offset + off*ELEMENTS_PER_LDG*THREADS_PER_PIXEL*2 + ELEMENTS_PER_LDG*threadIdx.x*2; // after sums for this GPU were computed, let CTA0 broadcast the sum to over GPU if (blockIdx.x == 0) { volatile float * write_data = &((reinterpret_cast(params_pair_data))[data_offset]); // write the data to memory region to be reflected to other GPU asm volatile ("st.global.wt.v4.b32 [%0], {%1,%2,%3,%4};" :: "l"(write_data) , "f"(x[0]), "r"(magic), "f"(x[2]), "r"(magic)); asm volatile ("st.global.wt.v4.b32 [%0], {%1,%2,%3,%4};" :: "l"(write_data+4) , "f"(x[1]), "r"(magic), "f"(x[3]), "r"(magic)); } // now each CTA (on each GPU) reads the data written by CTA 0 of the other GPU volatile float * read_data = &((reinterpret_cast(params_my_data))[data_offset]); float other[4]; uint32_t other_flag_a, other_flag_b; do { asm volatile ("ld.volatile.global.v4.b32 {%0, %1, %2, %3}, [%4];" : "=f"(other[0]), "=r"(other_flag_a), "=f"(other[2]), "=r"(other_flag_b) : "l"(read_data)); } while ((other_flag_a != magic) || (other_flag_b != magic)); do { asm volatile ("ld.volatile.global.v4.b32 {%0, %1, %2, %3}, [%4];" : "=f"(other[1]), "=r"(other_flag_a), "=f"(other[3]), "=r"(other_flag_b) : "l"(read_data+4)); } while ((other_flag_a != magic) || (other_flag_b != magic)); add(x, other); } // finally, after syncing up and accounting for partial sums from // other GPUs as required, write the result write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA > DEVICE_FUNCTION void parallel_sums_8x4(float *smem, float (&x)[4], int nhw) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of threads per pixel. const int THREADS_PER_PIXEL = 8; // The number of elements per ldg. const int ELEMENTS_PER_LDG = 4; // The warp decomposition. const int warp_id = threadIdx.x / THREADS_PER_WARP; const int lane_id = threadIdx.x % THREADS_PER_WARP; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL*2+lane_id); } // The warp leaders, write to SMEM. if (lane_id < THREADS_PER_PIXEL) { write_to_smem(smem, warp_id*THREADS_PER_PIXEL + lane_id, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // The 1st warp does all the work. // We do the final reduction each half-warp sequentially reduces the final values. if (warp_id == 0) { read_from_smem(x, smem, threadIdx.x); #pragma unroll for (int offset = 1; offset < WARPS_PER_CTA/(THREADS_PER_WARP / THREADS_PER_PIXEL); ++offset) { float y[ELEMENTS_PER_LDG]; // Read the mean and variance from the other pixel. read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_WARP); // Compute the updated sum. add(x, y); } for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL+lane_id); x[i] += __shfl_sync(0xffffffffU, x[i], THREADS_PER_PIXEL*2+lane_id); } // Make sure the data was read from SMEM. __syncwarp(); // Store the final values. if (threadIdx.x < THREADS_PER_PIXEL) { write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_CTA, int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG > DEVICE_FUNCTION void parallel_sums(float *smem, float (&x)[ELEMENTS_PER_LDG], int nhw) { // The size of a warp. const int THREADS_PER_WARP = 32; // The number of warps in a CTA. const int WARPS_PER_CTA = THREADS_PER_CTA / THREADS_PER_WARP; // The number of pixels computed by a single warp. const int PIXELS_PER_WARP = THREADS_PER_WARP / THREADS_PER_PIXEL; // The position in the warp. const int nhw_in_warp = nhw % PIXELS_PER_WARP; // The C in the warp. const int c_in_warp = threadIdx.x % THREADS_PER_PIXEL; // Store the values to shared memory. write_to_smem(smem, threadIdx.x, x); // Compute the parallel sums. for (int offset = PIXELS_PER_WARP/2; offset > 0; offset /= 2) { // NOP. __syncwarp(); // Read the running sum from the other thread. float y[ELEMENTS_PER_LDG]; if (nhw_in_warp < offset) { read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_PIXEL); } // Compute the updated sum. add(x, y); // NOP. __syncwarp(); // Update the sum in SMEM. if (offset > 1 && nhw_in_warp < offset) { write_to_smem(smem, threadIdx.x, x); } } // The warps are done. Do the final reduction at the CTA level. __syncthreads(); // The warp leaders, write to SMEM. const int idx = (threadIdx.x/THREADS_PER_WARP)*THREADS_PER_PIXEL + c_in_warp; if (nhw_in_warp == 0) { write_to_smem(smem, idx, x); } // The data is in SMEM. Do the final reduction. __syncthreads(); // Read the 1st element to prepare the work. if (nhw < WARPS_PER_CTA/2) { read_from_smem(x, smem, threadIdx.x); } // We have the running mean and running m2. Let's build the mean/var of the CTA. for (int offset = WARPS_PER_CTA/2; offset > 0; offset /= 2) { // NOP. __syncwarp(); // Read the mean and variance from the other pixel. float y[ELEMENTS_PER_LDG]; if (nhw < offset) { read_from_smem(y, smem, threadIdx.x + offset*THREADS_PER_PIXEL); } // Compute the updated sum. add(x, y); // NOP. __syncwarp(); // Store the mean/var for the different pixels. if (nhw < offset) { write_to_smem(smem, threadIdx.x, x); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG > struct ParallelSums { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[ELEMENTS_PER_LDG], int nhw) { parallel_sums(smem, x, nhw); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct ParallelSums<16, 4> { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[4], int nhw) { parallel_sums_16x2(smem, x, nhw, 0, 0, 0, 0, 0); } template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatchX(float *smem, float (&x)[4], int nhw, void* params_my_data, void** params_pair_datas, int off, const int magic, const unsigned int& sync_iters) { parallel_sums_16x2(smem, x, nhw, params_my_data, params_pair_datas, off, magic, sync_iters); } }; template<> struct ParallelSums<8, 4> { template< int THREADS_PER_CTA > DEVICE_FUNCTION void dispatch(float *smem, float (&x)[4], int nhw) { parallel_sums_8x4(smem, x, nhw); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// static inline int div_up(int m, int n) { return (m + n - 1) / n; } //////////////////////////////////////////////////////////////////////////////////////////////////// // It is expected that all threads in the CTA enter this function! DEVICE_FUNCTION void inter_block_sync(int* gmem_retired_ctas, int expected_count, bool master) { // Register the CTA. if (threadIdx.x == 0) { // Issue the membar. __threadfence(); // Notify that the CTA is done. int val_to_add = 1; if (master) { val_to_add = -(expected_count - 1); } atomicAdd(gmem_retired_ctas, val_to_add); } // Are all CTAs done? if (threadIdx.x == 0) { int retired_ctas = -1; do { __threadfence(); asm volatile ("ld.global.cg.b32 %0, [%1];" : "=r"(retired_ctas) : "l"(gmem_retired_ctas)); } while (retired_ctas != 0); } __syncthreads(); } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormFwdInferenceParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dst, *gmem_src1; // the final mean and variance as calculated during the training process float *gmem_mean, *gmem_var; // The bias/scale. float *gmem_bias, *gmem_scale; // The dimensions. int nhw, c; // epsilon float var_eps; }; //////////////////////////////////////////////////////////////////////////////////////////////////// // No DESIRED_OCCUPANCY launch bounds needed, as this is not launched cooperatively template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int ELEMENTS_PER_LDG, bool USE_RELU, bool USE_ADD_RELU > __global__ __launch_bounds__(THREADS_PER_CTA) void nhwc_batch_norm_fwd_inference(NhwcBatchNormFwdInferenceParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // The start position in the NHW dimension where the CTA starts. const int cta_nhw_stride = gridDim.x * PIXELS_PER_LDG; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // thread's starting point in NHW const int thread_nhw = thread_in_cta_nhw + blockIdx.x * PIXELS_PER_LDG; // The position in the C dimension where the CTA starts. const int cta_c = blockIdx.y * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; float mean[ELEMENTS_PER_LDG], var[ELEMENTS_PER_LDG]; float scale[ELEMENTS_PER_LDG], bias[ELEMENTS_PER_LDG]; zero_array(mean); zero_array(var); zero_array(scale); zero_array(bias); if (is_valid_c) { read_from_gmem(var, ¶ms.gmem_var[cta_c], thread_in_cta_c); read_from_gmem(scale, ¶ms.gmem_scale[cta_c], thread_in_cta_c); read_from_gmem(mean, ¶ms.gmem_mean[cta_c], thread_in_cta_c); read_from_gmem(bias, ¶ms.gmem_bias[cta_c], thread_in_cta_c); } // Update the scale with the stddev and eps. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { scale[i] *= rsqrtf(var[i] + params.var_eps); } // The base pointers for reading/writing uint16_t *const gmem_src = ¶ms.gmem_src[thread_c]; uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; const uint16_t *gmem_src1 = nullptr; if (USE_ADD_RELU) { gmem_src1 = ¶ms.gmem_src1[thread_c]; } // apply BN for (int nhw = thread_nhw; nhw < params.nhw; nhw += cta_nhw_stride) { float x_math[ELEMENTS_PER_LDG]; zero_array(x_math); if (is_valid_c) { ldg(x_math, &gmem_src[nhw*params.c]); } // Normalize and apply activation function normalize(x_math, bias, scale, mean); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg(x1_math, &gmem_src1[nhw*params.c]); add(x_math, x1_math); relu_activation(x_math); } else if (USE_RELU) { relu_activation(x_math); } if (is_valid_c) { stg(&gmem_dst[nhw*params.c], x_math); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormFwdParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dst, *gmem_src1; // The bias/scale. float *gmem_bias, *gmem_scale; // running mean/var (refer BN API from cudnn doc) float *gmem_running_mean, *gmem_running_var; // saved mean/var (refer BN API from cudnn doc) float *gmem_saved_mean, *gmem_saved_var; // ReLU bitmask unsigned int *gmem_relu_bitmask; // The dimensions. int nhw, c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. float svar_inv_count; // factor to scale sum of squared errors to get running variance. Should be 1/nhw or 1/(nhw-1). float rvar_inv_count; // The buffer to do the reduction for mean, stddev and count. float *gmem_sums; // The buffer to count items in the different CTAs. int *gmem_counts; // The counters of retired CTAs. int *gmem_retired_ctas; // The epsilon to apply to the computation of the variance. float var_eps; // outer loop count int outer_loops; // exponential average factor float exp_avg_factor; // number of CTAs along .x dimension int c_blks; void* my_data; void* pair_datas[4]; int magic; int sync_iters; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, bool USE_RELU, bool USE_ADD_RELU, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_fwd(NhwcBatchNormFwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Clamp thread_c so that we load from valid locations even if we don't use the value if (!is_valid_c) thread_c = params.c - 4; // Single pass numerically stable algorithm, see: // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm // // n = 0, mean = 0.0, M2 = 0.0 // // for x in data: // n += 1 // delta = x - mean // mean += delta/n // delta2 = x - mean // M2 += delta*delta2 // // if n < 2: // return float('nan') // else: // return M2 / (n - 1) // Register to store the number of elements read so far. float count = 0.f, mean[ELEMENTS_PER_LDG], m2[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean[i] = 0.f; m2[i] = 0.f; } // The number of elements loaded by this CTA. int cta_count = 0; // The base pointer to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute the mean/var across those elements. const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized, offset is evenly divisible by 32 int offset = (pixels_per_iteration * OUTER_LOOPS + PIXELS_PER_CTA_IN_SMEM * gridDim.x - params.nhw) & ~31; cta_nhw_regs -= offset; cta_nhw_smem -= offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(min(nhw_regs + PIXELS_PER_CTA_IN_REGISTERS, params.nhw) - max(nhw_regs, 0), 0); // Load the data and compute the local mean/sum and the variance. if (USE_ONLINE_APPROACH) { // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { float delta0 = x_math[j] - mean[j]; mean[j] += delta0 * inv_count; float delta1 = x_math[j] - mean[j]; m2[j] += delta0 * delta1 * is_valid[i]; } } } else { // Read the elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); } count += 1.f; } } // Sum the elements in registers. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { mean[j] += x_math[j]; } } // Compute the mean. float inv_count = 1.f / count; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { mean[j] *= inv_count; } // Compute the variance. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Is it a valid pixel? float is_valid = i < static_cast(count) ? 1.f : 0.f; // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { m2[j] += (x_math[j] - mean[j]) * (x_math[j] - mean[j]) * is_valid; } } } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(smem_nhw + PIXELS_PER_CTA_IN_SMEM, params.nhw) - max(smem_nhw, 0); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; float is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) ? 1.f : 0.f; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG]; ldg_stream(x_storage_local, &gmem_src[(is_pixel_valid ? idx : 0)*params.c]); // The offset to store in SMEM. const int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); // Update the mean and m2 using deltas. #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { float delta0 = x_math[j] - mean[j]; mean[j] += delta0 * inv_count; float delta1 = x_math[j] - mean[j]; m2[j] += delta0 * delta1 * is_pixel_valid; } } } // We scale the mean by the number of elements. It brings more stability. float m1[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = mean[i] * count; } // Run the parallel sum accross the CTA to get the local sum. ParallelSums::dispatch( smem, m1, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(m1, smem, thread_in_cta_c); __syncthreads(); // Adjust the variance. float inv_cta_count = 1.f / static_cast(cta_count); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { float mean_diff = m1[i]*inv_cta_count - mean[i]; m2[i] = m2[i] + mean_diff * mean_diff * count; } // Run the parallel sum accross the CTA to get the local adjusted variance. ParallelSums::dispatch( smem, m2, thread_in_cta_nhw); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, m1); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, m2); } // The memory location to store the number of pixels per CTA. int *gmem_counts = ¶ms.gmem_counts[c_blk_index*gridDim.x]; if (threadIdx.x == 0) { gmem_counts[blockIdx.x] = cta_count; } // Read the bias and scale. float bias[ELEMENTS_PER_LDG], scale[ELEMENTS_PER_LDG]; if (is_valid_c) { read_from_gmem(bias, ¶ms.gmem_bias[cta_c], thread_in_cta_c); read_from_gmem(scale, ¶ms.gmem_scale[cta_c], thread_in_cta_c); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the mean to compute the global mean. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = 0.f; } // Build the global mean. #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp[ELEMENTS_PER_LDG]; read_from_gmem(tmp, gmem_sums, idx); add(m1, tmp); } if (params.sync_iters>0) { ParallelSums::dispatchX( smem, m1, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+3, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, m1, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(m1, smem, thread_in_cta_c); __syncthreads(); // Normalize the mean. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m1[i] = m1[i] * params.svar_inv_count; } // Reset the variance. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m2[i] = 0.f; } // for add+relu fusion const uint16_t *gmem_src1 = nullptr; if (USE_ADD_RELU) { gmem_src1 = ¶ms.gmem_src1[thread_c]; } // Build the global variance. #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { // Read the means computed by different CTAs (again). Reuse tmp if we have 1 iteration. float tmp_mean[ELEMENTS_PER_LDG], tmp_var[ELEMENTS_PER_LDG]; read_from_gmem(tmp_mean, &gmem_sums[ 0], idx); read_from_gmem(tmp_var, &gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx); // Read the number of pixels visited by a given CTA. cta_count = __ldg(&gmem_counts[idx / THREADS_PER_PIXEL]); // Compute the diff to update the variance. float mean_diff[ELEMENTS_PER_LDG], inv_cta_count = 1.f / static_cast(cta_count); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean_diff[i] = m1[i] - tmp_mean[i]*inv_cta_count; } // Update the variance. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { m2[i] += tmp_var[i] + mean_diff[i]*mean_diff[i]*static_cast(cta_count); } } if (params.sync_iters>0) { ParallelSums::dispatchX( smem, m2, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+2, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, m2, thread_in_cta_nhw); } __syncthreads(); read_from_smem(m2, smem, thread_in_cta_c); // Finalize the stddev. // becasue saved var and running var may have different denominator, we don't do it here // scale_(m2, inv_count); // store the saved mean/var float svarinv[ELEMENTS_PER_LDG]; bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { svarinv[i] = rsqrtf(m2[i] * params.svar_inv_count + params.var_eps); } if (is_valid_for_saving) { write_to_gmem(params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG, m1); write_to_gmem(params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG, svarinv); } // store the running mean/var float rmean[ELEMENTS_PER_LDG], rvar[ELEMENTS_PER_LDG]; zero_array(rmean); zero_array(rvar); if (params.exp_avg_factor != 1.f && is_valid_for_saving) { read_from_gmem(rmean, params.gmem_running_mean, thread_c/ELEMENTS_PER_LDG); read_from_gmem(rvar, params.gmem_running_var, thread_c/ELEMENTS_PER_LDG); } #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { rmean[i] = (1.f - params.exp_avg_factor) * rmean[i] + \ params.exp_avg_factor * m1[i]; rvar[i] = (1.f - params.exp_avg_factor) * rvar[i] + \ params.exp_avg_factor * (m2[i] * params.rvar_inv_count); } if (is_valid_for_saving) { write_to_gmem(params.gmem_running_mean, thread_c/ELEMENTS_PER_LDG, rmean); write_to_gmem(params.gmem_running_var, thread_c/ELEMENTS_PER_LDG, rvar); } // Update the scale with the stddev and eps. multiply(scale, svarinv); // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; unsigned int *const gmem_relu_bitmask = params.gmem_relu_bitmask + ((params.nhw + 31) & ~31) * 2 * c_blk_index; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_valid = is_valid_nhw && is_valid_c; // Convert to float. float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); // Normalize and apply activation function normalize(x_math, bias, scale, m1); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg_stream(x1_math, &gmem_src1[(is_valid ? idx : 0)*params.c]); add(x_math, x1_math); unsigned int relu_mask; int lane_id = threadIdx.x & 31; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { bool rectified = x_math[i] < 0.0F; unsigned int local_relu_mask = __ballot_sync(0xFFFFFFFFU, rectified); if (lane_id == i) { // Thread 0 remembers the relu_mask from the first time through this // loop, Thread 1 the next, Thread 2 the next, and Thread 3 the last. relu_mask = local_relu_mask; } if (rectified) { x_math[i] = 0.0F; } } if (is_valid_nhw && (lane_id < ELEMENTS_PER_LDG)) { gmem_relu_bitmask[idx * 2 + lane_id] = relu_mask; } } else if (USE_RELU) { relu_activation(x_math); } // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], x_math); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { #pragma unroll 2 for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_valid = is_valid_nhw && is_valid_c; // Read from SMEM. const int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); // Normalize and apply activation function normalize(x_math, bias, scale, m1); if (USE_ADD_RELU) { float x1_math[ELEMENTS_PER_LDG]; ldg_stream(x1_math, &gmem_src1[(is_valid ? idx : 0)*params.c]); add(x_math, x1_math); unsigned int relu_mask; int lane_id = threadIdx.x & 31; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { bool rectified = x_math[i] < 0.0F; unsigned int local_relu_mask = __ballot_sync(0xFFFFFFFFU, rectified); if (lane_id == i) { relu_mask = local_relu_mask; } if (rectified) { x_math[i] = 0.0F; } } if (is_valid_nhw && (lane_id < ELEMENTS_PER_LDG)) { gmem_relu_bitmask[idx * 2 + lane_id] = relu_mask; } } else if (USE_RELU) { relu_activation(x_math); } // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], x_math); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// struct NhwcBatchNormBwdParams { // The input/output tensors. uint16_t *gmem_src, *gmem_dy, *gmem_dst, *gmem_dst1; // dscale/dbias float *gmem_dscale, *gmem_dbias; // The scale and bias. float *gmem_scale, *gmem_bias; // The mean/inv-var saved from fwd pass float *gmem_saved_mean, *gmem_saved_var; // ReLU bitmask unsigned int *gmem_relu_bitmask; // The dimensions. int nhw, c; // factor to scale sum of squared errors to get saved variance. Must be 1/nhw. float svar_inv_count; // The buffer to do the reduction for dscale and dbias float *gmem_sums; // The counters of retired CTAs. int *gmem_retired_ctas; // outer loop count int outer_loops; // number of CTAs along .x dimension int c_blks; void* my_data; void* pair_datas[4]; int magic; int sync_iters; float wgrad_coeff; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const float (&x)[N], const float (&mean_var_scale_bias)[N], const float (&var_scale)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { float y = (x[j] * var_scale[j]) + mean_var_scale_bias[j]; if ((y <= 0.f) && valid_data) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const float (&y)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { if ((y[j] <= 0.f) && valid_data) { dy[j] = 0.f; } } } template DEVICE_FUNCTION void relu_bwd(float (&dy)[N], const bool (&rectified)[N], bool valid_data) { #pragma unroll for (int j = 0; j < N; ++j) { if (rectified[j] && valid_data) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd_for_dx(float (&dy)[N], const float (&x)[N], const float (&mean_var_scale_bias)[N], const float (&var_scale)[N]) { #pragma unroll for (int j = 0; j < N; ++j) { float y = (x[j] * var_scale[j]) + mean_var_scale_bias[j]; if (y <= 0.f) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void relu_bwd_for_dx(float (&dy)[N], const float (&y)[N]) { #pragma unroll for (int j = 0; j < N; ++j) { if (y[j] <= 0.f) { dy[j] = 0.f; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void bwd_update(float (&dscale)[N], float (&dbias)[N], const float (&dy)[N], const float (&x)[N], const float (&mean)[N], float inv_count) { #pragma unroll for (int j = 0; j < N; ++j) { float delta0 = dy[j] - dbias[j]; dbias[j] += delta0 * inv_count; delta0 = (dy[j] * (x[j] - mean[j])) - dscale[j]; dscale[j] += delta0 * inv_count; } } //////////////////////////////////////////////////////////////////////////////////////////////////// template DEVICE_FUNCTION void bwd_dx(float (&dx)[N], const float (&dy)[N], const float (&var)[N], const float (&x)[N], const float (&mean)[N], const float (&dscale)[N], const float (&dbias)[N], float inv_count) { #pragma unroll for (int j = 0; j < N; ++j) { float tmp1 = dy[j] - (dbias[j]* inv_count); float tmp2 = dscale[j] * inv_count; float tmp3 = x[j] - mean[j]; dx[j] = var[j] * (tmp1 - (tmp2 * tmp3)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Registers to store the mean used for entire duration float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized int offset = params.nhw - pixels_per_iteration * OUTER_LOOPS - PIXELS_PER_CTA_IN_SMEM * gridDim.x; cta_nhw_regs += offset; cta_nhw_smem += offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; bool is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c); PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // inv-var float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } // Normalize the dscale. multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // scale float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } // Further normalize the dscale to be used in dx calculation multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd_relu(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; // Registers to store the mean/var/scale/bias used for the entire duration // Register usage optimizations: // 1. Can combine bias - (mean * var * scale) into a single register // 2. Can combine var * scale into a single register float varscale[ELEMENTS_PER_LDG]; zero_array(varscale); if (is_valid_c) { read_from_gmem(varscale, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } float tmp[ELEMENTS_PER_LDG]; zero_array(tmp); if (is_valid_c) { read_from_gmem(tmp, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(varscale, tmp); float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } zero_array(tmp); if (is_valid_c) { read_from_gmem(tmp, params.gmem_bias, thread_c/ELEMENTS_PER_LDG); } float mean_var_scale_bias[ELEMENTS_PER_LDG]; #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { mean_var_scale_bias[i] = tmp[i] - (mean[i] * varscale[i]); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized int offset = params.nhw - pixels_per_iteration * OUTER_LOOPS - PIXELS_PER_CTA_IN_SMEM * gridDim.x; cta_nhw_regs += offset; cta_nhw_smem += offset; } #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; relu_bwd(dy_math, x_math, mean_var_scale_bias, varscale, is_valid[i]); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; bool is_pixel_valid = (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c); PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd(dy_math, x_math, mean_var_scale_bias, varscale, is_pixel_valid); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // Normalize the dscale. float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // Further normalize the dscale to be used in dx calculation float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); relu_bwd_for_dx(dy_math, x_math, mean_var_scale_bias, var); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd_for_dx(dy_math, x_math, mean_var_scale_bias, var); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template< typename Storage, int THREADS_PER_CTA, int THREADS_PER_PIXEL, int PIXELS_PER_THREAD_IN_REGISTERS, int PIXELS_PER_THREAD_IN_SMEM, int ELEMENTS_PER_LDG, int USE_ONLINE_APPROACH, int OUTER_LOOPS_, int DESIRED_OCCUPANCY > __global__ __launch_bounds__(THREADS_PER_CTA, DESIRED_OCCUPANCY) void nhwc_batch_norm_bwd_add_relu(NhwcBatchNormBwdParams params) { // The number of pixels loaded in a single LDG. const int PIXELS_PER_LDG = THREADS_PER_CTA / THREADS_PER_PIXEL; // The number of pixels computed per CTA stored in registers. const int PIXELS_PER_CTA_IN_REGISTERS = PIXELS_PER_THREAD_IN_REGISTERS * PIXELS_PER_LDG; // The number of pixels computed per CTA stored in SMEM. const int PIXELS_PER_CTA_IN_SMEM = PIXELS_PER_THREAD_IN_SMEM*PIXELS_PER_LDG; // The number of C elements per CTA. const int C_ELEMENTS_PER_CTA = THREADS_PER_PIXEL*ELEMENTS_PER_LDG; // Shared memory to do CTA-wide parallel sums. __shared__ float smem[THREADS_PER_PIXEL*(THREADS_PER_CTA/32)*ELEMENTS_PER_LDG]; // The adapter for the storage. typedef PackedStorage PackedStorage_; // The data type for packed storage in SMEM. typedef typename PackedStorage_::Type PackedStorageType; // The number of elements in the packed storage. const int PACKED_ELEMENTS_PER_LDG = PackedStorage_::PACKED_ELEMENTS_PER_LDG; // Registers to keep the data live for the persistent approach. PackedStorageType x_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; PackedStorageType dy_storage[PIXELS_PER_THREAD_IN_REGISTERS][PACKED_ELEMENTS_PER_LDG]; // Shared memory buffer to store the extra pixels. extern __shared__ PackedStorageType smem_storage_packed[]; for (int c_blk_index = blockIdx.y; c_blk_index < params.c_blks; c_blk_index += gridDim.y) { // The position in the NHW dimension where the CTA starts. int cta_nhw_regs = blockIdx.x * PIXELS_PER_CTA_IN_REGISTERS; // The position in the NHW dimension where the CTA starts for the portion in SMEM. int cta_nhw_smem = blockIdx.x * PIXELS_PER_CTA_IN_SMEM; // Compute the NHW coordinate of the thread in the CTA. const int thread_in_cta_nhw = threadIdx.x / THREADS_PER_PIXEL; // The position in the C dimension where the CTA starts. const int cta_c = c_blk_index * C_ELEMENTS_PER_CTA; // Compute the C coordinate of the thread in the CTA. const int thread_in_cta_c = threadIdx.x % THREADS_PER_PIXEL; // Compute the C coordinate of the thread. const int thread_c = cta_c + thread_in_cta_c*ELEMENTS_PER_LDG; // Is the thread working on a valid C dimension? const int is_valid_c = thread_c < params.c; float mean[ELEMENTS_PER_LDG]; zero_array(mean); if (is_valid_c) { read_from_gmem(mean, params.gmem_saved_mean, thread_c/ELEMENTS_PER_LDG); } // accumulation related registers float count = 0.f, dscale[ELEMENTS_PER_LDG], dbias[ELEMENTS_PER_LDG]; zero_array(dscale); zero_array(dbias); // The number of elements loaded by this CTA. int cta_count = 0; // The base pointers to load from. const uint16_t *gmem_src = ¶ms.gmem_src[thread_c]; const uint16_t *gmem_dy = ¶ms.gmem_dy[thread_c]; uint16_t *gmem_dst1 = ¶ms.gmem_dst1[thread_c]; // outer loops int OUTER_LOOPS = OUTER_LOOPS_ == 1? 1 : params.outer_loops; // Load the batch of elements. Compute sum across them const int pixels_per_iteration = PIXELS_PER_CTA_IN_REGISTERS*gridDim.x; if (OUTER_LOOPS_ != 1) { // We cannot load everything to store persistently, so let's makes sure registers and // smem are fully utilized, offset is evenly divisible by 32 int offset = (pixels_per_iteration * OUTER_LOOPS + PIXELS_PER_CTA_IN_SMEM * gridDim.x - params.nhw) & ~31; cta_nhw_regs -= offset; cta_nhw_smem -= offset; } const unsigned int *const gmem_relu_bitmask = params.gmem_relu_bitmask + ((params.nhw + 31) & ~31) * 2 * c_blk_index; #pragma unroll 1 for (int loop_i = 0; loop_i < OUTER_LOOPS; ++loop_i) { // The nhw position. int nhw_regs = cta_nhw_regs + loop_i*pixels_per_iteration; // Update the number of elements loaded by this CTA. TODO: Skip if <= 0!!! cta_count += max(0, min(PIXELS_PER_CTA_IN_REGISTERS, params.nhw-nhw_regs)); int lane_id = threadIdx.x & 31; // Read the elements from memory. float is_valid[PIXELS_PER_THREAD_IN_REGISTERS]; unsigned int relu_mask[PIXELS_PER_THREAD_IN_REGISTERS]; #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; zero_array(x_storage[i]); zero_array(dy_storage[i]); is_valid[i] = 0.f; const bool is_valid_nhw = static_cast(idx) < static_cast(params.nhw); if (is_valid_nhw) { if (is_valid_c) { if (loop_i == OUTER_LOOPS - 1) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dy[idx*params.c]); } else { ldg(x_storage[i], &gmem_src[idx*params.c]); ldg(dy_storage[i], &gmem_dy[idx*params.c]); } is_valid[i] = 1.f; } if (lane_id < ELEMENTS_PER_LDG) { relu_mask[i] = gmem_relu_bitmask[idx * 2 + lane_id]; } } } // Do the math. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = nhw_regs + thread_in_cta_nhw + i*PIXELS_PER_LDG; // Convert to float and update float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; bool rectified[ELEMENTS_PER_LDG]; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { rectified[j] = ((__shfl_sync(0xFFFFFFFFU, relu_mask[i], j) & (1U << lane_id)) != 0); } to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); // Update the count. count += is_valid[i]; // Invert the count. float inv_count = is_valid[i] ? 1.f / count : 0.f; relu_bwd(dy_math, rectified, is_valid[i]); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); // Lastly we need 'dy' only for BN, so store the 'relu-dgrad'ed version from_float(dy_storage[i], dy_math); // dZ for elementwise add if (is_valid[i]) { if (loop_i == OUTER_LOOPS - 1) { stg_stream(&gmem_dst1[idx*params.c], dy_storage[i]); } else { stg(&gmem_dst1[idx*params.c], dy_storage[i]); } } } } // The elements to load and store in SMEM. int smem_nhw = OUTER_LOOPS*pixels_per_iteration + cta_nhw_smem; // Load elements from SMEM, update the CTA count. int pixels_in_smem = min(PIXELS_PER_CTA_IN_SMEM, params.nhw-smem_nhw); if (pixels_in_smem > 0) { cta_count += pixels_in_smem; for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_pixel_valid_nhw = static_cast(idx) < static_cast(params.nhw); const bool is_pixel_valid = is_pixel_valid_nhw && is_valid_c; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; unsigned int relu_mask; int lane_id = threadIdx.x & 31; zero_array(x_storage_local); zero_array(dy_storage_local); if (is_pixel_valid_nhw) { if (is_valid_c) { ldg_stream(x_storage_local, &gmem_src[idx*params.c]); ldg_stream(dy_storage_local, &gmem_dy[idx*params.c]); } if (lane_id < ELEMENTS_PER_LDG) { relu_mask = gmem_relu_bitmask[idx * 2 + lane_id]; } } bool rectified[ELEMENTS_PER_LDG]; #pragma unroll for (int j = 0; j < ELEMENTS_PER_LDG; ++j) { rectified[j] = ((__shfl_sync(0xFFFFFFFFU, relu_mask, j) & (1U << lane_id)) != 0); } // The offset to store in SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Store in SMEM. write_to_smem(&smem_storage_packed[offset], threadIdx.x, x_storage_local); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; // Update the count. count += is_pixel_valid; // Invert the count. float inv_count = is_pixel_valid ? 1.f / count : 0.f; float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); relu_bwd(dy_math, rectified, is_pixel_valid); bwd_update(dscale, dbias, dy_math, x_math, mean, inv_count); from_float(dy_storage_local, dy_math); // dZ for elementwise add if (is_pixel_valid) { stg_stream(&gmem_dst1[idx*params.c], dy_storage_local); } // only store the 'relu-dgrad'ed version! write_to_smem(&smem_storage_packed[offset], threadIdx.x, dy_storage_local); } } // We scale the mean by the number of elements. It brings more stability. #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dbias[i] *= count; dscale[i] *= count; } // dscale parallel sum ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); __syncthreads(); // The workspace in global memory is distributed across the different CTA. int gmem_sums_offset = c_blk_index*gridDim.x*C_ELEMENTS_PER_CTA*2; // Write the data for the CTA to global memory. float *gmem_sums = ¶ms.gmem_sums[gmem_sums_offset]; if (threadIdx.x < THREADS_PER_PIXEL) { const int idx = blockIdx.x*THREADS_PER_PIXEL + threadIdx.x; write_to_gmem(&gmem_sums[ 0], idx, dscale); write_to_gmem(&gmem_sums[C_ELEMENTS_PER_CTA*gridDim.x], idx, dbias); } // The counters to count how many CTAs have retired at this point. // A given cta uses the same counter every other time through the outer loop. int *gmem_retired_ctas = ¶ms.gmem_retired_ctas[c_blk_index % (2 * gridDim.y)]; inter_block_sync(gmem_retired_ctas, gridDim.x, blockIdx.x == 0); // Reset the accumulators for global summation zero_array(dscale); zero_array(dbias); // Build the global accumulation #pragma unroll 1 for (int idx = threadIdx.x; idx < THREADS_PER_PIXEL*gridDim.x; idx += THREADS_PER_CTA) { float tmp1[ELEMENTS_PER_LDG], tmp2[ELEMENTS_PER_LDG]; read_from_gmem(tmp1, gmem_sums, idx); read_from_gmem(tmp2, gmem_sums+C_ELEMENTS_PER_CTA*gridDim.x, idx); #pragma unroll for (int i = 0; i < ELEMENTS_PER_LDG; ++i) { dscale[i] += tmp1[i]; dbias[i] += tmp2[i]; } } // dscale parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dscale, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+1, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dscale, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dscale, smem, thread_in_cta_c); __syncthreads(); // dbias parallel sum if (params.sync_iters>0) { ParallelSums::dispatchX( smem, dbias, thread_in_cta_nhw, params.my_data, params.pair_datas, 4*c_blk_index+0, params.magic, params.sync_iters); } else { ParallelSums::dispatch( smem, dbias, thread_in_cta_nhw); } __syncthreads(); // The values in shared memory correspond to the CTA-wide sums. read_from_smem(dbias, smem, thread_in_cta_c); // Normalize the dscale. float var[ELEMENTS_PER_LDG]; zero_array(var); if (is_valid_c) { read_from_gmem(var, params.gmem_saved_var, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // store dscale/dbias bool is_valid_for_saving = is_valid_c && blockIdx.x == 0 && thread_in_cta_nhw == 0; if (is_valid_for_saving) { if (params.sync_iters>0) { scaled_write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale, params.wgrad_coeff); scaled_write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias, params.wgrad_coeff); } else { write_to_gmem(params.gmem_dscale, thread_c/ELEMENTS_PER_LDG, dscale); write_to_gmem(params.gmem_dbias, thread_c/ELEMENTS_PER_LDG, dbias); } } // Further normalize the dscale to be used in dx calculation float scale[ELEMENTS_PER_LDG]; zero_array(scale); if (is_valid_c) { read_from_gmem(scale, params.gmem_scale, thread_c/ELEMENTS_PER_LDG); } multiply(dscale, var); // scale the inv-var as well, afterwards multiply(var, scale); // inverse count float inv_count = params.svar_inv_count; // The base pointer to write to. uint16_t *const gmem_dst = ¶ms.gmem_dst[thread_c]; // Store the elements in registers. #pragma unroll 1 for (int loop_i = OUTER_LOOPS-1; loop_i >= 0; --loop_i) { // The value for nhw. int out_nhw = cta_nhw_regs + loop_i*pixels_per_iteration; // Normalize the elements and write to memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; // Convert to float. float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage[i]); to_float(dy_math, dy_storage[i]); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. if (is_valid) { stg_stream(&gmem_dst[idx*params.c], dx); } } // The next value of nhw. out_nhw -= pixels_per_iteration; // Read the next elements from memory. #pragma unroll for (int i = 0; i < PIXELS_PER_THREAD_IN_REGISTERS; ++i) { const int idx = out_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; float y[ELEMENTS_PER_LDG]; zero_array(y); if (((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c) { ldg_stream(x_storage[i], &gmem_src[idx*params.c]); ldg_stream(dy_storage[i], &gmem_dst1[idx*params.c]); } } } // Normalize the elements from SMEM and write them out. if (pixels_in_smem > 0) { for (int i = 0; i < PIXELS_PER_THREAD_IN_SMEM; ++i) { const int idx = smem_nhw + thread_in_cta_nhw + i*PIXELS_PER_LDG; const bool is_valid = ((unsigned int)idx < (unsigned int)params.nhw) && is_valid_c; if (is_valid) { // Read from SMEM. int offset = i*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; PackedStorageType x_storage_local[PACKED_ELEMENTS_PER_LDG], dy_storage_local[PACKED_ELEMENTS_PER_LDG]; read_from_smem(x_storage_local, &smem_storage_packed[offset], threadIdx.x); offset += PIXELS_PER_THREAD_IN_SMEM*THREADS_PER_CTA*PACKED_ELEMENTS_PER_LDG; read_from_smem(dy_storage_local, &smem_storage_packed[offset], threadIdx.x); float x_math[ELEMENTS_PER_LDG], dy_math[ELEMENTS_PER_LDG]; to_float(x_math, x_storage_local); to_float(dy_math, dy_storage_local); float dx[ELEMENTS_PER_LDG]; bwd_dx(dx, dy_math, var, x_math, mean, dscale, dbias, inv_count); // Write back. stg_stream(&gmem_dst[idx*params.c], dx); } } } // We're about to start on the next c-blk. Needed? __syncthreads(); } } #endif // MXNET_OPERATOR_NN_CUDNN_NHWC_BATCH_NORM_KERNEL_H_ ================================================ FILE: KoSimCSE/apex/contrib/csrc/layer_norm/ln_api.cpp ================================================ #include #include "ATen/cuda/CUDAContext.h" void ln_fwd_cuda(at::Tensor &y, at::Tensor &mu, at::Tensor &rsigma, const at::Tensor &x, const at::Tensor &gamma, const at::Tensor &beta, const float epsilon, const int rows, const int cols, cudaStream_t stream); void ln_bwd_cuda(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, cudaStream_t stream); std::vector ln_fwd(const at::Tensor &x, // BxSxhidden_size const at::Tensor &gamma, // hidden_size const at::Tensor &beta, // hidden_size const float epsilon ) { TORCH_CHECK(x.is_cuda()) TORCH_CHECK(gamma.is_cuda()) TORCH_CHECK(beta.is_cuda()) TORCH_CHECK(x.is_contiguous()); auto sizes = x.sizes(); TORCH_CHECK(sizes.size() == 2); const int rows = sizes[0]; const int cols = sizes[1]; auto dtype = x.scalar_type(); TORCH_CHECK(gamma.dtype() == dtype); TORCH_CHECK(beta.dtype() == dtype); TORCH_CHECK(gamma.sizes() == beta.sizes()); TORCH_CHECK(gamma.numel() == cols); TORCH_CHECK(epsilon >= 0.f); auto stream = at::cuda::getCurrentCUDAStream().stream(); auto y = torch::empty_like(x); auto opts = x.options(); auto mu = torch::empty({rows}, opts.dtype(torch::kFloat32)); auto rsigma = torch::empty({rows}, opts.dtype(torch::kFloat32)); ln_fwd_cuda(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, stream); return {y, mu, rsigma}; } std::vector ln_bwd(const at::Tensor &dw, // BxSxhidden_size const at::Tensor &x, // BxSxhidden_size const at::Tensor &mu, // BxS, FP32! const at::Tensor &rsigma, // BxS, FP32! const at::Tensor &gamma // hidden_size ) { TORCH_CHECK(x.is_cuda()); TORCH_CHECK(dw.is_cuda()); TORCH_CHECK(mu.is_cuda()); TORCH_CHECK(rsigma.is_cuda()); TORCH_CHECK(gamma.is_cuda()); TORCH_CHECK(x.is_contiguous()); TORCH_CHECK(dw.is_contiguous()); auto sizes = x.sizes(); TORCH_CHECK(sizes.size() == 2); TORCH_CHECK(dw.sizes() == sizes); auto rows = sizes[0]; auto cols = sizes[1]; auto dtype = x.scalar_type(); TORCH_CHECK(dw.dtype() == dtype); TORCH_CHECK(gamma.dtype() == dtype); TORCH_CHECK(mu.dtype() == torch::kFloat32); TORCH_CHECK(rsigma.dtype() == torch::kFloat32); TORCH_CHECK(mu.sizes() == rsigma.sizes()); TORCH_CHECK(mu.numel() == rows); TORCH_CHECK(gamma.numel() == cols); auto stream = at::cuda::getCurrentCUDAStream().stream(); auto dx = torch::empty_like(x); auto dgamma = torch::empty_like(gamma); auto dbeta = torch::empty_like(gamma); ln_bwd_cuda(dx, dgamma, dbeta, dw, x, mu, rsigma, gamma, rows, cols, stream); return {dx, dgamma, dbeta}; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.doc() = "CUDA LayerNorm"; // optional module docstring m.def("ln_fwd", &ln_fwd, "Run LayerNorm forward kernel"); m.def("ln_bwd", &ln_bwd, "Run LayerNorm backward kernel"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/layer_norm/ln_bwd_semi_cuda_kernel.cu ================================================ #include "utils.cuh" #include "ln_kernel_traits.h" #include "ATen/cuda/CUDAContext.h" template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_bwd_kernel(void * __restrict__ dx_, void * __restrict__ dg_, void * __restrict__ db_, const void * __restrict__ dw_, const void * __restrict__ x_, const void * __restrict__ mu_, const void * __restrict__ rs_, const void * __restrict__ g_, const int rows ){ using Vec = typename Ktraits::Vec; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { WARPS_M = Ktraits::WARPS_M }; enum { WARPS_N = Ktraits::WARPS_N }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { COLS = Ktraits::COLS }; enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum { LDGS = BYTES_PER_ROW / Ktraits::BYTES_PER_ROW_PER_CTA }; static_assert(LDGS * Ktraits::BYTES_PER_ROW_PER_CTA == BYTES_PER_ROW, ""); enum { NUM_ELTS = Vec::NUM_ELTS }; using vec_t = typename Ktraits::vec_t; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_m = warp / Ktraits::WARPS_N; const int warp_n = warp % Ktraits::WARPS_N; const int tid_r = warp_n * THREADS_PER_WARP + lane; const int r = bidx * Ktraits::ROWS_PER_CTA + warp_m; const int c = warp_n * THREADS_PER_WARP + lane; const char *dw_ptr = static_cast(dw_); const char *x_ptr = static_cast(x_); const char *g_ptr = static_cast(g_); char *dx_ptr = static_cast(dx_); const compute_t *mu_ptr = static_cast(mu_); const compute_t *rs_ptr = static_cast(rs_); static_assert(COLS == THREADS_PER_ROW * LDGS * NUM_ELTS, ""); // smem for final reduction //__shared__ compute_t smem_[ROWS_PER_CTA * COLS]; extern __shared__ compute_t smem_[]; // static_assert(sizeof(smem_dw_sum) == 32*1024,""); // Using the grid stride loop we can assign multiple rows to each thread // by using a number of CTAs smaller than rows / ROWS_PER_CTA // We accumulate them here, one in smem, one in registers, because the smem // capacity is limited compute_t * dw_sum = &smem_dw_sum[warp_m * COLS + tid_r // * LDGS * NUM_ELTS]; compute_t dwy_sum[LDGS * NUM_ELTS]; compute_t dw_sum[LDGS * NUM_ELTS]; memset(dwy_sum, 0, sizeof(compute_t) * LDGS * NUM_ELTS); memset(dw_sum, 0, sizeof(compute_t) * LDGS * NUM_ELTS); // Debug 8 rows, 4B, 1024 cols __shared__ compute_t smem_mdy[ROWS_PER_CTA * WARPS_N]; __shared__ compute_t smem_mdyy[ROWS_PER_CTA * WARPS_N]; compute_t *mdy_shared = &smem_mdy[warp_m * WARPS_N]; compute_t *mdyy_shared = &smem_mdyy[warp_m * WARPS_N]; constexpr float rn = 1.f / float(COLS); Vec gamma[LDGS]; int col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { gamma[it].load_from(g_ptr + col * BYTES_PER_LDG); col += Ktraits::THREADS_PER_ROW; } // TODO if ROWS_PER_CTA does not divice rows, we might get divergence in the // last blocks with syncthreads! // grid stride over rows #pragma unroll 1 for (int row = r; row < rows; row += gridDim.x * ROWS_PER_CTA) { const compute_t mu_r = mu_ptr[row]; const compute_t rs_r = rs_ptr[row]; Vec dw[LDGS], x[LDGS], dx[LDGS]; int col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { dw[it].load_from(dw_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); x[it].load_from(x_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } // local reductions compute_t dy[LDGS * NUM_ELTS]; compute_t y[LDGS * NUM_ELTS]; compute_t mdy_local = 0.f; compute_t mdyy_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < Vec::NUM_ELTS; jt++) { compute_t x_tmp = x[it].data.elt[jt]; compute_t y_tmp = rs_r * (x_tmp - mu_r); compute_t dy_tmp = gamma[it].data.elt[jt] * dw[it].data.elt[jt]; compute_t dw_tmp = dw[it].data.elt[jt]; mdy_local += dy_tmp; mdyy_local += dy_tmp * y_tmp; dy[it * NUM_ELTS + jt] = dy_tmp; y[it * NUM_ELTS + jt] = y_tmp; dwy_sum[it * NUM_ELTS + jt] += dw_tmp * y_tmp; dw_sum[it * NUM_ELTS + jt] += dw_tmp; } } // reduction across row for mdy, mdyy if (WARPS_N == 1) { // no need to go through smem! #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { mdy_local += __shfl_xor_sync(uint32_t(-1), mdy_local, it); mdyy_local += __shfl_xor_sync(uint32_t(-1), mdyy_local, it); } mdy_local *= rn; mdyy_local *= rn; } else { #pragma unroll for (int it = 16; it > 0; it /= 2) { mdy_local += __shfl_down_sync(uint32_t(-1), mdy_local, it); mdyy_local += __shfl_down_sync(uint32_t(-1), mdyy_local, it); } // lane 0 holds the result! if (lane == 0) { mdy_shared[warp_n] = mdy_local; mdyy_shared[warp_n] = mdyy_local; } __syncthreads(); if (warp_n == 0 && lane == 0) { mdy_local = 0.f; mdyy_local = 0.f; for (int it = 0; it < WARPS_N; it++) { mdy_local += mdy_shared[it]; mdyy_local += mdyy_shared[it]; } mdy_shared[0] = mdy_local; mdyy_shared[0] = mdyy_local; } __syncthreads(); mdy_local = mdy_shared[0] * rn; mdyy_local = mdyy_shared[0] * rn; } #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { compute_t dy_tmp = dy[it * NUM_ELTS + jt]; compute_t y_tmp = y[it * NUM_ELTS + jt]; compute_t dx_tmp = compute_t(rs_r) * (dy_tmp - mdyy_local * y_tmp - mdy_local); dx[it].data.elt[jt] = dx_tmp; } } col = c; #pragma unroll for (int it = 0; it < LDGS; it++) { dx[it].store_to(dx_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += Ktraits::THREADS_PER_ROW; } } // end: grid stride loop // Finalize reduction of part dgamma and dbeta for this CTA // by reducing over the rows held across the WARPS_M warps enum { NUM_RES = COLS / Ktraits::THREADS_PER_CTA }; static_assert(NUM_RES * Ktraits::THREADS_PER_CTA == COLS, ""); compute_t *smem_write; smem_write = &smem_[warp_m * COLS + tid_r * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { smem_write[jt] = dw_sum[it * NUM_ELTS + jt]; } smem_write += THREADS_PER_ROW * NUM_ELTS; } __syncthreads(); compute_t cta_dw_sum[NUM_RES]; memset(cta_dw_sum, 0, sizeof(compute_t) * NUM_RES); for (int it = 0; it < ROWS_PER_CTA; it++) { for (int jt = 0; jt < NUM_RES; jt++) { cta_dw_sum[jt] += smem_[it * COLS + tidx + jt * Ktraits::THREADS_PER_CTA]; } } __syncthreads(); smem_write = &smem_[warp_m * COLS + tid_r * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { smem_write[jt] = dwy_sum[it * NUM_ELTS + jt]; } smem_write += THREADS_PER_ROW * NUM_ELTS; } __syncthreads(); compute_t cta_dwy_sum[NUM_RES]; memset(cta_dwy_sum, 0, sizeof(compute_t) * NUM_RES); for (int it = 0; it < ROWS_PER_CTA; it++) { for (int jt = 0; jt < NUM_RES; jt++) { cta_dwy_sum[jt] += smem_[it * COLS + tidx + jt * Ktraits::THREADS_PER_CTA]; } } compute_t *dgamma_part = static_cast(dg_) + bidx * COLS + tidx; for (int jt = 0; jt < NUM_RES; jt++) { *dgamma_part = cta_dwy_sum[jt]; dgamma_part += Ktraits::THREADS_PER_CTA; } compute_t *dbeta_part = static_cast(db_) + bidx * COLS + tidx; for (int jt = 0; jt < NUM_RES; jt++) { *dbeta_part = cta_dw_sum[jt]; dbeta_part += Ktraits::THREADS_PER_CTA; } } template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_bwd_finalize_kernel(void * __restrict__ dg_, void * __restrict__ db_, const void * __restrict__ dg_part_, const void * __restrict__ db_part_, const int rows ){ using Vec = typename Ktraits::Vec; enum { NUM_ELTS = Vec::NUM_ELTS }; using vec_t = typename Ktraits::vec_t; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { WARPS_M = Ktraits::WARPS_M }; enum { WARPS_N = Ktraits::WARPS_N }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { COLS = Ktraits::COLS }; enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum {VEC_COLS = BYTES_PER_ROW / BYTES_PER_LDG}; //dbg static_assert(VEC_COLS == COLS / NUM_ELTS, ""); //static_assert(VEC_COLS == 1024,""); const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_m = warp / Ktraits::WARPS_N; const int warp_n = warp % Ktraits::WARPS_N; const int tid_c = warp_n * THREADS_PER_WARP + lane; const int c =bidx * THREADS_PER_ROW + tid_c; const int r = warp_m; __shared__ compute_t smem_[(WARPS_M - 1) * THREADS_PER_ROW * NUM_ELTS]; //Will probably run this with WARPS_N = 1 and grid = 1024 / (32*4) = 8, or NUM_ELTS=1 and grid = 32 // and WARPS_M = 4 (or 1??) for(int col = c; col < VEC_COLS; col += gridDim.x * THREADS_PER_ROW){ const char* dg_part_ptr = static_cast(dg_part_) + r * BYTES_PER_ROW + col * BYTES_PER_LDG; const char* db_part_ptr = static_cast(db_part_) + r * BYTES_PER_ROW + col * BYTES_PER_LDG; compute_t dg_sum[NUM_ELTS]; compute_t db_sum[NUM_ELTS]; memset(dg_sum, 0, sizeof(compute_t) * NUM_ELTS); memset(db_sum, 0, sizeof(compute_t) * NUM_ELTS); #pragma unroll for(int row = r; row < rows;row += ROWS_PER_CTA){ Vec dg; Vec db; dg.load_from(dg_part_ptr); db.load_from(db_part_ptr); dg_part_ptr += ROWS_PER_CTA * BYTES_PER_ROW; db_part_ptr += ROWS_PER_CTA * BYTES_PER_ROW; #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_sum[jt] += dg.data.elt[jt]; db_sum[jt] += db.data.elt[jt]; } } // Finalize the reduction across rows of the CTA compute_t * smem_write; smem_write = smem_ + (warp_m -1) *THREADS_PER_ROW * NUM_ELTS + tid_c; if (warp_m > 0) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { *smem_write = dg_sum[jt]; smem_write+=THREADS_PER_ROW; } } __syncthreads(); compute_t *smem_read ; smem_read = smem_ + tid_c ; if (warp_m == 0) { #pragma unroll for (int it = 0; it < WARPS_M - 1; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_sum[jt] += *smem_read; smem_read += THREADS_PER_ROW; } } } __syncthreads(); smem_write = smem_ + (warp_m -1) *THREADS_PER_ROW * NUM_ELTS + tid_c; if (warp_m > 0) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { *smem_write = db_sum[jt]; smem_write+=THREADS_PER_ROW; } } __syncthreads(); smem_read = smem_ + tid_c; if (warp_m == 0) { #pragma unroll for (int it = 0; it < WARPS_M - 1; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { db_sum[jt] += *smem_read; smem_read += THREADS_PER_ROW; } } using vout_t = typename Vec_type::Type; union { vout_t raw; out_t elt[NUM_ELTS]; } dg_out, db_out; // out_t dg_out[NUM_ELTS], db_out[NUM_ELTS]; #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { dg_out.elt[jt] = dg_sum[jt]; db_out.elt[jt] = db_sum[jt]; } vout_t *dg_ptr = reinterpret_cast(dg_) + col ; vout_t *db_ptr = reinterpret_cast(db_) + col ; *dg_ptr = dg_out.raw; *db_ptr = db_out.raw; } } } template void launch(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, at::Tensor &dgamma_part, at::Tensor &dbeta_part, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, const int gridx, cudaStream_t stream){ if (cols == 1024) { using Ktraits = Kernel_traits; if (Ktraits::SMEM_BYTES >= 48 * 1024) { AT_CUDA_CHECK(cudaFuncSetAttribute( ln_bwd_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, Ktraits::SMEM_BYTES)); } ln_bwd_kernel <<>>( dx.data_ptr(), dgamma_part.data_ptr(), dbeta_part.data_ptr(), dw.data_ptr(), x.data_ptr(), mu.data_ptr(), rsigma.data_ptr(), gamma.data_ptr(), rows); using Ktraits2 = Kernel_traits; constexpr int grid2 = DIVUP(1024, Ktraits2::THREADS_PER_ROW * Ktraits2::Vec::NUM_ELTS); ln_bwd_finalize_kernel <<>>( dgamma.data_ptr(), dbeta.data_ptr(), dgamma_part.data_ptr(), dbeta_part.data_ptr(), gridx); } else { assert(false && "Not implemented"); } AT_CUDA_CHECK(cudaPeekAtLastError()); } void ln_bwd_cuda(at::Tensor &dx, at::Tensor &dgamma, at::Tensor &dbeta, const at::Tensor &dw, const at::Tensor &x, const at::Tensor &mu, const at::Tensor &rsigma, const at::Tensor &gamma, const int rows, const int cols, cudaStream_t stream) { const auto dtype = x.scalar_type(); const auto props = at::cuda::getCurrentDeviceProperties(); const int smCount = props->multiProcessorCount; // Launch 2 CTAs per SM const int grid = 2 * smCount; //request workspace for two-step reduction. We always reduce in FP32. auto opts = x.options(); auto dbeta_part = torch::empty({grid, cols}, opts.dtype(torch::kFloat32)); auto dgamma_part = torch::empty({grid, cols}, opts.dtype(torch::kFloat32)); if (dtype == torch::kFloat16) { launch(dx, dgamma, dbeta, dgamma_part, dbeta_part, dw, x, mu, rsigma, gamma, rows, cols, grid, stream); } else if (dtype == torch::kFloat32) { launch(dx, dgamma, dbeta, dgamma_part, dbeta_part, dw, x, mu, rsigma, gamma, rows, cols, grid, stream); } else { assert(false && "Not implemented"); } } ================================================ FILE: KoSimCSE/apex/contrib/csrc/layer_norm/ln_fwd_cuda_kernel.cu ================================================ #include "utils.cuh" #include "ln_kernel_traits.h" #include "ATen/cuda/CUDAContext.h" template __global__ __launch_bounds__(Ktraits::THREADS_PER_CTA) void ln_fwd_kernel( void *__restrict__ y_, void *__restrict__ mu_, void *__restrict__ rsigma_, const void *__restrict__ x_, const void *__restrict__ gamma_, const void *__restrict__ beta_, const float epsilon, int rows) { using Vec = typename Ktraits::Vec; using base_t = typename Ktraits::base_t; using compute_t = typename Ktraits::compute_t; enum { NUM_ELTS = Vec::NUM_ELTS }; enum { WARPS_N = Ktraits::WARPS_N }; enum { WARPS_M = Ktraits::WARPS_M }; enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA }; enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW }; enum { BYTES_PER_LDG = Ktraits::BYTES_PER_LDG }; static_assert(BYTES_PER_LDG == 16, ""); enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW }; enum { LDGS = BYTES_PER_ROW / Ktraits::BYTES_PER_ROW_PER_CTA }; static_assert(LDGS * Ktraits::BYTES_PER_ROW_PER_CTA == BYTES_PER_ROW, ""); const int tidx = threadIdx.x; const int bidx = blockIdx.x; const int lane = tidx % THREADS_PER_WARP; const int warp = tidx / THREADS_PER_WARP; const int warp_n = warp % WARPS_N; const int warp_m = warp / WARPS_N; const int c = warp_n * THREADS_PER_WARP + lane; const int r = bidx * ROWS_PER_CTA + warp_m; const char *x_ptr = static_cast(x_); const char *g_ptr = static_cast(gamma_); const char *b_ptr = static_cast(beta_); char *y_ptr = static_cast(y_); compute_t *mu_ptr = static_cast(mu_); compute_t *rs_ptr = static_cast(rsigma_); Vec gamma[LDGS]; Vec beta[LDGS]; #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { gamma[it].load_from(g_ptr + col * BYTES_PER_LDG); beta[it].load_from(b_ptr + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } constexpr compute_t rn = 1.f / compute_t(Ktraits::COLS); for (int row = r; row < rows; row += gridDim.x * ROWS_PER_CTA) { Vec x[LDGS]; #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { x[it].load_from(x_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } compute_t xf[LDGS * NUM_ELTS]; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { xf[it * NUM_ELTS + jt] = compute_t(x[it].data.elt[jt]); } } compute_t mu_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { mu_local += xf[it * NUM_ELTS + jt]; } } #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { mu_local += __shfl_xor_sync(uint32_t(-1), mu_local, it); } mu_local *= rn; if(lane == 0){ mu_ptr[row] = mu_local; } compute_t var_local = 0.f; #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { compute_t diff = xf[it * NUM_ELTS + jt] - mu_local; var_local += diff * diff; } } #pragma unroll for (int it = 1; it < THREADS_PER_WARP; it *= 2) { var_local += __shfl_xor_sync(uint32_t(-1), var_local, it); } compute_t rsigma = rsqrtf(var_local * rn + epsilon); if(lane == 0){ rs_ptr[row] = rsigma; } #pragma unroll for (int it = 0; it < LDGS; it++) { #pragma unroll for (int jt = 0; jt < NUM_ELTS; jt++) { base_t tmp = (rsigma * (xf[it * NUM_ELTS + jt] - mu_local)); x[it].data.elt[jt] = gamma[it].data.elt[jt] * tmp + beta[it].data.elt[jt]; } } #pragma unroll for (int it = 0, col = c; it < LDGS; it++) { x[it].store_to(y_ptr + row * BYTES_PER_ROW + col * BYTES_PER_LDG); col += THREADS_PER_ROW; } } } template void launch( at::Tensor & y, // BxSxhidden_size at::Tensor & mu, at::Tensor & rsigma, const at::Tensor & x, // BxSxhidden_size const at::Tensor & gamma, const at::Tensor & beta, const float epsilon, const int rows, const int cols, const int max_gridx, cudaStream_t stream ){ if (cols == 1024) { using Ktraits = Kernel_traits; const int grid = std::min(DIVUP(rows, Ktraits::ROWS_PER_CTA), max_gridx); ln_fwd_kernel<<>>( y.data_ptr(), mu.data_ptr(), rsigma.data_ptr(), x.data_ptr(), gamma.data_ptr(), beta.data_ptr(), epsilon, rows); } else { assert(false && "Not implemented"); } AT_CUDA_CHECK(cudaPeekAtLastError()); } void ln_fwd_cuda( at::Tensor & y, // BxSxhidden_size at::Tensor & mu, at::Tensor & rsigma, const at::Tensor & x, // BxSxhidden_size const at::Tensor & gamma, const at::Tensor & beta, const float epsilon, const int rows, const int cols, cudaStream_t stream ){ const auto dtype = x.scalar_type(); const auto props = at::cuda::getCurrentDeviceProperties(); const int max_gridx = props->maxGridSize[0]; //TODO // - Using dispatch macro costs 1% perf wtf?!?! // - Tune FP32 warps // - Add more sizes if (dtype == torch::kFloat16) { launch(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, max_gridx, stream); } else if (dtype == torch::kFloat32) { launch(y, mu, rsigma, x, gamma, beta, epsilon, rows, cols, max_gridx, stream); } else { assert(false && "Not implemented"); } } ================================================ FILE: KoSimCSE/apex/contrib/csrc/layer_norm/ln_kernel_traits.h ================================================ #pragma once constexpr uint32_t THREADS_PER_WARP = 32; template struct Kernel_traits { enum { WARPS_M = WARPS_M_ }; enum { WARPS_N = WARPS_N_ }; enum { COLS = COLS_ }; enum { BYTES_PER_LDG = BYTES_PER_LDG_ }; using Vec = Vec; using vec_t = typename Vec::vec_t; using base_t = typename Vec::base_t; using packed_t = typename Vec::packed_t; using compute_t = typename Vec::compute_t; using packed_compute_t = typename Vec::packed_compute_t; enum { THREADS_PER_ROW = WARPS_N * THREADS_PER_WARP }; enum { THREADS_PER_CTA = WARPS_M * THREADS_PER_ROW }; enum { ROWS_PER_CTA = WARPS_M }; enum { BYTES_PER_ROW = COLS * sizeof(base_t) }; enum { BYTES_PER_ROW_PER_CTA = THREADS_PER_ROW * BYTES_PER_LDG }; enum {SMEM_BYTES = ROWS_PER_CTA * COLS * sizeof(compute_t)}; }; ================================================ FILE: KoSimCSE/apex/contrib/csrc/layer_norm/utils.cuh ================================================ #pragma once #include "torch/extension.h" #include // for CUDNN_CHECK #define DIVUP(x, y) (((x) + ((y)-1)) / (y)) #define DISPATCH_FLOAT_AND_HALF(TYPE, NAME, ...) \ [&] { \ const auto &the_type = TYPE; \ /* don't use TYPE again in case it is an expensive or side-effect op */ \ at::ScalarType _st = ::detail::scalar_type(the_type); \ switch (_st) { \ AT_PRIVATE_CASE_TYPE(at::ScalarType::Float, float, __VA_ARGS__) \ AT_PRIVATE_CASE_TYPE(at::ScalarType::Half, at::Half, __VA_ARGS__) \ default: \ AT_ERROR(#NAME, " not implemented for '", toString(_st), "'"); \ } \ }() template struct Vec_type {}; template <> struct Vec_type<16> { using Type = uint4; static __device__ inline Type zero() { return make_uint4(0, 0, 0, 0); } }; template <> struct Vec_type<8> { using Type = uint2; static __device__ inline Type zero() { return make_uint2(0, 0); } }; template <> struct Vec_type<4> { using Type = uint32_t; static __device__ inline Type zero() { return 0; } }; template <> struct Vec_type<2> { using Type = uint16_t; static __device__ inline Type zero() { return 0; } }; template struct TypeInfo { using base_t = T; using packed_t = T; using compute_t = float; using packed_compute_t = float; }; template <> struct TypeInfo { using base_t = half; using packed_t = half2; using compute_t = float; using packed_compute_t = float2; }; template struct Vec { using base_t = typename TypeInfo::base_t; using packed_t = typename TypeInfo::packed_t; using compute_t = typename TypeInfo::compute_t; using packed_compute_t = typename TypeInfo::packed_compute_t; static_assert(Bytes % sizeof(base_t) == 0, ""); static_assert(Bytes % sizeof(packed_t) == 0, ""); enum { BYTES_PER_THREAD = Bytes }; enum { NUM_ELTS = Bytes / sizeof(base_t) }; enum { NUM_PACKED = Bytes / sizeof(packed_t) }; using vec_t = typename Vec_type::Type; using store_t = union { vec_t raw; base_t elt[NUM_ELTS]; packed_t packed[NUM_PACKED]; }; store_t data; __device__ Vec() { data.raw = Vec_type::zero(); } __device__ inline void load_from(const char *ptr) { data.raw = *reinterpret_cast(ptr); } __device__ inline void load_or_zero(const char *ptr, const bool is_valid) { data.raw = is_valid ? *reinterpret_cast(ptr) : Vec_type::zero(); } __device__ inline void store_to(char *ptr) const { *reinterpret_cast(ptr) = data.raw; } __device__ inline void store_valid(char *ptr, const bool is_valid) const { if (is_valid) *reinterpret_cast(ptr) = data.raw; } }; ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/additive_masked_softmax_dropout.cpp ================================================ #include #include #include namespace multihead_attn { namespace fused_softmax { namespace additive_mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const half* pad_mask, float dropout_prob ); torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool is_training, int heads, torch::Tensor const& input, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(input.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Half, "Only BYTE is supported"); } return fwd_cuda( is_training, heads, input, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } torch::Tensor bwd( bool use_mask, int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); // AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, softmax_results, dropout_mask, dropout_prob ); } } // end namespace mask_softmax_dropout } // end namespace fused_softmax } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::fused_softmax::additive_mask_softmax_dropout::fwd, "Self Multihead Attention masked softmax dropout -- Forward."); m.def("backward", &multihead_attn::fused_softmax::additive_mask_softmax_dropout::bwd, "Self Multihead Attention masked softmax dropout -- Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/additive_masked_softmax_dropout_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "softmax.h" #include "dropout.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace fused_softmax { namespace additive_mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const half* pad_mask, float dropout_prob ) { const int attn_batches = input.size(0); const int sequences = attn_batches / heads; const int q_seq_len = input.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = input.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* input_ptr = static_cast(input.data_ptr()); void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { softmax_success = dispatch_additive_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 return { dropout_results, dropout_mask, softmax_results }; } torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, float dropout_prob ) { const int attn_batches = output_grads.size(0); const int q_seq_len = output_grads.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations // torch::Tensor input_grads = torch::empty_like(output_grads); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); //backward pass is completely in-place return output_grads; } } } } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/dropout.h ================================================ #include #ifdef OLD_GENERATOR #include #else #include #endif #include #include #include const int UNROLL = 4; template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_fused_dropout_kernel(scalar_t const *inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p, std::pair seeds ) { accscalar_t pinv = accscalar_t(1)/p; IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; curandStatePhilox4_32_10_t state; curand_init( seeds.first, idx, seeds.second, &state); IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { float4 rand = curand_uniform4(&state); scalar_t src[UNROLL]; rand.x = rand.x <= p; rand.y = rand.y <= p; rand.z = rand.z <= p; rand.w = rand.w <= p; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = src[ii]*(&rand.x)[ii]*pinv; mask[li] = (uint8_t)(&rand.x)[ii]; } } __syncthreads(); } } template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_dropout_add_kernel(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p, std::pair seeds ) { accscalar_t pinv = accscalar_t(1)/p; IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; curandStatePhilox4_32_10_t state; curand_init( seeds.first, idx, seeds.second, &state); IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { float4 rand = curand_uniform4(&state); scalar_t src[UNROLL]; scalar_t add_src[UNROLL]; rand.x = rand.x <= p; rand.y = rand.y <= p; rand.z = rand.z <= p; rand.w = rand.w <= p; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; add_src[ii] = add_inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { accscalar_t int1 = src[ii] * (&rand.x)[ii] * pinv; outputs[li] = static_cast(static_cast(add_src[ii]) + int1); mask[li] = (uint8_t)(&rand.x)[ii]; } } __syncthreads(); } } template < typename scalar_t, typename accscalar_t, typename IndexType > __global__ void apex_add_kernel( scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, IndexType totalElements ) { IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { scalar_t src[UNROLL]; scalar_t add_src[UNROLL]; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = inputs[li]; add_src[ii] = add_inputs[li]; } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = src[ii] + add_src[ii]; } } __syncthreads(); } } template __global__ void apex_masked_scale_kernel(scalar_t const *inputs, scalar_t *outputs, uint8_t const *mask, IndexType totalElements, accscalar_t scale ) { IndexType idx = blockIdx.x * blockDim.x + threadIdx.x; IndexType rounded_size = ((totalElements - 1)/(blockDim.x * gridDim.x * UNROLL)+1) * blockDim.x * gridDim.x * UNROLL; for (IndexType linearIndex = idx; linearIndex < rounded_size; linearIndex += gridDim.x * blockDim.x*UNROLL) { scalar_t src[UNROLL]; scalar_t msk[UNROLL]; for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { src[ii] = static_cast(inputs[li]); msk[ii] = static_cast(mask[li]); } } for (int ii = 0; ii < UNROLL; ii++) { IndexType li = linearIndex + blockDim.x * gridDim.x * ii; if (li < totalElements) { outputs[li] = static_cast(src[ii]) * scale * static_cast(msk[ii]); } } } } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_fused_dropout_cuda(scalar_t const *inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p) { auto gen = at::cuda::detail::getDefaultCUDAGenerator(); int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); //number of times random will be generated per thread, to offset philox counter in thc random state int64_t counter_offset = ((totalElements - 1)/(block_size*grid.x*UNROLL)+1)*UNROLL; std::pair rng_engine_inputs; { // See Note [Acquire lock when using random generators] #ifdef OLD_GENERATOR std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_engine_inputs(counter_offset); #else std::lock_guard lock(gen.mutex()); rng_engine_inputs = at::check_generator(gen)->philox_engine_inputs(counter_offset); #endif } apex_fused_dropout_kernel<<>>(inputs, outputs, mask, totalElements, p, rng_engine_inputs); THCudaCheck(cudaGetLastError()); } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_dropout_add_cuda(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, uint8_t *mask, IndexType totalElements, accscalar_t p) { auto gen = at::cuda::detail::getDefaultCUDAGenerator(); int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); //number of times random will be generated per thread, to offset philox counter in thc random state int64_t counter_offset = ((totalElements - 1)/(block_size*grid.x*UNROLL)+1)*UNROLL; std::pair rng_engine_inputs; { // See Note [Acquire lock when using random generators] #ifdef OLD_GENERATOR std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_engine_inputs(counter_offset); #else std::lock_guard lock(gen.mutex()); rng_engine_inputs = at::check_generator(gen)->philox_engine_inputs(counter_offset); #endif } apex_dropout_add_kernel<<>>(inputs, add_inputs, outputs, mask, totalElements, p, rng_engine_inputs); THCudaCheck(cudaGetLastError()); } template < typename scalar_t, typename accscalar_t, typename IndexType > void apex_add_cuda(scalar_t const *inputs, scalar_t const *add_inputs, scalar_t *outputs, IndexType totalElements ) { int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); apex_add_kernel<<>>(inputs, add_inputs, outputs, totalElements); THCudaCheck(cudaGetLastError()); } template void apex_masked_scale_cuda(scalar_t const *inputs, scalar_t *outputs, uint8_t const *mask, IndexType totalElements, accscalar_t scale ) { int block_size = 256; dim3 dim_block(block_size); dim3 grid((totalElements + block_size -1)/block_size); unsigned int blocks_per_sm = at::cuda::getCurrentDeviceProperties()->maxThreadsPerMultiProcessor/block_size; grid.x = std::min((unsigned int)at::cuda::getCurrentDeviceProperties()->multiProcessorCount * blocks_per_sm, grid.x); apex_masked_scale_kernel<<>>(inputs, outputs, mask, totalElements, scale); THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/encdec_multihead_attn.cpp ================================================ #include #include namespace multihead_attn { namespace encdec { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_q_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_kv_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_q_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_kv_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_q_results, input_lin_kv_results, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace encdec } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::encdec::cublas_gemmex::fwd, "Encdec Multihead Attention Forward."); m.def("backward", &multihead_attn::encdec::cublas_gemmex::bwd, "Encdec Multihead Attention Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_cuda.cu ================================================ #include #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace encdec { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs_q.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_q_results = torch::empty({q_seq_len, sequences, output_lin_q_dim}, act_options); torch::Tensor input_lin_kv_results = torch::empty({k_seq_len, sequences, output_lin_kv_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs_q, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); void* k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); void* v_lin_results_ptr = static_cast(static_cast(input_lin_kv_results.data_ptr()) + head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Q Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_q_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_q_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_kv_dim, batches_kv, embed_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), k_lin_results_ptr, CUDA_R_16F, output_lin_kv_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(q_lin_results_ptr), lead_dim_q, batch_stride_q, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_q_results, input_lin_kv_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_q_grads = torch::empty_like(inputs_q); torch::Tensor input_kv_grads = torch::empty_like(inputs_kv); torch::Tensor input_weight_q_grads = torch::empty_like(input_weights_q); torch::Tensor input_weight_kv_grads = torch::empty_like(input_weights_kv); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_q_output_grads = torch::empty_like(input_lin_q_results); at::Tensor input_lin_kv_output_grads = torch::empty_like(input_lin_kv_results); auto q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); auto v_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()) + head_dim; auto q_lin_grads_ptr = static_cast(input_lin_q_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()); auto v_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()) + head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches_q, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim_kv, batch_stride_kv, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim_q, batch_stride_q, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim_q, batch_stride_q, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Input Linear Q Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, output_lin_q_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Q Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_q_dim, batches_q, static_cast(&alpha), static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_weight_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_kv, output_lin_kv_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_kv_dim, batches_kv, static_cast(&alpha), static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_weight_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_q_grads, input_kv_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace encdec } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add.cpp ================================================ #include #include namespace multihead_attn { namespace encdec_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_q_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_kv_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_mean.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_invvar.dim() == 1, "expected 1D tensor"); AT_ASSERTM(inputs_q.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs_kv.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights_q.dim() == 2, "expected 2D tensor"); AT_ASSERTM(input_weights_kv.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_add_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_q_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_kv_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_mean.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(lyr_nrm_invvar.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(inputs_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_q.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights_kv.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); AT_ASSERTM(dropout_add_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_q_results, input_lin_kv_results, lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, dropout_mask, dropout_add_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace encdec_norm_add } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::encdec_norm_add::cublas_gemmex::fwd, "Encdec Multihead Attention Plus Layer Norm and Residual Add Forward."); m.def("backward", &multihead_attn::encdec_norm_add::cublas_gemmex::bwd, "Encdec Multihead Attention Plus Layer Norm and Residual Add Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/encdec_multihead_attn_norm_add_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace encdec_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int total_tokens_q = batches_q * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs_q.options().requires_grad(false); auto lyr_nrm_options = act_options.dtype(torch::kFloat32); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor lyr_nrm_mean = torch::empty({batches_q}, lyr_nrm_options); torch::Tensor lyr_nrm_invvar = torch::empty({batches_q}, lyr_nrm_options); torch::Tensor lyr_nrm_results = torch::empty_like(inputs_q, act_options); torch::Tensor input_lin_q_results = torch::empty({q_seq_len, sequences, output_lin_q_dim}, act_options); torch::Tensor input_lin_kv_results = torch::empty({k_seq_len, sequences, output_lin_kv_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor output_lin_results = torch::empty_like(inputs_q, act_options); torch::Tensor dropout_add_mask = torch::empty_like(inputs_q, mask_options); torch::Tensor outputs = torch::empty_like(inputs_q, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); void* k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); void* v_lin_results_ptr = static_cast(static_cast(input_lin_kv_results.data_ptr()) + head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Layer Norm HostApplyLayerNorm( static_cast(lyr_nrm_results.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(batches_q), // n1 static_cast(embed_dim), // n2 1.0e-5, static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr())); // Input Linear Q Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_q_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, //static_cast(inputs_q.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_q_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_kv_dim, batches_kv, embed_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), k_lin_results_ptr, CUDA_R_16F, output_lin_kv_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(q_lin_results_ptr), lead_dim_q, batch_stride_q, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()), //static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_results.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // End-of-block Dropout-Add if (is_training) { apex_dropout_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(outputs.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens_q, (1.0f - dropout_prob)); } else { apex_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs_q.data_ptr()), static_cast(outputs.data_ptr()), total_tokens_q); } THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, input_lin_q_results, input_lin_kv_results, softmax_results, dropout_results, dropout_mask, matmul2_results, dropout_add_mask, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_q_results, torch::Tensor const& input_lin_kv_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs_q, torch::Tensor const& inputs_kv, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights_q, torch::Tensor const& input_weights_kv, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { const int embed_dim = inputs_q.size(2); const int sequences = inputs_q.size(1); const int q_seq_len = inputs_q.size(0); const int k_seq_len = inputs_kv.size(0); const int batches_q = sequences * q_seq_len; const int batches_kv = sequences * k_seq_len; const int total_tokens_q = batches_q * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_q_dim = embed_dim; const int output_lin_kv_dim = 2 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim_q = attn_batches * head_dim; const int lead_dim_kv = attn_batches * 2 *head_dim; const int batch_stride_q = head_dim; const int batch_stride_kv = 2 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_q_grads = torch::empty_like(inputs_q); torch::Tensor input_kv_grads = torch::empty_like(inputs_kv); torch::Tensor lyr_nrm_gamma_grads = torch::empty_like(lyr_nrm_gamma_weights); torch::Tensor lyr_nrm_beta_grads = torch::empty_like(lyr_nrm_beta_weights); torch::Tensor input_weight_q_grads = torch::empty_like(input_weights_q); torch::Tensor input_weight_kv_grads = torch::empty_like(input_weights_kv); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor dropout_add_grads = torch::empty_like(output_grads); at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_q_output_grads = torch::empty_like(input_lin_q_results); at::Tensor input_lin_kv_output_grads = torch::empty_like(input_lin_kv_results); at::Tensor input_lin_q_grads = torch::empty_like(inputs_q); auto q_lin_results_ptr = static_cast(input_lin_q_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()); auto v_lin_results_ptr = static_cast(input_lin_kv_results.data_ptr()) + head_dim; auto q_lin_grads_ptr = static_cast(input_lin_q_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()); auto v_lin_grads_ptr = static_cast(input_lin_kv_output_grads.data_ptr()) + head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Dropout Add Backward apex_masked_scale_cuda( static_cast(output_grads.data_ptr()), static_cast(dropout_add_grads.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens_q, (1.0 / (1.0 - dropout_prob))); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches_q, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim_kv, batch_stride_kv, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim_kv, batch_stride_kv, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim_q, batch_stride_q, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim_q, batch_stride_q, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim_kv, batch_stride_kv, attn_batches); // Input Linear Q Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_q, output_lin_q_dim, static_cast(&alpha), static_cast(input_weights_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), //static_cast(input_q_grads.data_ptr()), static_cast(input_lin_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Q Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_q_dim, batches_q, static_cast(&alpha), static_cast(inputs_q.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_q_dim, static_cast(&beta), static_cast(input_weight_q_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches_kv, output_lin_kv_dim, static_cast(&alpha), static_cast(input_weights_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear KV Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_kv_dim, batches_kv, static_cast(&alpha), static_cast(inputs_kv.data_ptr()), CUDA_R_16F, embed_dim, static_cast(k_lin_grads_ptr), CUDA_R_16F, output_lin_kv_dim, static_cast(&beta), static_cast(input_weight_kv_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Fused Layer Norm Bwd with Residual Add HostLayerNormGradient( static_cast(input_lin_q_grads.data_ptr()), static_cast(output_grads.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), inputs_q, static_cast(batches_q), // n1 static_cast(embed_dim), // n2 static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr()), 1.0e-5, static_cast(input_q_grads.data_ptr()), static_cast(lyr_nrm_gamma_grads.data_ptr()), static_cast(lyr_nrm_beta_grads.data_ptr()) ); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_q_grads, input_kv_grads, lyr_nrm_gamma_grads, lyr_nrm_beta_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace encdec_norm_add } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/layer_norm.h ================================================ #include "ATen/ATen.h" #include #include #include template __device__ void cuWelfordOnlineSum( const U curr, U& mu, U& sigma2, U& count) { count = count + U(1); U delta = curr - mu; U lmean = mu + delta / count; mu = lmean; U delta2 = curr - lmean; sigma2 = sigma2 + delta * delta2; } template __device__ void cuChanOnlineSum( const U muB, const U sigma2B, const U countB, U& mu, U& sigma2, U& count) { U delta = muB - mu; U nA = count; U nB = countB; count = count + countB; U nX = count; if (nX > U(0)) { nA = nA / nX; nB = nB / nX; mu = nA*mu + nB*muB; sigma2 = sigma2 + sigma2B + delta * delta * nA * nB * nX; } else { mu = U(0); sigma2 = U(0); } } template __device__ void cuWelfordMuSigma2( const T* __restrict__ vals, const int n1, const int n2, const int i1, U& mu, U& sigma2, U* buf) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensor is contiguous // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. // // compute variance and mean over n2 U count = U(0); mu= U(0); sigma2 = U(0); if (i1 < n1) { // one warp normalizes one n1 index, // synchronization is implicit // initialize with standard Welford algorithm const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; const T* lvals = vals + i1*n2; int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { U curr = static_cast(lvals[l+k]); cuWelfordOnlineSum(curr,mu,sigma2,count); } } for (; l < n2; ++l) { U curr = static_cast(lvals[l]); cuWelfordOnlineSum(curr,mu,sigma2,count); } // intra-warp reductions for (int l = 0; l <= 4; ++l) { int srcLaneB = (threadIdx.x+(1<(muB,sigma2B,countB,mu,sigma2,count); } // threadIdx.x == 0 has correct values for each warp // inter-warp reductions if (blockDim.y > 1) { U* ubuf = (U*)buf; U* ibuf = (U*)(ubuf + blockDim.y); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_y = threadIdx.y - offset; ubuf[2*wrt_y] = mu; ubuf[2*wrt_y+1] = sigma2; ibuf[wrt_y] = count; } __syncthreads(); // lower half merges if (threadIdx.x == 0 && threadIdx.y < offset) { U muB = ubuf[2*threadIdx.y]; U sigma2B = ubuf[2*threadIdx.y+1]; U countB = ibuf[threadIdx.y]; cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); } __syncthreads(); } // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values if (threadIdx.x == 0 && threadIdx.y == 0) { ubuf[0] = mu; ubuf[1] = sigma2; } __syncthreads(); mu = ubuf[0]; sigma2 = ubuf[1]/U(n2); // don't care about final value of count, we know count == n2 } else { mu = WARP_SHFL(mu, 0); sigma2 = WARP_SHFL(sigma2/U(n2), 0); } } } template<> __device__ void cuWelfordMuSigma2( const at::Half* __restrict__ vals, const int n1, const int n2, const int i1, float& mu, float& sigma2, float* buf) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensor is contiguous // 3) 2*blockDim.y*sizeof(U)+blockDim.y*sizeof(int) shared memory available. // // compute variance and mean over n2 float count = 0.0f; mu= float(0); sigma2 = float(0); if (i1 < n1) { // one warp normalizes one n1 index, // synchronization is implicit // initialize with standard Welford algorithm const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; const at::Half* lvals = vals + i1*n2; int l = 8*thrx; if ((((size_t)lvals)&3) != 0) { // 16 bit alignment // first thread consumes first point if (thrx == 0) { float curr = static_cast(lvals[0]); cuWelfordOnlineSum(curr,mu,sigma2,count); } ++l; } // at this point, lvals[l] are 32 bit aligned for all threads. for (; l+7 < n2; l+=8*numx) { for (int k = 0; k < 8; k+=2) { float2 curr = __half22float2(*((__half2*)(lvals+l+k))); cuWelfordOnlineSum(curr.x,mu,sigma2,count); cuWelfordOnlineSum(curr.y,mu,sigma2,count); } } for (; l < n2; ++l) { float curr = static_cast(lvals[l]); cuWelfordOnlineSum(curr,mu,sigma2,count); } // intra-warp reductions for (int l = 0; l <= 4; ++l) { int srcLaneB = (threadIdx.x+(1< 1) { float* ubuf = (float*)buf; float* ibuf = (float*)(ubuf + blockDim.y); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.x == 0 && threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_y = threadIdx.y - offset; ubuf[2*wrt_y] = mu; ubuf[2*wrt_y+1] = sigma2; ibuf[wrt_y] = count; } __syncthreads(); // lower half merges if (threadIdx.x == 0 && threadIdx.y < offset) { float muB = ubuf[2*threadIdx.y]; float sigma2B = ubuf[2*threadIdx.y+1]; float countB = ibuf[threadIdx.y]; cuChanOnlineSum(muB,sigma2B,countB,mu,sigma2,count); } __syncthreads(); } // threadIdx.x = 0 && threadIdx.y == 0 only thread that has correct values if (threadIdx.x == 0 && threadIdx.y == 0) { ubuf[0] = mu; ubuf[1] = sigma2; } __syncthreads(); mu = ubuf[0]; sigma2 = ubuf[1]/float(n2); // don't care about final value of count, we know count == n2 } else { mu = WARP_SHFL(mu, 0); sigma2 = WARP_SHFL(sigma2/float(n2), 0); } } } template U rsqrt(U v) { return U(1) / sqrt(v); } template<> float rsqrt(float v) { return rsqrtf(v); } template<> double rsqrt(double v) { return rsqrt(v); } namespace { // This is the un-specialized struct. Note that we prevent instantiation of this // struct by putting an undefined symbol in the function body so it won't compile. // template // struct SharedMemory // { // // Ensure that we won't compile any un-specialized types // __device__ T *getPointer() // { // extern __device__ void error(void); // error(); // return NULL; // } // }; // https://github.com/NVIDIA/apex/issues/246 template struct SharedMemory; template <> struct SharedMemory { __device__ float *getPointer() { extern __shared__ float s_float[]; return s_float; } }; template <> struct SharedMemory { __device__ double *getPointer() { extern __shared__ double s_double[]; return s_double; } }; } template __global__ void cuApplyLayerNorm( T* __restrict__ output_vals, U* __restrict__ mean, U* __restrict__ invvar, const T* __restrict__ vals, const int n1, const int n2, const U epsilon, const T* __restrict__ gamma, const T* __restrict__ beta ) { // Assumptions: // 1) blockDim.x == warpSize // 2) Tensors are contiguous // for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { SharedMemory shared; U* buf = shared.getPointer(); U mu,sigma2; cuWelfordMuSigma2(vals,n1,n2,i1,mu,sigma2,buf); const T* lvals = vals + i1*n2; T* ovals = output_vals + i1*n2; U c_invvar = rsqrt(sigma2 + epsilon); const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; if (gamma != NULL && beta != NULL) { for (int i = thrx; i < n2; i+=numx) { U curr = static_cast(lvals[i]); ovals[i] = gamma[i] * static_cast(c_invvar * (curr - mu)) + beta[i]; } } else { for (int i = thrx; i < n2; i+=numx) { U curr = static_cast(lvals[i]); ovals[i] = static_cast(c_invvar * (curr - mu)); } } if (threadIdx.x == 0 && threadIdx.y == 0) { mean[i1] = mu; invvar[i1] = c_invvar; } } } template __device__ void cuLoadWriteStridedInputs( const int i1_block, const int thr_load_row_off, const int thr_load_col_off, const int i2_off, const int row_stride, U* warp_buf1, U* warp_buf2, const T* input, const T* dout, const int i1_end, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar ) { int i1 = i1_block+thr_load_row_off; if (i1 < i1_end) { U curr_mean = mean[i1]; U curr_invvar = invvar[i1]; for (int k = 0; k < blockDim.y; ++k) { int i2 = i2_off + k; int load_idx = i1*n2+i2; int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; if (i2(input[load_idx]); U curr_dout = static_cast(dout[load_idx]); warp_buf1[write_idx] = curr_dout; warp_buf2[write_idx] = curr_dout * (curr_input - curr_mean) * curr_invvar; } else { warp_buf1[write_idx] = U(0); warp_buf2[write_idx] = U(0); } } } else { for (int k = 0; k < blockDim.y; ++k) { int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; warp_buf1[write_idx] = U(0); warp_buf2[write_idx] = U(0); } } } template __device__ void cuLoadAddStridedInputs( const int i1_block, const int thr_load_row_off, const int thr_load_col_off, const int i2_off, const int row_stride, U* warp_buf1, U* warp_buf2, const T* input, const T* dout, const int i1_end, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar ) { int i1 = i1_block+thr_load_row_off; if (i1 < i1_end) { U curr_mean = mean[i1]; U curr_invvar = invvar[i1]; for (int k = 0; k < blockDim.y; ++k) { int i2 = i2_off + k; int load_idx = i1*n2+i2; int write_idx = thr_load_row_off*row_stride+thr_load_col_off+k; if (i2(input[load_idx]); U curr_dout = static_cast(dout[load_idx]); warp_buf1[write_idx] += curr_dout; warp_buf2[write_idx] += curr_dout * (curr_input - curr_mean) * curr_invvar; } } } } template __global__ void cuComputePartGradGammaBeta( const T* __restrict__ dout, const T* __restrict__ input, const int n1, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar, U epsilon, U* part_grad_gamma, U* part_grad_beta) { const int numsegs_n1 = (n1+blockDim.y*blockDim.y-1) / (blockDim.y*blockDim.y); const int segs_per_block = (numsegs_n1 + gridDim.y - 1) / gridDim.y; const int i1_beg = blockIdx.y * segs_per_block * blockDim.y*blockDim.y; const int i1_beg_plus_one = (blockIdx.y+1) * segs_per_block * blockDim.y*blockDim.y; const int i1_end = i1_beg_plus_one < n1 ? i1_beg_plus_one : n1; const int row_stride = blockDim.x+1; const int thr_load_col_off = (threadIdx.x*blockDim.y)&(blockDim.x-1); const int thr_load_row_off = (threadIdx.x*blockDim.y)/blockDim.x + threadIdx.y*blockDim.y; const int i2_off = blockIdx.x * blockDim.x + thr_load_col_off; SharedMemory shared; U* buf = shared.getPointer(); // buf has at least blockDim.x * blockDim.y * blockDim.y + (blockDim.y - 1)*(blockDim.x/blockDim.y) elements U* warp_buf1 = (U*)buf; U* warp_buf2 = warp_buf1 + blockDim.y * blockDim.y * row_stride; // compute partial sums from strided inputs // do this to increase number of loads in flight cuLoadWriteStridedInputs(i1_beg,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); for (int i1_block = i1_beg+blockDim.y*blockDim.y; i1_block < i1_end; i1_block+=blockDim.y*blockDim.y) { cuLoadAddStridedInputs(i1_block,thr_load_row_off,thr_load_col_off,i2_off,row_stride,warp_buf1,warp_buf2,input,dout,i1_end,n2,mean,invvar); } __syncthreads(); // inter-warp reductions // sum within each warp U acc1 = U(0); U acc2 = U(0); for (int k = 0; k < blockDim.y; ++k) { int row1 = threadIdx.y + k*blockDim.y; int idx1 = row1*row_stride + threadIdx.x; acc1 += warp_buf1[idx1]; acc2 += warp_buf2[idx1]; } warp_buf1[threadIdx.y*row_stride+threadIdx.x] = acc1; warp_buf2[threadIdx.y*row_stride+threadIdx.x] = acc2; __syncthreads(); // sum all warps for (int offset = blockDim.y/2; offset > 1; offset /= 2) { if (threadIdx.y < offset) { int row1 = threadIdx.y; int row2 = threadIdx.y + offset; int idx1 = row1*row_stride + threadIdx.x; int idx2 = row2*row_stride + threadIdx.x; warp_buf1[idx1] += warp_buf1[idx2]; warp_buf2[idx1] += warp_buf2[idx2]; } __syncthreads(); } int i2 = blockIdx.x * blockDim.x + threadIdx.x; if (threadIdx.y == 0 && i2 < n2) { int row1 = threadIdx.y; int row2 = threadIdx.y + 1; int idx1 = row1*row_stride + threadIdx.x; int idx2 = row2*row_stride + threadIdx.x; part_grad_beta[blockIdx.y*n2+i2] = warp_buf1[idx1] + warp_buf1[idx2]; part_grad_gamma[blockIdx.y*n2+i2] = warp_buf2[idx1] + warp_buf2[idx2]; } } template __global__ void cuComputeGradGammaBeta( const U* part_grad_gamma, const U* part_grad_beta, const int part_size, const int n1, const int n2, T* grad_gamma, T* grad_beta) { // sum partial gradients for gamma and beta SharedMemory shared; U* buf = shared.getPointer(); int i2 = blockIdx.x * blockDim.x + threadIdx.x; if (i2 < n2) { // each warp does sequential reductions until reduced part_size is num_warps int num_warp_reductions = part_size / blockDim.y; U sum_gamma = U(0); U sum_beta = U(0); const U* part_grad_gamma_ptr = part_grad_gamma + threadIdx.y * num_warp_reductions * n2 + i2; const U* part_grad_beta_ptr = part_grad_beta + threadIdx.y * num_warp_reductions * n2 + i2; for (int warp_offset = 0; warp_offset < num_warp_reductions; ++warp_offset) { sum_gamma += part_grad_gamma_ptr[warp_offset*n2]; sum_beta += part_grad_beta_ptr[warp_offset*n2]; } // inter-warp reductions const int nbsize3 = blockDim.x * blockDim.y / 2; for (int offset = blockDim.y/2; offset >= 1; offset /= 2) { // top half write to shared memory if (threadIdx.y >= offset && threadIdx.y < 2*offset) { const int write_idx = (threadIdx.y - offset) * blockDim.x + threadIdx.x; buf[write_idx] = sum_gamma; buf[write_idx+nbsize3] = sum_beta; } __syncthreads(); // bottom half sums if (threadIdx.y < offset) { const int read_idx = threadIdx.y * blockDim.x + threadIdx.x; sum_gamma += buf[read_idx]; sum_beta += buf[read_idx+nbsize3]; } __syncthreads(); } // write out fully summed gradients if (threadIdx.y == 0) { grad_gamma[i2] = sum_gamma; grad_beta[i2] = sum_beta; } } } template __global__ void cuComputeGradInput( const T* __restrict__ dout, const T* __restrict__ dout_resid, const T* __restrict__ input, const int n1, const int n2, const U* __restrict__ mean, const U* __restrict__ invvar, U epsilon, const T* gamma, T* grad_input) { for (auto i1=blockIdx.y; i1 < n1; i1 += gridDim.y) { U sum_loss1 = U(0); U sum_loss2 = U(0); const U c_mean = mean[i1]; const U c_invvar = invvar[i1]; const T* k_input = input + i1*n2; const T* k_dout = dout + i1*n2; const T* k_dout_resid = dout_resid + i1*n2; const int numx = blockDim.x * blockDim.y; const int thrx = threadIdx.x + threadIdx.y * blockDim.x; if (gamma != NULL) { int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { const U c_h = static_cast(k_input[l+k]); const U c_loss = static_cast(k_dout[l+k]); sum_loss1 += c_loss * static_cast(gamma[l+k]); sum_loss2 += c_loss * static_cast(gamma[l+k]) * (c_h - c_mean) * c_invvar; } } for (; l < n2; ++l) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); sum_loss1 += c_loss * static_cast(gamma[l]); sum_loss2 += c_loss * static_cast(gamma[l]) * (c_h - c_mean) * c_invvar; } } else { int l = 4*thrx; for (; l+3 < n2; l+=4*numx) { for (int k = 0; k < 4; ++k) { const U c_h = static_cast(k_input[l+k]); const U c_loss = static_cast(k_dout[l+k]); sum_loss1 += c_loss; sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; } } for (; l < n2; ++l) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); sum_loss1 += c_loss; sum_loss2 += c_loss * (c_h - c_mean) * c_invvar; } } // intra-warp reductions for (int mask = blockDim.x/2; mask > 0; mask /= 2) { sum_loss1 += WARP_SHFL_XOR(sum_loss1, mask); sum_loss2 += WARP_SHFL_XOR(sum_loss2, mask); } // inter-warp reductions if (blockDim.y > 1) { SharedMemory shared; U* buf = shared.getPointer(); for (int offset = blockDim.y/2; offset > 0; offset /= 2) { // upper half of warps write to shared if (threadIdx.y >= offset && threadIdx.y < 2*offset) { const int wrt_i = (threadIdx.y - offset) * blockDim.x + threadIdx.x; buf[2*wrt_i] = sum_loss1; buf[2*wrt_i+1] = sum_loss2; } __syncthreads(); // lower half merges if (threadIdx.y < offset) { const int read_i = threadIdx.y * blockDim.x + threadIdx.x; sum_loss1 += buf[2*read_i]; sum_loss2 += buf[2*read_i+1]; } __syncthreads(); } if (threadIdx.y == 0) { buf[2*threadIdx.x] = sum_loss1; buf[2*threadIdx.x+1] = sum_loss2; } __syncthreads(); if (threadIdx.y !=0) { sum_loss1 = buf[2*threadIdx.x]; sum_loss2 = buf[2*threadIdx.x+1]; } } // all threads now have the two sums over l U fH = (U)n2; U term1 = (U(1) / fH) * c_invvar; T* k_grad_input = grad_input + i1*n2; if (gamma != NULL) { for (int l = thrx; l < n2; l+=numx) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); const T c_resid= static_cast(k_dout_resid[l]); U f_grad_input = fH * c_loss * static_cast(gamma[l]); f_grad_input -= sum_loss1; f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; f_grad_input *= term1; k_grad_input[l] = static_cast(f_grad_input)+c_resid; } } else { for (int l = thrx; l < n2; l+=numx) { const U c_h = static_cast(k_input[l]); const U c_loss = static_cast(k_dout[l]); const T c_resid= static_cast(k_dout_resid[l]); U f_grad_input = fH * c_loss; f_grad_input -= sum_loss1; f_grad_input -= (c_h - c_mean) * c_invvar * sum_loss2; f_grad_input *= term1; k_grad_input[l] = static_cast(f_grad_input)+c_resid; } } } } template void HostApplyLayerNorm( T* output, U* mean, U* invvar, const T* input, int n1, int n2, double epsilon, const T* gamma, const T* beta ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); const dim3 threads(32,4,1); const uint64_t maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; const dim3 blocks(1, std::min((uint64_t)n1, maxGridY), 1); int nshared = threads.y > 1 ? threads.y*sizeof(U)+(threads.y/2)*sizeof(U) : 0; cuApplyLayerNorm<<>>( output, mean, invvar, input, n1,n2, U(epsilon), gamma,beta); } template void HostLayerNormGradient( const T* dout, const T* dout_resid, const U* mean, const U* invvar, const at::Tensor& input, int n1, int n2, const T* gamma, const T* beta, double epsilon, T* grad_input, T* grad_gamma, T* grad_beta ) { auto stream = at::cuda::getCurrentCUDAStream().stream(); if (gamma != NULL && beta != NULL) { // compute grad_gamma(j) and grad_beta(j) const int part_size = 16; const dim3 threads2(32,4,1); const dim3 blocks2((n2+threads2.x-1)/threads2.x,part_size,1); const int nshared2_a = 2 * sizeof(U) * threads2.y * threads2.y * (threads2.x + 1); const int nshared2_b = threads2.x * threads2.y * sizeof(U); const int nshared2 = nshared2_a > nshared2_b ? nshared2_a : nshared2_b; at::Tensor part_grad_gamma = at::empty({part_size,n2}, input.options().dtype(input.scalar_type()==at::ScalarType::Half ? at::ScalarType::Float : input.scalar_type())); at::Tensor part_grad_beta = at::empty_like(part_grad_gamma); cuComputePartGradGammaBeta<<>>( dout, static_cast(input.data_ptr()), n1,n2, mean, invvar, U(epsilon), static_cast(part_grad_gamma.data_ptr()), static_cast(part_grad_beta.data_ptr())); const dim3 threads3(32,8,1); const dim3 blocks3((n2+threads2.x-1)/threads2.x,1,1); const int nshared3 = threads3.x * threads3.y * sizeof(U); cuComputeGradGammaBeta<<>>( static_cast(part_grad_gamma.data_ptr()), static_cast(part_grad_beta.data_ptr()), part_size, n1,n2, grad_gamma, grad_beta); } // compute grad_input const uint64_t maxGridY = at::cuda::getCurrentDeviceProperties()->maxGridSize[1]; const dim3 blocks1(1, std::min((uint64_t)n1, maxGridY), 1); const dim3 threads1(32,4,1); int nshared = threads1.y > 1 ? threads1.y*threads1.x*sizeof(U) : 0; cuComputeGradInput<<>>( dout, dout_resid, static_cast(input.data_ptr()), n1,n2, mean, invvar, U(epsilon), gamma, grad_input); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/masked_softmax_dropout.cpp ================================================ #include #include namespace multihead_attn { namespace fused_softmax { namespace mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const uint8_t* pad_mask, float dropout_prob ); torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, const uint8_t *padding_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool is_training, int heads, torch::Tensor const& input, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(input.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( is_training, heads, input, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } torch::Tensor bwd( bool use_mask, int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, torch::Tensor const& padding_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); // AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, softmax_results, dropout_mask, use_mask ? static_cast(padding_mask.data_ptr()) : nullptr, dropout_prob ); } } // end namespace mask_softmax_dropout } // end namespace fused_softmax } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::fused_softmax::mask_softmax_dropout::fwd, "Self Multihead Attention masked softmax dropout -- Forward."); m.def("backward", &multihead_attn::fused_softmax::mask_softmax_dropout::bwd, "Self Multihead Attention masked softmax dropout -- Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/masked_softmax_dropout_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "softmax.h" #include "dropout.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace fused_softmax { namespace mask_softmax_dropout { std::vector fwd_cuda( bool is_training, int heads, torch::Tensor const& input, const uint8_t* pad_mask, float dropout_prob ) { const int attn_batches = input.size(0); const int sequences = attn_batches / heads; const int q_seq_len = input.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = input.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* input_ptr = static_cast(input.data_ptr()); void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(input_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 return { dropout_results, dropout_mask, softmax_results }; } torch::Tensor bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& softmax_results, torch::Tensor const& dropout_mask, const uint8_t *padding_mask, float dropout_prob ) { const int attn_batches = output_grads.size(0); const int q_seq_len = output_grads.size(1); const int k_seq_len = q_seq_len; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations // torch::Tensor input_grads = torch::empty_like(output_grads); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad if (padding_mask == nullptr) { dispatch_masked_scale_softmax_backward_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); } else{ dispatch_masked_scale_softmax_backward_masked_out_stream( static_cast(output_grads.data_ptr()), static_cast(output_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), static_cast(padding_mask), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, heads, stream); } //backward pass is completely in-place return output_grads; } } } } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/philox.h ================================================ #pragma once //Philox CUDA. class Philox { public: __device__ inline Philox(unsigned long long seed, unsigned long long subsequence, unsigned long long offset) { key.x = (unsigned int)seed; key.y = (unsigned int)(seed >> 32); counter = make_uint4(0, 0, 0, 0); counter.z = (unsigned int)(subsequence); counter.w = (unsigned int)(subsequence >> 32); STATE = 0; incr_n(offset / 4); } __device__ inline uint4 operator()() { if(STATE == 0) { uint4 counter_ = counter; uint2 key_ = key; //7-round philox for(int i = 0; i < 6; i++) { counter_ = single_round(counter_, key_); key_.x += (kPhilox10A); key_.y += (kPhilox10B); } output = single_round(counter_, key_); incr(); } //return a float4 directly //unsigned long ret; //switch(STATE) { // case 0: ret = output.x; break; // case 1: ret = output.y; break; // case 2: ret = output.z; break; // case 3: ret = output.w; break; //} //STATE = (STATE + 1) % 4; return output; } private: uint4 counter; uint4 output; uint2 key; unsigned int STATE; __device__ inline void incr_n(unsigned long long n) { unsigned int nlo = (unsigned int)(n); unsigned int nhi = (unsigned int)(n >> 32); counter.x += nlo; if (counter.x < nlo) nhi++; counter.y += nhi; if (nhi <= counter.y) return; if (++counter.z) return; ++counter.w; } __device__ inline void incr() { if (++counter.x) return; if (++counter.y) return; if (++counter.z) return; ++counter.w; } __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, unsigned int *result_high) { *result_high = __umulhi(a, b); return a*b; } __device__ inline uint4 single_round(uint4 ctr, uint2 key) { unsigned int hi0; unsigned int hi1; unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; return ret; } static const unsigned long kPhilox10A = 0x9E3779B9; static const unsigned long kPhilox10B = 0xBB67AE85; static const unsigned long kPhiloxSA = 0xD2511F53; static const unsigned long kPhiloxSB = 0xCD9E8D57; }; // Inverse of 2^32. #define M_RAN_INVM32 2.3283064e-10f __device__ __inline__ float4 uniform4(uint4 x) { return make_float4(x.x * M_RAN_INVM32, x.y * M_RAN_INVM32, x.z * M_RAN_INVM32,x.w * M_RAN_INVM32); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn.cpp ================================================ #include #include namespace multihead_attn { namespace self { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self::cublas_gemmex::fwd, "Self Multihead Attention Forward."); m.def("backward", &multihead_attn::self::cublas_gemmex::bwd, "Self Multihead Attention Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias.cpp ================================================ #include #include namespace multihead_attn { namespace self_bias { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, //torch::Tensor const& input_biases, //torch::Tensor const& output_biases, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_bias::cublas_gemmex::fwd, "Self Multihead Attention with Bias -- Forward."); m.def("backward", &multihead_attn::self_bias::cublas_gemmex::bwd, "Self Multihead Attention with Bias -- Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_additive_mask.cpp ================================================ #include #include #include namespace multihead_attn { namespace self_bias_additive_mask { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const half* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, // torch::Tensor const& softmax_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, //torch::Tensor const& input_biases, //torch::Tensor const& output_biases, torch::Tensor const& dropout_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(use_mask , "no mask is not supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Half, "Only Half is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda( heads, output_grads, matmul2_results, dropout_results, bmm1_results, pad_mask, input_lin_results, inputs, input_weights, output_weights, dropout_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_bias_additive_mask::cublas_gemmex::fwd, "Self Multihead Attention with Bias -- Forward."); m.def("backward", &multihead_attn::self_bias_additive_mask::cublas_gemmex::bwd, "Self Multihead Attention with Bias -- Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_additive_mask_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_bias_additive_mask { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const half* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta_zero = 0.0; const float beta_one = 1.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor bmm1_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* bmm1_results_ptr = static_cast(bmm1_results.data_ptr()); void* dropout_results_ptr = static_cast(dropout_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd input_lin_results.copy_(input_biases); THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta_zero, static_cast(bmm1_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (is_training) { softmax_success = dispatch_additive_masked_softmax_dropout( reinterpret_cast(dropout_results_ptr), (is_training) ? reinterpret_cast(dropout_mask.data_ptr()) : nullptr, reinterpret_cast(bmm1_results_ptr), pad_mask, attn_batches*q_seq_len*q_seq_len, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences, 1.0f-dropout_prob, stream); } else { softmax_success = dispatch_additive_masked_softmax( reinterpret_cast(dropout_results_ptr),//this is actually softmax results, but making it consistent for the next function reinterpret_cast(bmm1_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta_zero, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); outputs.copy_(output_biases); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, bmm1_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& bmm1_results, torch::Tensor const& pad_mask, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto output_bias_grads = output_grads.view({-1, embed_dim}) .sum(0, false); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_recompute( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(bmm1_results.data_ptr()), reinterpret_cast(pad_mask.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len/sequences, attn_batches*q_seq_len, stream); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(input_lin_output_grads.data_ptr()), //static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto input_bias_grads = input_lin_output_grads.view({-1, output_lin_dim}).sum(0, false); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads, input_bias_grads, output_bias_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_bias_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_bias { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& input_biases, torch::Tensor const& output_biases, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta_zero = 0.0; const float beta_one = 1.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd input_lin_results.copy_(input_biases); THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta_zero, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } if (is_training) { //use at:: function so that C++ version generates the same random mask as python version auto dropout_tuple = at::_fused_dropout(softmax_results, 1.0f-dropout_prob); dropout_results = std::get<0>(dropout_tuple); dropout_mask = std::get<1>(dropout_tuple); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta_zero, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); outputs.copy_(output_biases); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta_one), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO1_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto output_bias_grads = output_grads.view({-1, embed_dim}) .sum(0, false); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability // Softmax Grad dispatch_masked_scale_softmax_backward_stream( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), static_cast(dropout_mask.data_ptr()), 1.0/(1.0-dropout_prob), k_seq_len, k_seq_len, attn_batches*q_seq_len, stream); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(input_lin_output_grads.data_ptr()), //static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); auto input_bias_grads = input_lin_output_grads.view({-1, output_lin_dim}).sum(0, false); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads, input_bias_grads, output_bias_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Input Linear Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(outputs.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& inputs, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations at::Tensor output_lin_grads = torch::empty_like(matmul2_results); at::Tensor matmul2_grads = torch::empty_like(dropout_results); at::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(output_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), static_cast(inputs.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, input_weight_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace self } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add.cpp ================================================ #include #include namespace multihead_attn { namespace self_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ); std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector fwd( bool use_mask, bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& pad_mask, float dropout_prob ) { AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); if (use_mask) { AT_ASSERTM(pad_mask.dim() == 2, "expected 2D tensor"); AT_ASSERTM(pad_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); } return fwd_cuda( use_time_mask, is_training, heads, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, use_mask ? static_cast(pad_mask.data_ptr()) : nullptr, dropout_prob ); } std::vector bwd( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { AT_ASSERTM(output_grads.dim() == 3, "expected 3D tensor"); AT_ASSERTM(matmul2_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(softmax_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(input_lin_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_results.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_mean.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_invvar.dim() == 1, "expected 1D tensor"); AT_ASSERTM(inputs.dim() == 3, "expected 3D tensor"); AT_ASSERTM(lyr_nrm_gamma_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(lyr_nrm_beta_weights.dim() == 1, "expected 1D tensor"); AT_ASSERTM(input_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(output_weights.dim() == 2, "expected 2D tensor"); AT_ASSERTM(dropout_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(dropout_add_mask.dim() == 3, "expected 3D tensor"); AT_ASSERTM(output_grads.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(matmul2_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(softmax_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_lin_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_results.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_mean.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(lyr_nrm_invvar.type().scalarType() == at::ScalarType::Float, "Only FLOAT is supported"); AT_ASSERTM(inputs.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_gamma_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(lyr_nrm_beta_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(input_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(output_weights.type().scalarType() == at::ScalarType::Half, "Only HALF is supported"); AT_ASSERTM(dropout_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); AT_ASSERTM(dropout_add_mask.type().scalarType() == at::ScalarType::Byte, "Only BYTE is supported"); return bwd_cuda(heads, output_grads, matmul2_results, dropout_results, softmax_results, input_lin_results, lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, dropout_mask, dropout_add_mask, dropout_prob ); } } // end namespace cublas_gemmex } // end namespace self_norm_add } // end namespace multihead_attn PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &multihead_attn::self_norm_add::cublas_gemmex::fwd, "Self Multihead Attention Plus Layer Norm and Residual Add Forward."); m.def("backward", &multihead_attn::self_norm_add::cublas_gemmex::bwd, "Self Multihead Attention Plus Layer Norm and Residual Add Backward."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/self_multihead_attn_norm_add_cuda.cu ================================================ #include #include #include #include #include #include #include #include "THC/THC.h" #include #include #include #include "strided_batched_gemm.h" #include "softmax.h" #include "dropout.h" #include "layer_norm.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; namespace multihead_attn { namespace self_norm_add { namespace cublas_gemmex { std::vector fwd_cuda( bool use_time_mask, bool is_training, int heads, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, const uint8_t* pad_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int total_tokens = batches * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // There is no reason to use more than one stream as every kernel is // sequentially dependent cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // 3 Intermediate Results + Output (Note: dropout intermediates are generated by ATen library code) auto act_options = inputs.options().requires_grad(false); auto lyr_nrm_options = act_options.dtype(torch::kFloat32); auto mask_options = act_options.dtype(torch::kUInt8); torch::Tensor lyr_nrm_mean = torch::empty({batches}, lyr_nrm_options); torch::Tensor lyr_nrm_invvar = torch::empty({batches}, lyr_nrm_options); torch::Tensor lyr_nrm_results = torch::empty_like(inputs, act_options); torch::Tensor input_lin_results = torch::empty({q_seq_len, sequences, output_lin_dim}, act_options); torch::Tensor softmax_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_results = torch::empty({attn_batches, q_seq_len, k_seq_len}, act_options); torch::Tensor dropout_mask = torch::empty({attn_batches, q_seq_len, k_seq_len}, mask_options); torch::Tensor matmul2_results = torch::empty({q_seq_len, attn_batches, head_dim}, act_options); torch::Tensor output_lin_results= torch::empty_like(inputs, act_options); torch::Tensor dropout_add_mask = torch::empty_like(inputs, mask_options); torch::Tensor outputs = torch::empty_like(inputs, act_options); // Input Linear Results Pointers to Q, K, and V of interviewed activations void* q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); void* k_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + head_dim); void* v_lin_results_ptr = static_cast(static_cast(input_lin_results.data_ptr()) + 2*head_dim); // Softmax Intermediate Result Ptr (used by Matmul1 -> Softmax) void* softmax_results_ptr = static_cast(softmax_results.data_ptr()); char a_layout_t{'t'}; char a_layout_n{'n'}; char b_layout_n{'n'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Layer Norm HostApplyLayerNorm( static_cast(lyr_nrm_results.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), static_cast(inputs.data_ptr()), static_cast(batches), // n1 static_cast(embed_dim), // n2 1.0e-5, static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr())); // Input Linear Fwd THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, output_lin_dim, batches, embed_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, //static_cast(inputs.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), q_lin_results_ptr, CUDA_R_16F, output_lin_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul1 of Dot-Product Attention Plus scaling by 1/Sqrt(head size) gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, scale, static_cast(k_lin_results_ptr), lead_dim, batch_stride, static_cast(q_lin_results_ptr), lead_dim, batch_stride, beta, static_cast(softmax_results_ptr), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Padded Softmax bool softmax_success = false; if (pad_mask == nullptr) { softmax_success = dispatch_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), k_seq_len, k_seq_len, attn_batches*q_seq_len); } else { if (use_time_mask) { softmax_success = dispatch_time_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, q_seq_len); } else { softmax_success = dispatch_masked_softmax( reinterpret_cast(softmax_results_ptr), reinterpret_cast(softmax_results_ptr), pad_mask, k_seq_len, k_seq_len, attn_batches*q_seq_len, attn_batches*q_seq_len/sequences); } } assert(softmax_success); if (is_training) { apex_fused_dropout_cuda( static_cast(softmax_results.data_ptr()), static_cast(dropout_results.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0f - dropout_prob)); } // Matmul2 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, (is_training) ? static_cast(dropout_results.data_ptr()) : static_cast(softmax_results.data_ptr()) , //static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, static_cast(matmul2_results.data_ptr()), head_dim*attn_batches, head_dim, attn_batches); // Output Linear THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_T, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_results.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // End-of-block Dropout-Add if (is_training) { apex_dropout_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs.data_ptr()), static_cast(outputs.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens, (1.0f - dropout_prob)); } else { apex_add_cuda( static_cast(output_lin_results.data_ptr()), static_cast(inputs.data_ptr()), static_cast(outputs.data_ptr()), total_tokens); } THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { lyr_nrm_results, lyr_nrm_mean, lyr_nrm_invvar, input_lin_results, softmax_results, dropout_results, dropout_mask, matmul2_results, dropout_add_mask, outputs }; } std::vector bwd_cuda( int heads, torch::Tensor const& output_grads, torch::Tensor const& matmul2_results, torch::Tensor const& dropout_results, torch::Tensor const& softmax_results, torch::Tensor const& input_lin_results, torch::Tensor const& lyr_nrm_results, torch::Tensor const& lyr_nrm_mean, torch::Tensor const& lyr_nrm_invvar, torch::Tensor const& inputs, torch::Tensor const& lyr_nrm_gamma_weights, torch::Tensor const& lyr_nrm_beta_weights, torch::Tensor const& input_weights, torch::Tensor const& output_weights, torch::Tensor const& dropout_mask, torch::Tensor const& dropout_add_mask, float dropout_prob ) { const int embed_dim = inputs.size(2); const int sequences = inputs.size(1); const int q_seq_len = inputs.size(0); const int k_seq_len = q_seq_len; const int batches = sequences * q_seq_len; const int total_tokens = batches * embed_dim; const int head_dim = embed_dim / heads; const int output_lin_dim = 3 * embed_dim; const int attn_batches = heads * sequences; const int lead_dim = attn_batches * 3 * head_dim; const int batch_stride = 3 * head_dim; const int dropout_elems = attn_batches * q_seq_len * k_seq_len; const float alpha = 1.0; const float beta = 0.0; const float scale = 1.0 / sqrt(static_cast(head_dim)); // TODO: Streams can be used in Backprop but I haven't added more than one // in my first attempt to create the code cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); // Output Tensor Allocations torch::Tensor input_grads = torch::empty_like(inputs); torch::Tensor lyr_nrm_gamma_grads = torch::empty_like(lyr_nrm_gamma_weights); torch::Tensor lyr_nrm_beta_grads = torch::empty_like(lyr_nrm_beta_weights); torch::Tensor input_weight_grads = torch::empty_like(input_weights); torch::Tensor output_weight_grads = torch::empty_like(output_weights); // Intermediate Tensor Allocations torch::Tensor dropout_add_grads = torch::empty_like(output_grads); torch::Tensor output_lin_grads = torch::empty_like(matmul2_results); torch::Tensor matmul2_grads = torch::empty_like(dropout_results); torch::Tensor input_lin_output_grads = torch::empty_like(input_lin_results); torch::Tensor input_lin_grads = torch::empty_like(inputs); auto q_lin_results_ptr = static_cast(input_lin_results.data_ptr()); auto k_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + head_dim; auto v_lin_results_ptr = static_cast(input_lin_results.data_ptr()) + 2*head_dim; auto q_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()); auto k_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + head_dim; auto v_lin_grads_ptr = static_cast(input_lin_output_grads.data_ptr()) + 2*head_dim; char a_layout_n{'n'}; char a_layout_t{'t'}; char b_layout_n{'n'}; char b_layout_t{'t'}; THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); // Dropout Add Backward apex_masked_scale_cuda( static_cast(output_grads.data_ptr()), static_cast(dropout_add_grads.data_ptr()), static_cast(dropout_add_mask.data_ptr()), total_tokens, (1.0 / (1.0 - dropout_prob))); // Output Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, embed_dim, static_cast(&alpha), static_cast(output_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Output Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, embed_dim, batches, static_cast(&alpha), static_cast(matmul2_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(dropout_add_grads.data_ptr()), CUDA_R_16F, embed_dim, static_cast(&beta), static_cast(output_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // MatMul2 Dgrad1 gemm_switch_fp32accum( state, a_layout_t, b_layout_n, k_seq_len, q_seq_len, head_dim, alpha, static_cast(v_lin_results_ptr), lead_dim, batch_stride, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, beta, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, attn_batches); // Matmul2 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, alpha, static_cast(output_lin_grads.data_ptr()), head_dim*attn_batches, head_dim, static_cast(dropout_results.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, v_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Apply Dropout Mask and Scale by Dropout Probability apex_masked_scale_cuda( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), static_cast(dropout_mask.data_ptr()), dropout_elems, (1.0 / (1.0 - dropout_prob))); // Softmax Grad bool softmax_success = false; softmax_success = dispatch_softmax_backward( static_cast(matmul2_grads.data_ptr()), static_cast(matmul2_grads.data_ptr()), reinterpret_cast(softmax_results.data_ptr()), k_seq_len, k_seq_len, attn_batches*q_seq_len); assert(softmax_success); // Matmul1 Dgrad1 gemm_switch_fp32accum( state, a_layout_n, b_layout_n, head_dim, q_seq_len, k_seq_len, scale, k_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, q_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Matmul1 Dgrad2 gemm_switch_fp32accum( state, a_layout_n, b_layout_t, head_dim, k_seq_len, q_seq_len, scale, q_lin_results_ptr, lead_dim, batch_stride, static_cast(matmul2_grads.data_ptr()), k_seq_len, k_seq_len*q_seq_len, beta, k_lin_grads_ptr, lead_dim, batch_stride, attn_batches); // Input Linear Dgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, embed_dim, batches, output_lin_dim, static_cast(&alpha), static_cast(input_weights.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), //static_cast(input_grads.data_ptr()), static_cast(input_lin_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, //CUBLAS_GEMM_ALGO10_TENSOR_OP)); CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Input Linear Wgrad THCublasCheck(cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_T, embed_dim, output_lin_dim, batches, static_cast(&alpha), //static_cast(inputs.data_ptr()), static_cast(lyr_nrm_results.data_ptr()), CUDA_R_16F, embed_dim, static_cast(q_lin_grads_ptr), CUDA_R_16F, output_lin_dim, static_cast(&beta), static_cast(input_weight_grads.data_ptr()), CUDA_R_16F, embed_dim, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP)); // Fused Layer Norm Bwd with Residual Add HostLayerNormGradient( static_cast(input_lin_grads.data_ptr()), static_cast(output_grads.data_ptr()), static_cast(lyr_nrm_mean.data_ptr()), static_cast(lyr_nrm_invvar.data_ptr()), inputs, static_cast(batches), // n1 static_cast(embed_dim), // n2 static_cast(lyr_nrm_gamma_weights.data_ptr()), static_cast(lyr_nrm_beta_weights.data_ptr()), 1.0e-5, static_cast(input_grads.data_ptr()), static_cast(lyr_nrm_gamma_grads.data_ptr()), static_cast(lyr_nrm_beta_grads.data_ptr()) ); THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); return { input_grads, lyr_nrm_gamma_grads, lyr_nrm_beta_grads, input_weight_grads, output_weight_grads }; } } // end namespace cublas_gemmex } // end namespace self_norm_add } // end namespace multihead_attn ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/softmax.h ================================================ #pragma once #include #include #include #include "philox.h" #include #include #include #include #include #include namespace { template __device__ __inline__ void copy_vector(Datatype *dst, const Datatype *src); template <> __device__ __inline__ void copy_vector<__half, 1>(__half *dst, const __half *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector(float *dst, const float *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector<__half, 4>(__half *dst, const __half *src) { *((float2*) dst) = *((float2*) src); } template <> __device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) { *dst = *src; } template <> __device__ __inline__ void copy_vector(uint8_t *dst, const uint8_t *src) {*((half2*) dst) = *((half2*) src); } template __device__ __inline__ void apply_mask(Datatype *dst, Datatype value, const uint8_t *src); template <> __device__ __inline__ void apply_mask<__half, 1>(__half *dst, __half value, const uint8_t *src) { if (*src == 1) { *dst = value; } } template __device__ __inline__ void apply_additive_mask(Datatype *dst, const Datatype *additive_mask); template <> __device__ __inline__ void apply_additive_mask<__half, 1>(__half *dst, const __half *additive_mask) { *dst += *additive_mask; } template <> __device__ __inline__ void apply_additive_mask<__half, 4>(__half *dst, const __half *additive_mask) { *dst += *additive_mask; *(dst+1) += *(additive_mask+1); *(dst+2) += *(additive_mask+2); *(dst+3) += *(additive_mask+3);} } // namespace anonymous //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp Softmax forward //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void softmax_warp_forward(input_t *dst, const output_t *src, int batch_size, int stride, int element_count) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; src += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; dst += first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { copy_vector(&elements_input[i][it], src + i * element_count + it * WARP_SIZE); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using softmax_forward_func = void(*)(input_t *dst, const output_t *src, int batch_size, int stride, int element_count); template bool warp_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &softmax_warp_forward; break; case 1: // 2 kernel = &softmax_warp_forward; break; case 2: // 4 kernel = &softmax_warp_forward; break; case 3: // 8 kernel = &softmax_warp_forward; break; case 4: // 16 kernel = &softmax_warp_forward; break; case 5: // 32 kernel = &softmax_warp_forward; break; case 6: // 64 kernel = &softmax_warp_forward; break; case 7: // 128 kernel = &softmax_warp_forward; break; case 8: // 256 kernel = &softmax_warp_forward; break; case 9: // 512 kernel = &softmax_warp_forward; break; case 10: // 1024 kernel = &softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_softmax(output_t *dst, const input_t *src, int softmax_elements, int softmax_elements_stride, int batch_count) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template __global__ void additive_masked_softmax_dropout_warp_forward_vec4(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p) { assert(ELEMENTS_PER_LDG_STG==4); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; int tid = blockIdx.x * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; acc_t pinv = acc_t(1)/p; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; //vectorize if element_count is multiple of 4, else don't vectorize input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; dropout_mask += thread_offset; // load data from global memory for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const half* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); //(__half)-std::numeric_limits::infinity() } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } auto seeds = at::cuda::philox::unpack(philox_args); Philox ph(std::get<0>(seeds), tid, std::get<1>(seeds)); uint8_t rands[WARP_BATCH][WARP_ITERATIONS]; float4 rand_num; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it+=ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { rand_num = uniform4(ph()); rands[i][it] = (rand_num.x <= p) > 0.5; rands[i][it+1] = (rand_num.y <= p) > 0.5; rands[i][it+2] = (rand_num.z <= p) > 0.5; rands[i][it+3] = (rand_num.w <= p) > 0.5; copy_vector(dropout_mask + i * element_count + it * WARP_SIZE, &rands[i][it]); } } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { output_t out[ELEMENTS_PER_LDG_STG]; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = rands[i][it+element] * (pinv * (elements[i][it + element] / sum[i])); } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } template __global__ void additive_masked_softmax_dropout_warp_forward(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; int tid = blockIdx.x * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; acc_t pinv = acc_t(1)/p; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; //vectorize if element_count is multiple of 4, else don't vectorize input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; int thread_offset = first_batch * stride + local_idx; src += thread_offset; dst += thread_offset; dropout_mask += thread_offset; // load data from global memory for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + local_idx; const half* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += 1) { int element_index = local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < 1;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } curandStatePhilox4_32_10_t state; auto seeds = at::cuda::philox::unpack(philox_args); curand_init( std::get<0>(seeds), tid, std::get<1>(seeds), &state); // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += 1) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { output_t out[1]; acc_t softmax_out[1]; uint8_t dropout_mask_temp[1]; //generate a vector of random numbers here float rand = curand_uniform(&state); float *rand_ptr = (float*)(&rand); #pragma unroll for (int element = 0;element < 1;++element) { softmax_out[element] = (elements[i][it + element] / sum[i]); rand_ptr[element] = rand_ptr[element] <= p; out[element] = rand_ptr[element] * pinv * softmax_out[element]; dropout_mask_temp[element] = rand_ptr[element] > 0.5; // just to distinguish 0.0f and 1.0f } copy_vector(dst + i * element_count + it * WARP_SIZE, out); copy_vector(dropout_mask + i * element_count + it * WARP_SIZE, dropout_mask_temp); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using additive_masked_softmax_dropout_forward_func = void(*)(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride, at::PhiloxCudaState philox_args, float p); template bool warp_additive_masked_softmax_dropout_kernel(int element_count, int log2_elements, int &warp_size, int &batches_per_warp, additive_masked_softmax_dropout_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; bool flag_vec4 = (element_count % 4 == 0); switch (log2_elements) { case 0: // 1 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 1: // 2 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 2: // 4 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 3: // 8 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 4: // 16 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 5: // 32 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 6: // 64 kernel = &additive_masked_softmax_dropout_warp_forward; break; case 7: // 128 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 8: // 256 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 9: // 512 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 10: // 1024 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; case 11: // 2048 if (flag_vec4) kernel = &additive_masked_softmax_dropout_warp_forward_vec4; else kernel = &additive_masked_softmax_dropout_warp_forward; break; default: return false; } return true; } template bool dispatch_additive_masked_softmax_dropout(output_t *dst, uint8_t *dropout_mask, const input_t *src, const input_t *pad_mask, int totalElements, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride, float p, cudaStream_t streamid)// p is the probability to keep, not drop { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 2048) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_dropout_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_dropout_kernel(softmax_elements, log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; c10::optional gen_; auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); int64_t counter_offset = (totalElements/(blocks*threads_per_block)+1); at::PhiloxCudaState rng_engine_inputs; { std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_cuda_state(counter_offset); } // compute launch size dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, dropout_mask, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride, rng_engine_inputs, p); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void additive_masked_softmax_warp_forward(input_t *dst, const output_t *src, const input_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const half* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); //apply_mask(&elements_input[i][it], // (__half)-std::numeric_limits::infinity(), // curr_mask + itr_jmp); elements_input[i][it] += *(curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using additive_masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const half *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_additive_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, additive_masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &additive_masked_softmax_warp_forward; break; case 1: // 2 kernel = &additive_masked_softmax_warp_forward; break; case 2: // 4 kernel = &additive_masked_softmax_warp_forward; break; case 3: // 8 kernel = &additive_masked_softmax_warp_forward; break; case 4: // 16 kernel = &additive_masked_softmax_warp_forward; break; case 5: // 32 kernel = &additive_masked_softmax_warp_forward; break; case 6: // 64 kernel = &additive_masked_softmax_warp_forward; break; case 7: // 128 kernel = &additive_masked_softmax_warp_forward; break; case 8: // 256 kernel = &additive_masked_softmax_warp_forward; break; case 9: // 512 kernel = &additive_masked_softmax_warp_forward; break; case 10: // 1024 kernel = &additive_masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_additive_masked_softmax(output_t *dst, const input_t *src, const input_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } template bool dispatch_additive_masked_softmax_stream(output_t *dst, const input_t *src, const input_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; additive_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_additive_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void masked_softmax_warp_forward(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_mask(&elements_input[i][it], (__half)-std::numeric_limits::infinity(), curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &masked_softmax_warp_forward; break; case 1: // 2 kernel = &masked_softmax_warp_forward; break; case 2: // 4 kernel = &masked_softmax_warp_forward; break; case 3: // 8 kernel = &masked_softmax_warp_forward; break; case 4: // 16 kernel = &masked_softmax_warp_forward; break; case 5: // 32 kernel = &masked_softmax_warp_forward; break; case 6: // 64 kernel = &masked_softmax_warp_forward; break; case 7: // 128 kernel = &masked_softmax_warp_forward; break; case 8: // 256 kernel = &masked_softmax_warp_forward; break; case 9: // 512 kernel = &masked_softmax_warp_forward; break; case 10: // 1024 kernel = &masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_masked_softmax(output_t *dst, const input_t *src, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template __global__ void time_masked_softmax_warp_forward(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int mod_seq_len) { assert(ELEMENTS_PER_LDG_STG==1); int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; src += thread_offset; dst += thread_offset; // load data from global memory input_t elements_input[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) % mod_seq_len) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { elements_input[i][it + element] = -std::numeric_limits::infinity(); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], src + itr_idx); apply_mask(&elements_input[i][it], (__half)-std::numeric_limits::infinity(), curr_mask + itr_jmp); } } } // convert input_t to acc_t acc_t elements[WARP_BATCH][WARP_ITERATIONS]; for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { //dst[i * element_count + it * WARP_SIZE] = elements[i][it] / sum[i]; output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = elements[i][it + element] / sum[i]; } copy_vector(dst + i * element_count + it * WARP_SIZE, out); } else { break; } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using time_masked_softmax_forward_func = void(*)(input_t *dst, const output_t *src, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int mod_seq_len); template bool warp_time_masked_softmax_kernel(int log2_elements, int &warp_size, int &batches_per_warp, time_masked_softmax_forward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &time_masked_softmax_warp_forward; break; case 1: // 2 kernel = &time_masked_softmax_warp_forward; break; case 2: // 4 kernel = &time_masked_softmax_warp_forward; break; case 3: // 8 kernel = &time_masked_softmax_warp_forward; break; case 4: // 16 kernel = &time_masked_softmax_warp_forward; break; case 5: // 32 kernel = &time_masked_softmax_warp_forward; break; case 6: // 64 kernel = &time_masked_softmax_warp_forward; break; case 7: // 128 kernel = &time_masked_softmax_warp_forward; break; case 8: // 256 kernel = &time_masked_softmax_warp_forward; break; case 9: // 512 kernel = &time_masked_softmax_warp_forward; break; case 10: // 1024 kernel = &time_masked_softmax_warp_forward; break; default: return false; } return true; } template bool dispatch_time_masked_softmax(output_t *dst, const input_t *src, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int mod_seq_len) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; time_masked_softmax_forward_func kernel; int warp_size, batches_per_warp; if (!warp_time_masked_softmax_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(dst, src, pad_mask, batch_count, softmax_elements_stride, softmax_elements, mod_seq_len); return true; } return false; } int log2_ceil_native(int value) { int log2_value = 0; while ((1 << log2_value) < value) ++log2_value; return log2_value; } template __device__ __forceinline__ T WARP_SHFL_XOR_NATIVE(T value, int laneMask, int width = warpSize, unsigned int mask = 0xffffffff) { #if CUDA_VERSION >= 9000 return __shfl_xor_sync(mask, value, laneMask, width); #else return __shfl_xor(value, laneMask, width); #endif } template __device__ __forceinline__ void warp_reduce_sum(acc_t* sum) { #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { acc_t b = WARP_SHFL_XOR_NATIVE(sum[i], offset, WARP_SIZE); sum[i] = sum[i] + b; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp softmax backward functions as fused variants of at::softmax_backward_data function //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //softmax backward data function is taken from native pytorch, elementwise mul is fused in the epolog, as well as masking and scaling for fusing dropout template __global__ void masked_scale_softmax_warp_backward_masked_dgrad(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int batch_size, int stride, int element_count, int heads) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = (input_t)((acc_t)mask[i*element_count+it*WARP_SIZE] * (acc_t)grad[i*element_count+it*WARP_SIZE] * (acc_t)scale )*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients int total_ind = thread_offset + i*element_count + it*WARP_SIZE; int pad_mask_ind = element_count*(total_ind/(heads * element_count * element_count)) + total_ind%element_count; uint8_t pad_mask_element = 1 - pad_mask[pad_mask_ind]; if (pad_mask_element == 0) gradInput[i*element_count+it*WARP_SIZE] = 0; else { if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } } template void dispatch_masked_scale_softmax_backward_masked_out(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, int heads) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 1: // 2 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 2: // 4 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 3: // 8 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 4: // 16 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 5: // 32 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 6: // 64 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 7: // 128 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 8: // 256 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 9: // 512 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 10: // 1024 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; default: break; } } } template void dispatch_masked_scale_softmax_backward_masked_out_stream(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, const uint8_t *pad_mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, int heads, cudaStream_t streamid) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 1: // 2 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 2: // 4 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 3: // 8 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 4: // 16 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 5: // 32 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 6: // 64 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 7: // 128 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 8: // 256 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 9: // 512 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; case 10: // 1024 masked_scale_softmax_warp_backward_masked_dgrad <<>>(grad_input, grad, output, mask, pad_mask, scale, batch_count, softmax_elements_stride, softmax_elements, heads); break; default: break; } } } template __global__ void masked_scale_softmax_warp_backward(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *mask, acc_t scale, int batch_size, int stride, int element_count) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = (input_t)((acc_t)mask[i*element_count+it*WARP_SIZE] * (acc_t)grad[i*element_count+it*WARP_SIZE] * (acc_t)scale )*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } template __global__ void masked_scale_softmax_warp_backward_recompute(output_t *gradInput, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int batch_size, int stride, int pad_batch_stride, int element_count) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; //vectorize if a row length is multiple of 4 int flag_vec4 = element_count & 3 == 0; acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; input_t elements_input[WARP_BATCH][WARP_ITERATIONS] ; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; softmax_input += thread_offset; gradInput += thread_offset; mask += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const input_t* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { //masking_value is a large negative value elements_input[i][it + element] = -10000; grad_reg[i][it+element] = acc_t(0); } if (element_index < batch_element_count) { int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; copy_vector(&elements_input[i][it], softmax_input + itr_idx); apply_additive_mask(&elements_input[i][it], curr_mask + itr_jmp); //(__half)-std::numeric_limits::infinity() uint8_t mask_temp[ELEMENTS_PER_LDG_STG]; input_t grad_temp[ELEMENTS_PER_LDG_STG]; copy_vector(&mask_temp[0], mask + itr_idx); copy_vector(&grad_temp[0], grad + itr_idx); #pragma unroll for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { grad_reg[i][it+element] = ((acc_t)mask_temp[element] * (acc_t)grad_temp[element] * (acc_t)scale ); } } } } // load data from global memory // convert input_t to acc_t // TODO : remove this, input is already acc_t type in register acc_t elements[WARP_BATCH][WARP_ITERATIONS] ; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { elements[i][it] = elements_input[i][it]; } } constexpr uint32_t FULL_MASK = 0xffffffff; // compute local max_value // take the max_value of the first element to avoid one max call acc_t max_value[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = elements[i][0]; } #pragma unroll for (int it = 1;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = (max_value[i] > elements[i][it]) ? max_value[i] : elements[i][it]; } } // reduction max_value #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { float val[WARP_BATCH]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { val[i] = __shfl_xor_sync(FULL_MASK, max_value[i], offset, WARP_SIZE); } #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { max_value[i] = max_value[i] > val[i] ? max_value[i] : val[i]; } } // compute local sum acc_t sum[WARP_BATCH] { 0.0f }; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { //elements[i][it] = expf(elements[i][it] - max_value[i]); elements[i][it] = std::exp(elements[i][it] - max_value[i]); sum[i] += elements[i][it]; } } // reduction sum #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it ++) { elements[i][it] = elements[i][it] / sum[i]; grad_reg[i][it] = grad_reg[i][it] * elements[i][it]; } } acc_t grad_sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { grad_sum[i] = grad_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { grad_sum[i] += grad_reg[i][it]; } } warp_reduce_sum(grad_sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t grad_input_reg[ELEMENTS_PER_LDG_STG]; #pragma unroll for (int element=0; element(gradInput + i * element_count + it * WARP_SIZE, grad_input_reg); } } } } template using masked_scale_softmax_warp_backward_recompute_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int batch_size, int stride, int pad_batch_stride, int element_count); template bool masked_scale_softmax_warp_backward_recompute_kernel(int element_count, int log2_elements, int &warp_size, int &batches_per_warp, masked_scale_softmax_warp_backward_recompute_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; bool flag_vec4 = (element_count % 4 == 0); switch (log2_elements) { case 0: // 1 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 1: // 2 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 2: // 4 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 3: // 8 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 4: // 16 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 5: // 32 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 6: // 64 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 7: // 128 kernel = &masked_scale_softmax_warp_backward_recompute; break; case 8: // 256 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 9: // 512 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 10: // 1024 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; case 11: // 2048 if (flag_vec4) kernel = &masked_scale_softmax_warp_backward_recompute; else kernel = &masked_scale_softmax_warp_backward_recompute; break; default: return false; } return true; } template bool dispatch_masked_scale_softmax_backward_recompute(output_t *grad_input, const input_t *grad, const input_t *softmax_input, const input_t *pad_mask, const uint8_t *mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int pad_batch_stride, int batch_count, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 2048) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_scale_softmax_warp_backward_recompute_func kernel; int warp_size, batches_per_warp; if (!masked_scale_softmax_warp_backward_recompute_kernel(softmax_elements, log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; // compute launch size dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, softmax_input, pad_mask, mask, scale, batch_count, softmax_elements_stride, pad_batch_stride, softmax_elements); return true; } return false; } template void dispatch_masked_scale_softmax_backward_stream(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *mask, acc_t scale, int softmax_elements, int softmax_elements_stride, int batch_count, cudaStream_t streamid) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 1: // 2 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 2: // 4 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 3: // 8 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 4: // 16 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 5: // 32 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 6: // 64 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 7: // 128 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 8: // 256 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 9: // 512 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; case 10: // 1024 masked_scale_softmax_warp_backward <<>>(grad_input, grad, output, mask, scale, batch_count, softmax_elements_stride, softmax_elements); break; default: break; } } } // elementwise multiplication called in at::softmax_backward_data is fused inside softmax dgrad kernel // as a result of fusion, intermediate multiplication result is stored in fp32 in registers, instead of fp16 template __global__ void softmax_warp_backward_fused_native(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count) { // WARP_SIZE and WARP_BATCH must match the return values batches_per_warp and warp_size of method warp_softmax_backward_kernel. constexpr int next_power_of_two = 1 << log2_elements; constexpr int WARP_SIZE = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; constexpr int WARP_ITERATIONS = next_power_of_two / WARP_SIZE; constexpr int WARP_BATCH = (next_power_of_two <= 128) ? 2 : 1; int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x % WARP_SIZE; // the first element to process by the current thread int thread_offset = first_batch * stride + local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // The nested loops over WARP_BATCH and then WARP_ITERATIONS can be simplified to one loop, // but I think doing so would obfuscate the logic of the algorithm, thus I chose to keep // the nested loops. // This should have no impact on performance because the loops are unrolled anyway. // load data from global memory acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS] ; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS] ; for (int i = 0; i < WARP_BATCH; ++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { grad_reg[i][it] = grad[i*element_count+it*WARP_SIZE]*output[i*element_count+it*WARP_SIZE]; output_reg[i][it] = output[i*element_count+it*WARP_SIZE]; } else { grad_reg[i][it] = acc_t(0); output_reg[i][it] = acc_t(0); } } } acc_t sum[WARP_BATCH]; #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { sum[i] = grad_reg[i][0]; //* output_reg[i][0]; #pragma unroll for (int it = 1; it < WARP_ITERATIONS; ++it) { sum[i] += grad_reg[i][it];// * output_reg[i][it]; } } warp_reduce_sum(sum); // store result #pragma unroll for (int i = 0; i < WARP_BATCH; ++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0; it < WARP_ITERATIONS; ++it) { int element_index = local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients if (is_log_softmax) { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - std::exp(output_reg[i][it]) * sum[i]); } else { gradInput[i*element_count+it*WARP_SIZE] = (grad_reg[i][it] - output_reg[i][it] * sum[i]); } } } } } template void dispatch_softmax_backward_fused_native(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count) { TORCH_INTERNAL_ASSERT( softmax_elements >= 0 && softmax_elements <= 1024 ); if (softmax_elements == 0) { return; } else { int log2_elements = log2_ceil_native(softmax_elements); const int next_power_of_two = 1 << log2_elements; // This value must match the WARP_SIZE constexpr value computed inside softmax_warp_backward. int warp_size = (next_power_of_two < C10_WARP_SIZE) ? next_power_of_two : C10_WARP_SIZE; // This value must match the WARP_BATCH constexpr value computed inside softmax_warp_backward. int batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; int warps_per_block = (threads_per_block / warp_size); int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // Launch code would be more elegant if C++ supported FOR CONSTEXPR switch (log2_elements) { case 0: // 1 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 1: // 2 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 2: // 4 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 3: // 8 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 4: // 16 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 5: // 32 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 6: // 64 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 7: // 128 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 8: // 256 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 9: // 512 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; case 10: // 1024 softmax_warp_backward_fused_native <<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); break; default: break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Warp softmax backward //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template __global__ void softmax_warp_backward(__half *gradInput, const __half *grad, const __half *output, int batch_size, int stride, int element_count) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // load data from global memory input_t grad_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; input_t output_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { copy_vector(&grad_reg_input[i][it], grad + i * element_count + it * WARP_SIZE); copy_vector(&output_reg_input[i][it], output + i * element_count + it * WARP_SIZE); } } } // convert half to floating point acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS]; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { grad_reg[i][it] = grad_reg_input[i][it]; output_reg[i][it] = output_reg_input[i][it]; } } // compute thread local sum acc_t sum[WARP_BATCH] = {0}; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { sum[i] += grad_reg[i][it] * output_reg[i][it]; } } // reduction sum constexpr uint32_t FULL_MASK = 0xffffffff; #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = (output_reg[i][it+element] * (grad_reg[i][it+element] - sum[i])); } // store them in global memory copy_vector(gradInput + i * element_count + it * WARP_SIZE, out); } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using softmax_backward_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *output, int batch_size, int stride, int element_count); template bool warp_softmax_backward_kernel(int log2_elements, int &warp_size, int &batches_per_warp, softmax_backward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &softmax_warp_backward; break; case 1: // 2 kernel = &softmax_warp_backward; break; case 2: // 4 kernel = &softmax_warp_backward; break; case 3: // 8 kernel = &softmax_warp_backward; break; case 4: // 16 kernel = &softmax_warp_backward; break; case 5: // 32 kernel = &softmax_warp_backward; break; case 6: // 64 kernel = &softmax_warp_backward; break; case 7: // 128 kernel = &softmax_warp_backward; break; case 8: // 256 kernel = &softmax_warp_backward; break; case 9: // 512 kernel = &softmax_warp_backward; break; case 10: // 1024 kernel = &softmax_warp_backward; break; default: return false; } return true; } template bool dispatch_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template bool dispatch_softmax_backward_stream(output_t *grad_input, const input_t *grad, const input_t *output, int softmax_elements, int softmax_elements_stride, int batch_count, cudaStream_t streamid) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, batch_count, softmax_elements_stride, softmax_elements); return true; } return false; } template __global__ void masked_softmax_warp_backward(__half *gradInput, const __half *grad, const __half *output, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride) { int first_batch = (blockDim.y * blockIdx.x + threadIdx.y) * WARP_BATCH; // batch_size might not be a multiple of WARP_BATCH. Check how // many batches have to computed within this WARP. int local_batches = batch_size - first_batch; if (local_batches > WARP_BATCH) local_batches = WARP_BATCH; // there might be multiple batches per warp. compute the index within the batch int local_idx = threadIdx.x; // the first element to process by the current thread int thread_offset = first_batch * stride + ELEMENTS_PER_LDG_STG * local_idx; grad += thread_offset; output += thread_offset; gradInput += thread_offset; // load data from global memory input_t grad_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; input_t output_reg_input[WARP_BATCH][WARP_ITERATIONS] = {0.0f}; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { int batch_element_count = (i >= local_batches) ? 0 : element_count; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < batch_element_count) { copy_vector(&grad_reg_input[i][it], grad + i * element_count + it * WARP_SIZE); copy_vector(&output_reg_input[i][it], output + i * element_count + it * WARP_SIZE); } } } // convert half to floating point acc_t grad_reg[WARP_BATCH][WARP_ITERATIONS]; acc_t output_reg[WARP_BATCH][WARP_ITERATIONS]; #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { for (int it = 0;it < WARP_ITERATIONS;++it) { grad_reg[i][it] = grad_reg_input[i][it]; output_reg[i][it] = output_reg_input[i][it]; } } // compute thread local sum acc_t sum[WARP_BATCH] = {0}; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;++it) { for (int i = 0;i < WARP_BATCH;++i) { sum[i] += grad_reg[i][it] * output_reg[i][it]; } } // reduction sum constexpr uint32_t FULL_MASK = 0xffffffff; #pragma unroll for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) { #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { sum[i] += __shfl_xor_sync(FULL_MASK, sum[i], offset, WARP_SIZE); } } // store result #pragma unroll for (int i = 0;i < WARP_BATCH;++i) { if (i >= local_batches) break; int pad_thread_offset = ( (first_batch + i) / pad_batch_stride) * stride + ELEMENTS_PER_LDG_STG * local_idx; const uint8_t* curr_mask = pad_mask + pad_thread_offset; #pragma unroll for (int it = 0;it < WARP_ITERATIONS;it += ELEMENTS_PER_LDG_STG) { int element_index = ELEMENTS_PER_LDG_STG * local_idx + it * WARP_SIZE; if (element_index < element_count) { // compute gradients output_t out[ELEMENTS_PER_LDG_STG]; for (int element = 0;element < ELEMENTS_PER_LDG_STG;++element) { out[element] = (output_reg[i][it+element] * (grad_reg[i][it+element] - sum[i])); } // store them in global memory int itr_jmp = it * WARP_SIZE; int itr_idx = i * element_count + itr_jmp; // It is kind of unfortunate this has to be here to zero something out that is close to // zero in the first place apply_mask(&out[0], 0.0, curr_mask + itr_jmp); copy_vector(gradInput + itr_idx, out); } } } } // WARP_BATCH number of batches. // WARP_ITERATOINS The number of iterations required for one warp to iterate over all data. // WARP_SIZE number of elements working on a single batch, has to be a power of two. // ELEMENTS_PER_LDG_STG has to be 1. template using masked_softmax_backward_func = void(*)(output_t *gradInput, const input_t *grad, const input_t *output, const uint8_t *pad_mask, int batch_size, int stride, int element_count, int pad_batch_stride); template bool warp_masked_softmax_backward_kernel(int log2_elements, int &warp_size, int &batches_per_warp, masked_softmax_backward_func &kernel) { // determine size of a warp const int next_power_of_two = 1 << log2_elements; warp_size = (next_power_of_two < 32) ? next_power_of_two : 32; // determine how many batches a warp should process. batches_per_warp = (next_power_of_two <= 128) ? 2 : 1; switch (log2_elements) { case 0: // 1 kernel = &masked_softmax_warp_backward; break; case 1: // 2 kernel = &masked_softmax_warp_backward; break; case 2: // 4 kernel = &masked_softmax_warp_backward; break; case 3: // 8 kernel = &masked_softmax_warp_backward; break; case 4: // 16 kernel = &masked_softmax_warp_backward; break; case 5: // 32 kernel = &masked_softmax_warp_backward; break; case 6: // 64 kernel = &masked_softmax_warp_backward; break; case 7: // 128 kernel = &masked_softmax_warp_backward; break; case 8: // 256 kernel = &masked_softmax_warp_backward; break; case 9: // 512 kernel = &masked_softmax_warp_backward; break; case 10: // 1024 kernel = &masked_softmax_warp_backward; break; default: return false; } return true; } template bool dispatch_masked_softmax_backward(output_t *grad_input, const input_t *grad, const input_t *output, const uint8_t *pad_mask, int softmax_elements, int softmax_elements_stride, int batch_count, int pad_batch_stride) { if (softmax_elements == 0) { return true; } else if (softmax_elements <= 1024) { // compute function index. there's a function for each power of two size up to 1024. int log2_elements = 0; while ((1 << log2_elements) < softmax_elements) ++log2_elements; masked_softmax_backward_func kernel; int warp_size, batches_per_warp; if (!warp_masked_softmax_backward_kernel(log2_elements, warp_size, batches_per_warp, kernel)) { return false; } // use 128 threads per block to maximimize gpu utilization constexpr int threads_per_block = 128; // compute warps per block. int warps_per_block = (threads_per_block / warp_size); // compute launch size int batches_per_block = warps_per_block * batches_per_warp; int blocks = (batch_count + batches_per_block - 1) / batches_per_block; dim3 threads(warp_size, warps_per_block, 1); // launch kernel<<>>(grad_input, grad, output, pad_mask, batch_count, softmax_elements_stride, softmax_elements, pad_batch_stride); return true; } return false; } ================================================ FILE: KoSimCSE/apex/contrib/csrc/multihead_attn/strided_batched_gemm.h ================================================ #include #include //#include #include #include #include #include #include #include "THC/THC.h" #include #include "cutlass/cutlass.h" #include "cutlass/gemm/gemm.h" #include "cutlass/gemm/wmma_gemm_traits.h" // symbol to be automatically resolved by PyTorch libs extern THCState *state; cublasOperation_t convertTransToCublasOperation(char trans) { if (trans == 't') return CUBLAS_OP_T; else if (trans == 'n') return CUBLAS_OP_N; else if (trans == 'c') return CUBLAS_OP_C; else { THError("trans must be one of: t, n, c"); return CUBLAS_OP_T; } } void CublasStridedBatchedGemm(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount, cublasGemmAlgo_t algo=CUBLAS_GEMM_DEFAULT_TENSOR_OP) { cublasOperation_t opa = convertTransToCublasOperation(transa); cublasOperation_t opb = convertTransToCublasOperation(transb); cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle(); cudaStream_t stream = at::cuda::getCurrentCUDAStream().stream(); cublasSetStream(handle, stream); float fAlpha = alpha; float fBeta = beta; //THCublasCheck(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH)); THCublasCheck(cublasGemmStridedBatchedEx(handle, opa, opb, (int)m, (int)n, (int)k, (void*)&fAlpha, a, CUDA_R_16F, (int)lda, strideA, b, CUDA_R_16F, (int)ldb, strideB, (void*)&fBeta, c, CUDA_R_16F, (int)ldc, strideC, (int)batchCount, CUDA_R_32F, algo)); //THCublasCheck(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH)); } template void CutlassGemm_FP32Accum(cudaStream_t stream, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { //printf("CUTLASS-> %c%c M: %ld N: %ld K: %ld %d%d%d LDA: %ld LDB: %ld LDC: %ld strideA: %ld strideB: %ld strideC: %ld Alpha: %f Beta: %f\n", ((int)A_LAYOUT == 0 ? 'T' : 'N'), ((int)B_LAYOUT ==0 ? 'T' : 'N'), m, n, k, SRC_A,SRC_B,DST_C, lda, ldb, ldc, strideA, strideB, strideC, alpha, beta); typedef cutlass::gemm::WmmaGemmTraits< A_LAYOUT, B_LAYOUT, cutlass::Shape<32, 16, 16>, half, half, half, cutlass::gemm::LinearScaling, float, typename cutlass::gemm::WmmaGemmAccumulatorsPerWarp >::Shape, typename cutlass::Shape<16, 16, 16>, SRC_A, //kScalarsPerLdgA_ SRC_B, //kScalarsPerLdgB_ SRC_A, //KScalarsPerLdsA_ SRC_B, //KScalarsPerLdsB_ DST_C, //kScalarsPerLdgCAndStgD_ DST_C/2, //kScalarsPerStsD_ DST_C/2 //kScalarsPerLdsD_ > WmmaGemmTraits; typedef cutlass::gemm::Gemm Gemm; typename Gemm::Params params; int result = params.initialize( m, // M dimension for each batch n, // N dimension for each batch k, // K dimension for each batch alpha, // scalar alpha a, lda, strideA, // distance in memory between the first element of neighboring batch b, ldb, strideB, // distance in memory between the first element of neighboring batch beta, // scalar beta c, // source matrix C ldc, strideC, // distance in memory between the first element of neighboring batch c, // destination matrix C (may be different memory than source C matrix) ldc, strideC, // distance in memory between the first element of neighboring batch batchCount ); AT_ASSERTM(result == 0, "Failed to initialize CUTLASS Gemm::Params object."); // batchCount in cutlass batched GEMM kernels maps to gridDim.z, which is limited to 16 bits. // To implement batched GEMM with larger batch size, we fragment it into // smaller batched GEMMs of gridDim.z <= 64k long batchesLeft = batchCount; long iterBatchCount = std::min(batchesLeft, static_cast((1 << 16) - 1)); do { //printf("CUTLASS-> %c%c M: %ld N: %ld K: %ld %d%d%d LDA: %ld LDB: %ld LDC: %ld strideA: %ld strideB: %ld strideC: %ld Alpha: %f Beta: %f TotalBatches: %ld iterBatchCount %ld\n", ((int)A_LAYOUT == 0 ? 'T' : 'N'), ((int)B_LAYOUT ==0 ? 'T' : 'N'), m, n, k, SRC_A,SRC_B,DST_C, lda, ldb, ldc, strideA, strideB, strideC, alpha, beta, batchesLeft, iterBatchCount); int result = params.initialize( m, // M dimension for each batch n, // N dimension for each batch k, // K dimension for each batch alpha, // scalar alpha a, lda, strideA, // distance in memory between the first element of neighboring batch b, ldb, strideB, // distance in memory between the first element of neighboring batch beta, // scalar beta c, // source matrix C ldc, strideC, // distance in memory between the first element of neighboring batch c, // destination matrix C (may be different memory than source C matrix) ldc, strideC, // distance in memory between the first element of neighboring batch iterBatchCount ); AT_ASSERTM(result == 0, "Failed to initialize CUTLASS Gemm::Params object."); // Launch the CUTLASS GEMM kernel. THCudaCheck(Gemm::launch(params, stream)); // Update batched GEMM params based on completed work batchesLeft = batchesLeft - iterBatchCount; a += iterBatchCount * strideA; b += iterBatchCount * strideB; c += iterBatchCount * strideC;; iterBatchCount = std::min(batchesLeft, static_cast((1 << 16) - 1)); } while(batchesLeft > 0); } void gemm_switch_fp32accum(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { auto stream = c10::cuda::getCurrentCUDAStream(); //printf("GEMM -> %c%c M: %i N: %i K: %i Alpha: %f Beta: %f\n", (transa == 't' ? 'T' : 'N'), (transb =='t' ? 'T' : 'N'), m, n, k, alpha, beta); if ( (transa == 't') && (transb == 'n') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else if ( (transa == 'n') && (transb == 'n') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else if ( (transa == 'n') && (transb == 't') ) { if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } /*if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x7)) { int m_rem = m % 64; int n_rem = n % 64; if ( (m_rem > 48) && ( m <= 192) && (n_rem > 48) && (n <= 192 ) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else if ( (m_rem > 32) && ( m > 192) && (n_rem > 32) && (n > 192) ) { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount, CUBLAS_GEMM_ALGO0_TENSOR_OP); } else { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } }*/ else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x7) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x3) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x7) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x3) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x7)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x3)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else if (!(lda & 0x1) && !(ldb & 0x1) && !(ldc & 0x1)) { CutlassGemm_FP32Accum(stream, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } else { CublasStridedBatchedGemm(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } } else { AT_ASSERTM(false, "TransA and TransB are invalid"); } } void adjustLdLevel3(char transa, char transb, int64_t m, int64_t n, int64_t k, int64_t *lda, int64_t *ldb, int64_t *ldc) { int transa_ = ((transa == 't') || (transa == 'T')); int transb_ = ((transb == 't') || (transb == 'T')); // Note: leading dimensions generally are checked that they are > 0 and at least as big the result // requires (even if the value won't be used). if(n <= 1) *ldc = std::max(m, 1); if(transa_) { if(m <= 1) *lda = std::max(k, 1); } else { if(k <= 1) *lda = std::max(m, 1); } if(transb_) { if(k <= 1) *ldb = std::max(n, 1); } else { if(n <= 1) *ldb = std::max(k, 1); } } void HgemmStridedBatched(THCState *state, char transa, char transb, long m, long n, long k, float alpha, const half *a, long lda, long strideA, const half *b, long ldb, long strideB, float beta, half *c, long ldc, long strideC, long batchCount) { if( (m >= INT_MAX) || (n >= INT_MAX) || (k >= INT_MAX) || (lda >= INT_MAX) || (ldb >= INT_MAX) || (ldc >= INT_MAX) || (batchCount >= INT_MAX) ) { THError("Cublas_SgemmStridedBatched only supports m, n, k, lda, ldb, ldc, batchCount" "with the bound [val] <= %d", INT_MAX); } adjustLdLevel3(transa, transb, m, n, k, &lda, &ldb, &ldc); //gemm_switch(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); gemm_switch_fp32accum(state, transa, transb, m, n, k, alpha, a, lda, strideA, b, ldb, strideB, beta, c, ldc, strideC, batchCount); } /****** at::Tensor strided_batched_gemm_cuda( float beta, at::Tensor in_result, float alpha, at::Tensor batch1, at::Tensor batch2) { bool transpose_result; char transpose_batch1, transpose_batch2; int64_t lda, ldb, ldc; at::Tensor result, input1, input2; if (in_result.stride(1) == 1) { transpose_result = false; result = in_result; ldc = result.stride(2); } else if (in_result.stride(2) == 1) { transpose_result = true; at::Tensor swap = batch2; batch2 = batch1; batch1 = swap; result = in_result; ldc = result.stride(1); } else { AT_ASSERTM(false, "result should be contiguous"); } if (batch1.stride(transpose_result ? 2 : 1) == 1 && batch1.stride(transpose_result ? 1 : 2) != 0) { transpose_batch1 = 'n'; input1 = batch1; lda = input1.stride(transpose_result ? 1 : 2); } else if (batch1.stride(transpose_result ? 1 : 2) == 1 && batch1.stride(transpose_result ? 2 : 1) != 0) { transpose_batch1 = 't'; input1 = batch1; lda = input1.stride(transpose_result ? 2 : 1); } else { AT_ASSERTM(false, "input1 should be contiguous"); } if (batch2.stride(transpose_result ? 2 : 1) == 1 && batch2.stride(transpose_result ? 1 : 2) != 0) { transpose_batch2 = 'n'; input2 = batch2; ldb = input2.stride(transpose_result ? 1 : 2); } else if (batch2.stride(transpose_result ? 1 : 2) == 1 && batch2.stride(transpose_result ? 2 : 1) != 0) { transpose_batch2 = 't'; input2 = batch2; ldb = input2.stride(transpose_result ? 2 : 1); } else { AT_ASSERTM(false, "input2 should be contiguous"); } int64_t num_batches = result.size(0); HgemmStridedBatched( state, transpose_batch1, transpose_batch2, result.size(transpose_result ? 2 : 1), result.size(transpose_result ? 1 : 2), input1.size(transpose_result ? 1 : 2), alpha, static_cast(input1.data_ptr()), lda, input1.stride(0), static_cast(input2.data_ptr()), ldb, input2.stride(0), beta, static_cast(result.data_ptr()), ldc, result.stride(0), num_batches); return in_result; } ***/ ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/fused_adam_cuda.cpp ================================================ #include // CUDA forward declaration void fused_strided_check_finite(at::Tensor & overflow_flag, at::Tensor & p_copy, int stride, int clear_overflow_first); void fused_adam_cuda(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_reversible_adam_cuda(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_maybe_adam_undo_cuda(at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void fused_adam_cuda_mt(int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay); void maybe_cast_cuda(at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out); void maybe_cast_cuda_mt(int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists); #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) // C++ interface void strided_check_finite( at::Tensor& overflow_flag, at::Tensor& p_copy, int stride, int clear_overflow_first ) { CHECK_INPUT(p_copy); fused_strided_check_finite(overflow_flag, p_copy, stride, clear_overflow_first); } void adam(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); if (p_copy.numel() > 0) CHECK_INPUT(p_copy); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); AT_ASSERTM(p_copy.numel() == num_elem || p_copy.numel() == 0, "number of elements in p_copy and p tensors should be equal, or p_copy should be empty"); fused_adam_cuda(p, p_copy, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void reversible_adam(at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); if (p_copy.numel() > 0) CHECK_INPUT(p_copy); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); AT_ASSERTM(p_copy.numel() == num_elem || p_copy.numel() == 0, "number of elements in p_copy and p tensors should be equal, or p_copy should be empty"); fused_reversible_adam_cuda(p, p_copy, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void maybe_adam_undo(at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { CHECK_INPUT(p); CHECK_INPUT(m); CHECK_INPUT(v); CHECK_INPUT(g); int64_t num_elem = p.numel(); AT_ASSERTM(m.numel() == num_elem, "number of elements in m and p tensors should be equal"); AT_ASSERTM(v.numel() == num_elem, "number of elements in v and p tensors should be equal"); AT_ASSERTM(g.numel() == num_elem, "number of elements in g and p tensors should be equal"); fused_maybe_adam_undo_cuda(overflow_flag, p, m, v, g, lr, beta1, beta2, eps, grad_scale, step, mode, bias_correction, decay); } void maybe_cast(at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out) { CHECK_INPUT(p_in); CHECK_INPUT(p_out); int64_t num_elem = p_in.numel(); AT_ASSERTM(p_out.numel() == num_elem, "number of elements in p_in and p_out should be equal"); maybe_cast_cuda(overflow_flag, p_in, p_out); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("strided_check_finite", &strided_check_finite, "Strided finite check."); m.def("adam", &adam, "Adam optimized CUDA implementation."); m.def("reversible_adam", &reversible_adam, "Reversible Adam optimized CUDA implementation."); m.def("adam_mt", &fused_adam_cuda_mt, "Multi tensor Adam optimized CUDA implementation."); m.def("maybe_adam_undo", &maybe_adam_undo, "Undo function for Adam optimized CUDA implementation."); m.def("maybe_cast", &maybe_cast, "Unpack byte tensor containing e5m2 floats."); m.def("maybe_cast_mt", &maybe_cast_cuda_mt, "Unpack byte tensor containing e5m2 floats."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/fused_adam_cuda_kernel.cu ================================================ #include "ATen/ATen.h" #include "ATen/cuda/CUDAContext.h" #include "ATen/cuda/detail/IndexUtils.cuh" #include #include #include #include #include "ATen/TensorUtils.h" // #include "ATen/Type.h" #include "ATen/AccumulateType.h" #include #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } #include "type_shim.h" typedef enum{ ADAM_MODE_0 =0, // eps under square root ADAM_MODE_1 =1 // eps outside square root } adamMode_t; template __global__ void adam_cuda_kernel( T* __restrict__ p, GRAD_T* __restrict__ p_copy, // For mixed precision training, pass NULL if not needed T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; for (int j = i; j < tsize; j+=totThreads) { T scaled_grad = g[j]/grad_scale; m[j] = b1*m[j] + (1-b1)*scaled_grad; v[j] = b2*v[j] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(v[j] + eps); else // Mode 1 denom = sqrtf(v[j]) + eps; float update = (m[j]/denom) + (decay*p[j]); p[j] = p[j] - (step_size*update); if (p_copy != NULL) p_copy[j] = (GRAD_T) p[j]; } } template struct AdamFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata& tl, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, adamMode_t mode, const float decay) { int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; T* p = (T *)tl.addresses[0][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T *)tl.addresses[1][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T *)tl.addresses[2][tensor_loc]; v += chunk_idx*chunk_size; GRAD_T* g = (GRAD_T *)tl.addresses[3][tensor_loc]; g += chunk_idx*chunk_size; GRAD_T* p_copy = NULL; if (DEPTH == 5) { p_copy = (GRAD_T *)tl.addresses[4][tensor_loc]; p_copy += chunk_idx*chunk_size; } n -= chunk_idx*chunk_size; T incoming_p[ILP]; T incoming_m[ILP]; T incoming_v[ILP]; T incoming_g[ILP]; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(m) && is_aligned(v) && is_aligned(g) && is_aligned(p_copy)) { for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load GRAD_T tmp_g[ILP]; load_store(incoming_p, p, 0, i_start); load_store(incoming_m, m, 0, i_start); load_store(incoming_v, v, 0, i_start); load_store(tmp_g, g, 0, i_start); #pragma unroll for(int ii = 0; ii < ILP; ii++) { incoming_g[ii] = static_cast(tmp_g[ii]); T scaled_grad = incoming_g[ii]/grad_scale; incoming_m[ii] = b1*incoming_m[ii] + (1-b1)*scaled_grad; incoming_v[ii] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(incoming_v[ii] + eps); else // Mode 1 denom = sqrtf(incoming_v[ii]) + eps; float update = (incoming_m[ii]/denom) + (decay*incoming_p[ii]); incoming_p[ii] = incoming_p[ii] - (step_size*update); if (DEPTH == 5) tmp_g[ii] = static_cast(incoming_p[ii]); } load_store(p, incoming_p, i_start, 0); load_store(m, incoming_m, i_start, 0); load_store(v, incoming_v, i_start, 0); if (DEPTH == 5) load_store(p_copy, tmp_g, i_start, 0); } } else { for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { incoming_p[ii] = 0; incoming_m[ii] = 0; incoming_v[ii] = 0; incoming_g[ii] = 0; int i = i_start + threadIdx.x + ii*blockDim.x; if (i < n && i < chunk_size) { incoming_p[ii] = p[i]; incoming_m[ii] = m[i]; incoming_v[ii] = v[i]; incoming_g[ii] = static_cast(g[i]); } } // note for clarification to future michael: // From a pure memory dependency perspective, there's likely no point unrolling // the write loop, since writes just fire off once their LDGs arrive. // Put another way, the STGs are dependent on the LDGs, but not on each other. // There is still compute ILP benefit from unrolling the loop though. #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = i_start + threadIdx.x + ii*blockDim.x; if(j < n && j < chunk_size) { T scaled_grad = incoming_g[ii]/grad_scale; m[j] = b1*incoming_m[ii] + (1-b1)*scaled_grad; v[j] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(v[j] + eps); else // Mode 1 denom = sqrtf(v[j]) + eps; float update = (m[j]/denom) + (decay*incoming_p[ii]); p[j] = incoming_p[ii] - (step_size*update); if (DEPTH == 5) p_copy[j] = (GRAD_T) p[j]; } } } } } }; void fused_adam_cuda( at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { // using namespace at; //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.numel() ? p_copy.DATA_PTR() : NULL, m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", adam_cuda_kernel<<>>( p.DATA_PTR(), NULL, //don't output p_copy for fp32, it's wasted write m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } void fused_adam_cuda_mt( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, // p, m, v, g, p_copy float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 4 || tl_sz == 5, "expected tensor lists of size 4 or 5"); if (tensor_lists[3][0].scalar_type() == at::ScalarType::Half) { //alher values should be fp32 for half gradients AT_ASSERTM(tensor_lists[0][0].scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dich is done on the gradient type if (tl_sz == 5) { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", using accscalar_t = at::acc_type; multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<5, accscalar_t, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } else { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", using accscalar_t = at::acc_type; multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<4, accscalar_t, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } } else { if (tl_sz == 5) { DISPATCH_DOUBLE_AND_FLOAT(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<5, scalar_t_0, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } else { DISPATCH_DOUBLE_AND_FLOAT(tensor_lists[3][0].scalar_type(), 0, "adam_cuda_mt_kernel", multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, AdamFunctor<4, scalar_t_0, scalar_t_0>(), beta1, beta2, eps, grad_scale, step_size, (adamMode_t) mode, decay); ); } } THCudaCheck(cudaGetLastError()); } template __device__ void convert(const FROM_T vi, TO_T& vo) { vo = static_cast(vi); } template <> __device__ void convert(const float vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = vi; s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, float& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = static_cast(t.as_half); } template <> __device__ void convert(const at::Half vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = static_cast(vi); s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, at::Half& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = t.as_half; } template __global__ void strided_check_finite_cuda_kernel( volatile int* noop_gmem, GRAD_T* __restrict__ p_copy, const size_t tsize, int stride, int clear_overflow_first) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock) * stride; const int totThreads = gridDim.x*gridDim.y*threadsPerBlock*stride; if (clear_overflow_first) { if (i == 0) { *noop_gmem = 0; } __syncthreads(); } for (int j = i; j < tsize; j+=totThreads) { GRAD_T pi = p_copy[j]; if (!isfinite(pi)) { *noop_gmem = 1; } } } template <> __global__ void strided_check_finite_cuda_kernel( volatile int* noop_gmem, uint8_t* __restrict__ p_copy, const size_t tsize, int stride, int clear_overflow_first) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock) * stride; const int totThreads = gridDim.x*gridDim.y*threadsPerBlock*stride; if (clear_overflow_first) { if (i == 0) { *noop_gmem = 0; } __syncthreads(); } for (int j = i; j < tsize; j+=totThreads) { at::Half pi; convert(p_copy[j], pi); if (!isfinite(pi)) { *noop_gmem = 1; } } } template __global__ void maybe_cast_kernel( volatile int* overflow_flag, const FROM_T* p_in, TO_T* p_out, const size_t tsize) { if (overflow_flag && *overflow_flag != 0) return; //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; FROM_T pi[ILP]; TO_T po[ILP]; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { pi[ii] = 0; int j = j_start + i + totThreads*ii; if (j < tsize) { pi[ii] = p_in[j]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { convert(pi[ii], po[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i + totThreads*ii; if (j < tsize) { p_out[j] = po[ii]; } } } } template __global__ void reversible_adam_cuda_kernel( T* __restrict__ p, REDU_T* __restrict__ p_copy, // For mixed precision training, pass NULL if not needed T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; T mi[ILP]; T vi[ILP]; T pi[ILP]; T gi[ILP]; bool overflow = false; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { mi[ii] = T(0); vi[ii] = T(0); pi[ii] = T(0); gi[ii] = GRAD_T(0); int j = j_start + i + totThreads*ii; if (j < tsize) { pi[ii] = p[j]; mi[ii] = m[j]; vi[ii] = v[j]; gi[ii] = static_cast(g[j]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { T scaled_grad = gi[ii]/grad_scale; if (isfinite(scaled_grad)) { mi[ii] = b1*mi[ii] + (1-b1)*scaled_grad; vi[ii] = b2*vi[ii] + (1-b2)*scaled_grad*scaled_grad; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(vi[ii] + eps); else // Mode 1 denom = sqrtf(vi[ii]) + eps; float update = (mi[ii]/denom) + (decay*pi[ii]); pi[ii] = pi[ii] - (step_size*update); } else { overflow = true; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i + totThreads*ii; if (j < tsize) { m[j] = mi[ii]; v[j] = vi[ii]; p[j] = pi[ii]; if (p_copy != NULL) { convert(pi[ii], p_copy[j]); } } } } if (p_copy != NULL) { __syncthreads(); if (overflow) { convert(float(INFINITY), p_copy[0]); } } } template __global__ void maybe_adam_undo_cuda_kernel( volatile int* overflow_flag, T* __restrict__ p, T* __restrict__ m, T* __restrict__ v, const GRAD_T * __restrict__ g, const float b1, const float b2, const float eps, const float grad_scale, const float step_size, const size_t tsize, adamMode_t mode, const float decay) { // NB! Skip undo kernel when overflow flag is NOT set if (overflow_flag && *overflow_flag == 0) return; //Assuming 2D grids and 2D blocks const int blockId = gridDim.x * blockIdx.y + blockIdx.x; const int threadsPerBlock = blockDim.x * blockDim.y; const int threadIdInBlock = threadIdx.y * blockDim.x + threadIdx.x; const int i = (blockId * threadsPerBlock + threadIdInBlock); const int totThreads = gridDim.x*gridDim.y*threadsPerBlock; T mi[ILP]; T vi[ILP]; T pi[ILP]; T gi[ILP]; for(int j_start = 0; j_start < tsize; j_start+=totThreads*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { mi[ii] = T(0); vi[ii] = T(0); pi[ii] = T(0); gi[ii] = GRAD_T(0); int j = j_start + i*ILP; if (j < tsize) { pi[ii] = p[j]; mi[ii] = m[j]; vi[ii] = v[j]; gi[ii] = static_cast(g[j]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { T scaled_grad = gi[ii]/grad_scale; if (isfinite(scaled_grad)) { float denom; if (mode == ADAM_MODE_0) denom = sqrtf(vi[ii] + eps); else // Mode 1 denom = sqrtf(vi[ii]) + eps; pi[ii] = (pi[ii] + step_size*(mi[ii]/denom)) / (1.0f - step_size*decay); mi[ii] = (mi[ii] - (1-b1)*scaled_grad) / b1; vi[ii] = (vi[ii] - (1-b2)*scaled_grad*scaled_grad) / b2; // Make sure round off errors don't create (small) negative value. // This can happen if we have to revert the very first step. vi[ii] = vi[ii] >= 0.0f ? vi[ii] : 0.0f; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + i*ILP; if (j < tsize) { m[j] = mi[ii]; v[j] = vi[ii]; p[j] = pi[ii]; } } } } template struct MaybeCastFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* overflow_flag, TensorListMetadata& tl) { if (overflow_flag && *overflow_flag != 0) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; FROM_T* p_in = (FROM_T *)tl.addresses[0][tensor_loc]; p_in += chunk_idx*chunk_size; TO_T* p_out = (TO_T *)tl.addresses[1][tensor_loc]; p_out += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; int dim = chunk_size < n ? chunk_size : n; FROM_T pi[ILP]; TO_T po[ILP]; for(int j_start = 0; j_start < dim; j_start+=blockDim.x*ILP) { #pragma unroll for(int ii = 0; ii < ILP; ii++) { pi[ii] = FROM_T(0); int j = j_start + threadIdx.x + ii*blockDim.x; if (j < dim) { pi[ii] = p_in[j]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { convert(pi[ii], po[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int j = j_start + threadIdx.x + ii*blockDim.x; if (j < dim) { p_out[j] = po[ii]; } } } } }; void fused_strided_check_finite( at::Tensor & overflow_flag, at::Tensor & p_copy, int stride, int clear_overflow_first) { //Get tensor size int tsize = p_copy.numel(); int niter = (tsize + stride - 1) / stride; //Determine #threads and #blocks const int threadsPerBlock = 512; //In order to avoid race condition, blocks must be 1 when clear_overflow_first flag is set. const dim3 blocks(clear_overflow_first ? 1 : (niter+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p_copy), "parameter tensor is too large to be indexed with int32"); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_HALF_AND_BYTE(p_copy.scalar_type(), 0, "check_finite_cuda_kernel", strided_check_finite_cuda_kernel<<>>( overflow_flag.DATA_PTR(), p_copy.DATA_PTR(), tsize, stride, clear_overflow_first); ); THCudaCheck(cudaGetLastError()); } void fused_reversible_adam_cuda( at::Tensor & p, at::Tensor & p_copy, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { // using namespace at; //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors if (p_copy.numel() == 0 || p_copy.scalar_type() == g.scalar_type()) { DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.numel() ? p_copy.DATA_PTR() : NULL, m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { AT_ASSERTM(p_copy.scalar_type() == at::ScalarType::Byte, "expected parameter to be of byte type"); DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_e5m2_kernel", using accscalar_t = at::acc_type; reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), p_copy.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", reversible_adam_cuda_kernel<<>>( p.DATA_PTR(), NULL, //don't output p_copy for fp32, it's wasted write m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } void maybe_cast_cuda( at::Tensor & overflow_flag, at::Tensor & p_in, at::Tensor & p_out) { //Get tensor size int tsize = p_in.numel(); AT_ASSERTM(tsize == p_out.numel(), "p_in.numel() must equal p_out.numel()"); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p_in), "parameter tensor is too large to be indexed with int32"); //Constants cudaStream_t stream = at::cuda::getCurrentCUDAStream(); DISPATCH_FLOAT_HALF_AND_BYTE(p_in.scalar_type(), 0, "maybe_cast_cuda" DISPATCH_FLOAT_HALF_AND_BYTE(p_out.scalar_type(), 1, "maybe_cast_cuda", maybe_cast_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p_in.DATA_PTR(), p_out.DATA_PTR(), tsize); )) THCudaCheck(cudaGetLastError()); } void maybe_cast_cuda_mt( int chunk_size, at::Tensor overflow_flag, std::vector> tensor_lists) // p_in, p_out { //Constants cudaStream_t stream = at::cuda::getCurrentCUDAStream(); size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 2, "expected tensor lists of size 2"); DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[0][0].scalar_type(), 0, "maybe_cast_cuda_mt_kernel", DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[1][0].scalar_type(), 1, "maybe_cast_cuda_mt_kernel", multi_tensor_apply<2>( BLOCK_SIZE, chunk_size, overflow_flag, tensor_lists, MaybeCastFunctor<2, scalar_t_0, scalar_t_1>()); )) THCudaCheck(cudaGetLastError()); } void fused_maybe_adam_undo_cuda( at::Tensor & overflow_flag, at::Tensor & p, at::Tensor & m, at::Tensor & v, at::Tensor & g, float lr, float beta1, float beta2, float eps, float grad_scale, int step, int mode, int bias_correction, float decay) { //Get tensor size int tsize = p.numel(); //Determine #threads and #blocks const int threadsPerBlock = 512; const dim3 blocks((tsize+threadsPerBlock-1)/threadsPerBlock); AT_ASSERTM(at::cuda::detail::canUse32BitIndexMath(p), "parameter tensor is too large to be indexed with int32"); //Constants float step_size = 0; if (bias_correction == 1) { const float bias_correction1 = 1 - std::pow(beta1, step); const float bias_correction2 = 1 - std::pow(beta2, step); step_size = lr * std::sqrt(bias_correction2)/bias_correction1; } else { step_size = lr; } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (g.scalar_type() == at::ScalarType::Half) { //all other values should be fp32 for half gradients AT_ASSERTM(p.scalar_type() == at::ScalarType::Float, "expected parameter to be of float type"); //dispatch is done on the gradient type using namespace at; // prevents "toString is undefined" errors DISPATCH_FLOAT_AND_HALF(g.scalar_type(), 0, "adam_cuda_kernel", using accscalar_t = at::acc_type; maybe_adam_undo_cuda_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } else { using namespace at; DISPATCH_DOUBLE_AND_FLOAT(g.scalar_type(), 0, "adam_cuda_kernel", maybe_adam_undo_cuda_kernel<<>>( overflow_flag.numel() ? overflow_flag.DATA_PTR() : NULL, p.DATA_PTR(), m.DATA_PTR(), v.DATA_PTR(), g.DATA_PTR(), beta1, beta2, eps, grad_scale, step_size, tsize, (adamMode_t) mode, decay); ); } THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/fused_lamb_cuda.cpp ================================================ #include void multi_tensor_lamb_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int bias_correction, const float weight_decay, const int grad_averaging, const int mode, const float global_grad_norm, const float max_grad_norm); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("lamb", &multi_tensor_lamb_cuda, "Computes and apply update for LAMB optimizer"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/fused_lamb_cuda_kernel.cu ================================================ #include #include #include #include // Another possibility: // #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 typedef enum{ MOMENT_MODE_0 =0, // L2 regularization mode MOMENT_MODE_1 =1 // Decoupled weight decay mode } adamMode_t; std::tuple multi_tensor_l2norm_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::optional per_tensor_python); using MATH_T = float; template struct LAMBStage1Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<4>& tl, const float beta1, const float beta2, const float beta3, const float beta1_correction, const float beta2_correction, const float epsilon, adamMode_t mode, const float decay, const float global_grad_norm, const float max_global_grad_norm) { // I'd like this kernel to propagate infs/nans. // if(*noop_gmem == 1) // return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float clipped_global_grad_norm = global_grad_norm > max_global_grad_norm ? global_grad_norm / max_global_grad_norm : 1.0f; T* g = (T*)tl.addresses[0][tensor_loc]; g += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T*)tl.addresses[2][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T*)tl.addresses[3][tensor_loc]; v += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; // see note in multi_tensor_scale_kernel.cu for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_g[ii] = g[i]; // special ?optimization? for lamb stage 1 if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = p[i]; } r_m[ii] = m[i]; r_v[ii] = v[i]; } else { r_g[ii] = MATH_T(0); r_p[ii] = MATH_T(0); r_m[ii] = MATH_T(0); r_v[ii] = MATH_T(0); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / clipped_global_grad_norm; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / clipped_global_grad_norm; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { g[i] = r_p[ii]; m[i] = r_m[ii]; v[i] = r_v[ii]; } } } } }; // Step 2 reads in 'update' value and per-tensor param_norm and update_norm. // It computes new parameter value. template struct LAMBStage2Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<2>& tl, const float* per_tensor_param_norm, const float* per_tensor_update_norm, const float learning_rate, const float decay) { // I'd like this kernel to propagate infs/nans. // if(*noop_gmem == 1) // return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; MATH_T ratio = learning_rate; // apply adaptive learning rate to parameters with non-zero weight decay if (decay != 0.0) { float param_norm = per_tensor_param_norm[tensor_num]; float update_norm = per_tensor_update_norm[tensor_num]; ratio = (update_norm != 0.0f && param_norm != 0.0f) ? learning_rate * (param_norm / update_norm) : learning_rate; } T* update = (T*)tl.addresses[0][tensor_loc]; update += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_p[ILP]; MATH_T r_update[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_p[ii] = p[i]; r_update[ii] = update[i]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = r_p[ii] - (ratio * r_update[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { p[i] = r_p[ii]; } } } } }; void multi_tensor_lamb_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, const float lr, const float beta1, const float beta2, const float epsilon, const int step, const int bias_correction, const float weight_decay, const int grad_averaging, const int mode, const float global_grad_norm, const float max_grad_norm) { using namespace at; // Master weight and 32bit momentum(potentially changing) is not handled by this // So we assume every tensor are all in the same type // Handle bias correction mode float bias_correction1 = 1.0f, bias_correction2 = 1.0f; if (bias_correction == 1) { bias_correction1 = 1 - std::pow(beta1, step); bias_correction2 = 1 - std::pow(beta2, step); } // Handle grad averaging mode float beta3 = 1.0f; if (grad_averaging == 1) beta3 = 1 - beta1; std::vector> grad_list(tensor_lists.begin(), tensor_lists.begin()+1); std::vector> param_list(tensor_lists.begin()+1, tensor_lists.begin()+2); // Compute per tensor param norm auto param_norm_tuple = multi_tensor_l2norm_cuda(chunk_size, noop_flag, param_list, true); // We now in-place modify grad to store update before compute its norm // Generally this is not a issue since people modify grad in step() method all the time // We can also grab list of empty tensor to avoid this, but I'd like to save space/cpu code DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 0, "lamb_stage_1", multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, LAMBStage1Functor(), beta1, beta2, beta3, // 1-beta1 or 1 depends on averaging mode bias_correction1, bias_correction2, epsilon, (adamMode_t) mode, weight_decay, global_grad_norm, max_grad_norm); ) // Compute update norms auto update_norm_tuple = multi_tensor_l2norm_cuda(chunk_size, noop_flag, grad_list, true); std::vector> grad_param_list(tensor_lists.begin(), tensor_lists.begin()+2); DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 0, "lamb_stage_2", multi_tensor_apply<2>( BLOCK_SIZE, chunk_size, noop_flag, grad_param_list, LAMBStage2Functor(), std::get<1>(param_norm_tuple).DATA_PTR(), std::get<1>(update_norm_tuple).DATA_PTR(), lr, weight_decay); ) AT_CUDA_CHECK(cudaGetLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/multi_tensor_distopt_adam.cpp ================================================ #include void multi_tensor_fused_adam_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_bias_correction, at::Tensor per_tensor_eps, at::Tensor per_tensor_weight_decay, float lr, float grad_scale, int step, int mode); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("multi_tensor_fused_adam", &multi_tensor_fused_adam_cuda, "Multi tensor Adam optimized CUDA implementation."); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/multi_tensor_distopt_adam_kernel.cu ================================================ #include #include #include #include #include // Another possibility: // #include #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } typedef enum{ ADAM_MODE_0 =0, // eps under square root ADAM_MODE_1 =1 // eps outside square root } adamMode_t; template struct DistAdamFunctor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata& tl, const float* per_tensor_beta1, const float* per_tensor_beta2, const int* per_tensor_bias_correction, const float* per_tensor_eps, const float* per_tensor_weight_decay, const float lr, const float grad_scale, const int step, adamMode_t mode) { int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float b1 = per_tensor_beta1[tensor_num]; float b2 = per_tensor_beta2[tensor_num]; float eps = per_tensor_eps[tensor_num]; float decay = per_tensor_weight_decay[tensor_num]; float beta1_correction = 1.0f, beta2_correction = 1.0f; if (per_tensor_bias_correction[tensor_num] == 1) { beta1_correction = 1 - std::pow(b1, step); beta2_correction = 1 - std::pow(b2, step); } T* p = (T *)tl.addresses[0][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T *)tl.addresses[1][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T *)tl.addresses[2][tensor_loc]; v += chunk_idx*chunk_size; GRAD_T* g = (GRAD_T *)tl.addresses[3][tensor_loc]; g += chunk_idx*chunk_size; GRAD_T* p_copy = NULL; if (DEPTH == 5) { p_copy = (GRAD_T *)tl.addresses[4][tensor_loc]; p_copy += chunk_idx*chunk_size; } n -= chunk_idx*chunk_size; T incoming_p[ILP]; T incoming_m[ILP]; T incoming_v[ILP]; T incoming_g[ILP]; // to make things simple, we put aligned case in a different code path if (n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(m) && is_aligned(v) && is_aligned(g) && is_aligned(p_copy)) { for (int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load GRAD_T tmp_g[ILP]; load_store(incoming_p, p, 0, i_start); load_store(incoming_m, m, 0, i_start); load_store(incoming_v, v, 0, i_start); load_store(tmp_g, g, 0, i_start); #pragma unroll for (int ii = 0; ii < ILP; ii++) { incoming_g[ii] = static_cast(tmp_g[ii]); T scaled_grad = incoming_g[ii]/grad_scale; incoming_m[ii] = b1*incoming_m[ii] + (1-b1)*scaled_grad; incoming_v[ii] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; T next_m_unbiased = incoming_m[ii] / beta1_correction; T next_v_unbiased = incoming_v[ii] / beta2_correction; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(next_v_unbiased + eps); else // Mode 1 denom = sqrtf(next_v_unbiased) + eps; float update = (next_m_unbiased / denom) + (decay * incoming_p[ii]); incoming_p[ii] = incoming_p[ii] - (lr * update); if (DEPTH == 5) tmp_g[ii] = static_cast(incoming_p[ii]); } load_store(p, incoming_p, i_start, 0); load_store(m, incoming_m, i_start, 0); load_store(v, incoming_v, i_start, 0); if (DEPTH == 5) load_store(p_copy, tmp_g, i_start, 0); } } else { for (int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { #pragma unroll for (int ii = 0; ii < ILP; ii++) { incoming_p[ii] = 0; incoming_m[ii] = 0; incoming_v[ii] = 0; incoming_g[ii] = 0; int i = i_start + threadIdx.x + ii*blockDim.x; if (i < n && i < chunk_size) { incoming_p[ii] = p[i]; incoming_m[ii] = m[i]; incoming_v[ii] = v[i]; incoming_g[ii] = static_cast(g[i]); } } #pragma unroll for (int ii = 0; ii < ILP; ii++) { int j = i_start + threadIdx.x + ii*blockDim.x; if (j < n && j < chunk_size) { T scaled_grad = incoming_g[ii]/grad_scale; m[j] = b1*incoming_m[ii] + (1-b1)*scaled_grad; v[j] = b2*incoming_v[ii] + (1-b2)*scaled_grad*scaled_grad; T next_m_unbiased = m[j] / beta1_correction; T next_v_unbiased = v[j] / beta2_correction; float denom; if (mode == ADAM_MODE_0) denom = sqrtf(next_v_unbiased + eps); else // Mode 1 denom = sqrtf(next_v_unbiased) + eps; float update = (next_m_unbiased / denom) + (decay * incoming_p[ii]); p[j] = incoming_p[ii] - (lr * update); if (DEPTH == 5) p_copy[j] = (GRAD_T) p[j]; } } } } } }; void multi_tensor_fused_adam_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, // p, m, v, g, p_copy at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_bias_correction, at::Tensor per_tensor_eps, at::Tensor per_tensor_weight_decay, float lr, float grad_scale, int step, int mode) { using namespace at; size_t tl_sz = tensor_lists.size(); AT_ASSERTM(tl_sz == 4 || tl_sz == 5, "expected tensor lists of size 4 or 5"); if (tl_sz == 5) { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "dist_adam_cuda_kernel", // g using accscalar_t = at::acc_type; multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistAdamFunctor<5, accscalar_t, scalar_t_0>(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), per_tensor_eps.DATA_PTR(), per_tensor_weight_decay.DATA_PTR(), lr, grad_scale, step, (adamMode_t) mode); ); } else { DISPATCH_FLOAT_AND_HALF(tensor_lists[3][0].scalar_type(), 0, "dist_adam_cuda_kernel", // g using accscalar_t = at::acc_type; multi_tensor_apply<4>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistAdamFunctor<4, accscalar_t, scalar_t_0>(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), per_tensor_eps.DATA_PTR(), per_tensor_weight_decay.DATA_PTR(), lr, grad_scale, step, (adamMode_t) mode); ); } THCudaCheck(cudaGetLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/multi_tensor_distopt_lamb.cpp ================================================ #include void multi_tensor_lamb_compute_update_term_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_beta3, at::Tensor per_tensor_bias_correction, at::Tensor step, at::Tensor per_tensor_epsilon, const int mode, at::Tensor per_tensor_decay, at::Tensor global_scale, at::Tensor global_grad_norm, const float max_grad_norm); void multi_tensor_lamb_update_weights_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_param_norm, at::Tensor per_tensor_update_norm, at::Tensor update_norm_offset, at::Tensor learning_rate, at::Tensor per_tensor_decay, at::Tensor global_grad_norm, bool use_nvlamb); PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("multi_tensor_lamb_compute_update_term", &multi_tensor_lamb_compute_update_term_cuda, "Computes update term for LAMB optimizer"); m.def("multi_tensor_lamb_update_weights", &multi_tensor_lamb_update_weights_cuda, "Applies update term for LAMB optimizer"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/optimizers/multi_tensor_distopt_lamb_kernel.cu ================================================ #include #include #include #include // Another possibility: // #include #include #include "type_shim.h" #include "multi_tensor_apply.cuh" #define BLOCK_SIZE 512 #define ILP 4 template __device__ __forceinline__ bool is_aligned(T* p){ return ((uint64_t)p) % (ILP*sizeof(T)) == 0; } template __device__ __forceinline__ void load_store(T* dst, T* src, int dst_offset, int src_offset){ typedef typename std::aligned_storage::type LT; ((LT*)dst)[dst_offset] = ((LT*)src)[src_offset]; } template __device__ void convert(const FROM_T vi, TO_T& vo) { vo = static_cast(vi); } template <> __device__ void convert(const float vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = vi; s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, float& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = static_cast(t.as_half); } template <> __device__ void convert(const at::Half vi, uint8_t& vo) { union S { float as_float; int as_int; }; S s; s.as_float = static_cast(vi); s.as_int = s.as_int & 0xFF800000; union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_half = static_cast(vi + s.as_float / 8.0f); vo = t.as_byte[1]; } template <> __device__ void convert(const uint8_t vi, at::Half& vo) { union T { at::Half as_half; uint8_t as_byte[2]; }; T t; t.as_byte[0] = 0; t.as_byte[1] = vi; vo = t.as_half; } typedef enum{ MOMENT_MODE_0 =0, // L2 regularization mode MOMENT_MODE_1 =1 // Decoupled weight decay mode } adamMode_t; template struct DistOptLAMBStage1Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<5>& tl, const MATH_T* per_tensor_beta1, const MATH_T* per_tensor_beta2, const MATH_T* per_tensor_beta3, const int* per_tensor_bias_correction, const int* step, const MATH_T* per_tensor_epsilon, adamMode_t mode, const MATH_T* per_tensor_decay, const MATH_T* global_scale, const MATH_T* global_grad_norm, const float max_grad_norm) { // I'd like this kernel to propagate infs/nans. if (*noop_gmem == 1) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; float combined_scale = *global_scale; if (max_grad_norm > 0) { combined_scale = max_grad_norm / (*global_grad_norm / *global_scale + 1e-6); combined_scale = *global_scale / std::min((float) 1.0, combined_scale); } MATH_T beta1 = per_tensor_beta1[tensor_num]; MATH_T beta2 = per_tensor_beta2[tensor_num]; MATH_T beta3 = 1 - beta1; MATH_T beta1_correction, beta2_correction; if (per_tensor_bias_correction[tensor_num] == 1) { beta1_correction = 1 - pow(beta1, *step); beta2_correction = 1 - pow(beta2, *step); } else { beta1_correction = (MATH_T) 1.0; beta2_correction = (MATH_T) 1.0; } MATH_T epsilon = per_tensor_epsilon[tensor_num]; MATH_T decay = per_tensor_decay[tensor_num]; GRAD_T* g = (GRAD_T*)tl.addresses[0][tensor_loc]; g += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; T* m = (T*)tl.addresses[2][tensor_loc]; m += chunk_idx*chunk_size; T* v = (T*)tl.addresses[3][tensor_loc]; v += chunk_idx*chunk_size; MATH_T* u = (MATH_T*)tl.addresses[4][tensor_loc]; u += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(g) && is_aligned(p) && is_aligned(m) && is_aligned(v)) { GRAD_T l_g[ILP]; T l_p[ILP]; T l_m[ILP]; T l_v[ILP]; for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load load_store(l_g, g, 0, i_start); if (decay != 0) load_store(l_p, p, 0, i_start); load_store(l_m, m, 0, i_start); load_store(l_v, v, 0, i_start); // unpack #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_g[ii] = l_g[ii]; if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = l_p[ii]; } r_m[ii] = l_m[ii]; r_v[ii] = l_v[ii]; } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / combined_scale; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / combined_scale; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { l_m[ii] = r_m[ii]; l_v[ii] = r_v[ii]; } // store load_store(u, r_p, i_start, 0); load_store(m, l_m, i_start, 0); load_store(v, l_v, i_start, 0); } } else { // see note in multi_tensor_scale_kernel.cu for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_g[ILP]; MATH_T r_p[ILP]; MATH_T r_m[ILP]; MATH_T r_v[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_g[ii] = g[i]; // special ?optimization? for lamb stage 1 if (decay == 0) { r_p[ii] = MATH_T(0); } else { r_p[ii] = p[i]; } r_m[ii] = m[i]; r_v[ii] = v[i]; } else { r_g[ii] = MATH_T(0); r_p[ii] = MATH_T(0); r_m[ii] = MATH_T(0); r_v[ii] = MATH_T(0); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { if (mode == MOMENT_MODE_0) { MATH_T scaled_grad = r_g[ii] / combined_scale; // L2 on scaled grad scaled_grad = scaled_grad + decay*r_p[ii]; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = next_m_unbiased / denom; } else { MATH_T scaled_grad = r_g[ii] / combined_scale; r_m[ii] = r_m[ii] * beta1 + beta3 * scaled_grad; r_v[ii] = r_v[ii] * beta2 + (1-beta2) * scaled_grad * scaled_grad; MATH_T next_m_unbiased = r_m[ii] / beta1_correction; MATH_T next_v_unbiased = r_v[ii] / beta2_correction; MATH_T denom = sqrtf(next_v_unbiased) + epsilon; r_p[ii] = (next_m_unbiased/denom) + (decay*r_p[ii]); } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { u[i] = r_p[ii]; m[i] = r_m[ii]; v[i] = r_v[ii]; } } } } } }; // Step 2 reads in 'update' value and per-tensor param_norm and update_norm. // It computes new parameter value. template struct DistOptLAMBStage2Functor { __device__ __forceinline__ void operator()( int chunk_size, volatile int* noop_gmem, TensorListMetadata<3>& tl, const MATH_T* per_tensor_param_norm, const MATH_T* per_tensor_update_norm, const long* update_norm_offset, const MATH_T* learning_rate, const MATH_T* per_tensor_decay, const MATH_T* global_grad_norm, bool use_nvlamb) { // I'd like this kernel to propagate infs/nans. if (*noop_gmem == 1) return; int tensor_loc = tl.block_to_tensor[blockIdx.x]; int tensor_num = tl.start_tensor_this_launch + tensor_loc; int chunk_idx = tl.block_to_chunk[blockIdx.x]; int n = tl.sizes[tensor_loc]; MATH_T decay = per_tensor_decay[tensor_num]; MATH_T ratio = *learning_rate; // nvlamb: apply adaptive learning rate to all parameters // otherwise, only apply to those with non-zero weight decay if (use_nvlamb || (decay != (MATH_T) 0.0)) { MATH_T param_norm = per_tensor_param_norm[tensor_num]; MATH_T update_norm = per_tensor_update_norm[update_norm_offset[tensor_num]]; ratio = (update_norm != 0.0 && param_norm != 0.0) ? (*learning_rate) * (param_norm / update_norm) : (*learning_rate); } MATH_T* update = (MATH_T*)tl.addresses[0][tensor_loc]; update += chunk_idx*chunk_size; T* p = (T*)tl.addresses[1][tensor_loc]; p += chunk_idx*chunk_size; GRAD_T* p_copy = (GRAD_T*)tl.addresses[2][tensor_loc]; p_copy += chunk_idx*chunk_size; n -= chunk_idx*chunk_size; // to make things simple, we put aligned case in a different code path if(n % ILP == 0 && chunk_size % ILP == 0 && is_aligned(p) && is_aligned(update)) { T r_p[ILP]; MATH_T r_update[ILP]; GRAD_T r_p_copy[ILP]; for(int i_start = threadIdx.x; i_start*ILP < n && i_start*ILP < chunk_size; i_start += blockDim.x) { // load load_store(r_p, p, 0, i_start); load_store(r_update, update, 0, i_start); #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = static_cast(r_p[ii]) - (ratio * r_update[ii]); convert(r_p[ii], r_p_copy[ii]); } load_store(p, r_p, i_start, 0); load_store(p_copy, r_p_copy, i_start, 0); } } else { for(int i_start = 0; i_start < n && i_start < chunk_size; i_start += blockDim.x*ILP) { MATH_T r_p[ILP]; MATH_T r_update[ILP]; #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { r_p[ii] = p[i]; r_update[ii] = update[i]; } } #pragma unroll for(int ii = 0; ii < ILP; ii++) { r_p[ii] = r_p[ii] - (ratio * r_update[ii]); } #pragma unroll for(int ii = 0; ii < ILP; ii++) { int i = i_start + threadIdx.x + ii*blockDim.x; if(i < n && i < chunk_size) { p[i] = r_p[ii]; convert(r_p[ii], p_copy[i]); } } } } } }; void multi_tensor_lamb_compute_update_term_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_beta1, at::Tensor per_tensor_beta2, at::Tensor per_tensor_beta3, at::Tensor per_tensor_bias_correction, at::Tensor step, at::Tensor per_tensor_epsilon, const int mode, at::Tensor per_tensor_decay, at::Tensor global_scale, at::Tensor global_grad_norm, const float max_grad_norm) { using namespace at; DISPATCH_FLOAT_AND_HALF(tensor_lists[1][0].scalar_type(), 0, "lamb_stage_1", DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 1, "lamb_stage_1", DISPATCH_FLOAT_AND_HALF(tensor_lists[4][0].scalar_type(), 2, "lamb_stage_1", multi_tensor_apply<5>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistOptLAMBStage1Functor(), per_tensor_beta1.DATA_PTR(), per_tensor_beta2.DATA_PTR(), per_tensor_beta3.DATA_PTR(), per_tensor_bias_correction.DATA_PTR(), step.DATA_PTR(), per_tensor_epsilon.DATA_PTR(), (adamMode_t) mode, per_tensor_decay.DATA_PTR(), global_scale.DATA_PTR(), global_grad_norm.DATA_PTR(), max_grad_norm); ))) AT_CUDA_CHECK(cudaGetLastError()); } void multi_tensor_lamb_update_weights_cuda( int chunk_size, at::Tensor noop_flag, std::vector> tensor_lists, at::Tensor per_tensor_param_norm, at::Tensor per_tensor_update_norm, at::Tensor update_norm_offset, at::Tensor learning_rate, at::Tensor per_tensor_decay, at::Tensor global_grad_norm, bool use_nvlamb) { using namespace at; DISPATCH_FLOAT_AND_HALF(tensor_lists[1][0].scalar_type(), 0, "lamb_stage_2", DISPATCH_FLOAT_HALF_AND_BYTE(tensor_lists[2][0].scalar_type(), 1, "lamb_stage_2", DISPATCH_FLOAT_AND_HALF(tensor_lists[0][0].scalar_type(), 2, "lamb_stage_2", multi_tensor_apply<3>( BLOCK_SIZE, chunk_size, noop_flag, tensor_lists, DistOptLAMBStage2Functor(), per_tensor_param_norm.DATA_PTR(), per_tensor_update_norm.DATA_PTR(), update_norm_offset.DATA_PTR(), learning_rate.DATA_PTR(), per_tensor_decay.DATA_PTR(), global_grad_norm.DATA_PTR(), use_nvlamb); ))) AT_CUDA_CHECK(cudaGetLastError()); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/transducer/transducer_joint.cpp ================================================ #include #include #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector transducer_joint_cuda_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize); std::vector transducer_joint_cuda_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale); std::vector transducer_joint_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize) { CHECK_INPUT(f); CHECK_INPUT(g); CHECK_INPUT(fLen); CHECK_INPUT(gLen); if (packOutput) CHECK_INPUT(batchOffset); return transducer_joint_cuda_forward( f, g, fLen, gLen, batchOffset, packedBatch, opt, packOutput, relu, dropout, dropoutProb, tileSize); } std::vector transducer_joint_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale) { for (auto t : in){ CHECK_INPUT(t); } CHECK_INPUT(fLen); CHECK_INPUT(gLen); if (packOutput) CHECK_INPUT(batchOffset); return transducer_joint_cuda_backward( in, fLen, gLen, batchOffset, maxFLen, maxGLen, packOutput, scale); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &transducer_joint_forward, "transducer joint forward (CUDA)"); m.def("backward", &transducer_joint_backward, "transducer joint backward (CUDA)"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/transducer/transducer_joint_kernel.cu ================================================ #include #include #include #include #include #include #include #include #include #include #include "philox.h" // Warp reduce kernels to reduce N groups of data into N numbers, where N = warpSize / width. // width should be a power of 2 and should be less than warpSize. template __device__ __forceinline__ scalar_t warpReduce(scalar_t x, int width=C10_WARP_SIZE){ for (unsigned offset = width/2; offset > 0; offset /= 2){ x += __shfl_down_sync(0xffffffff, x, offset, width); } return x; } inline int largestPowerOfTwo(int x){ int y = 1; while (y <= x) y <<= 1; return y >> 1; } /* Figure out vectorization type for masks. Similar to how PyTorch figures out acc_t here: aten/src/ATen/AccumulateType.h */ template struct MaskVecType { }; template <> struct MaskVecType<1> { using type = uint8_t; }; template <> struct MaskVecType<2> { using type = uint16_t; }; template <> struct MaskVecType<4> { using type = uint32_t; }; template using mvec_type = typename MaskVecType::type; // Helper class to calculate pointer offset that can be shared by different flavors of kernels. // For fwd, batch offset and stride are different for packing and non-packing mode. struct OffsetCalFwd{ __device__ __forceinline__ OffsetCalFwd( int64_t batch, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t gLen, int64_t hiddenSize, bool packOutput) : batch(batch), batchOffset(batchOffset), maxFLen(maxFLen), maxGLen(maxGLen), gLen(gLen), hiddenSize(hiddenSize), packOutput(packOutput) {} int64_t batch; const int64_t *batchOffset; int64_t maxFLen; int64_t maxGLen; int64_t gLen; int64_t hiddenSize; bool packOutput; __device__ __forceinline__ int64_t getBatchOffset(){ return packOutput ? ((batch==0) ? 0 : batchOffset[batch-1])*hiddenSize : batch*maxFLen*maxGLen*hiddenSize; } __device__ __forceinline__ int64_t getStrideF(){ return packOutput ? gLen*hiddenSize : maxGLen*hiddenSize; } }; // Helper class to calculate pointer offset that can be shared by different flavors of kernels // For bwd, batch offset and stride are different for packing and non-packing mode. // The reducion is done for two input tensors. Therefore, generating two sets of offsets // according to bwdFasterDim can lead to a unified implementation in the actual kernel. struct OffsetCalBwd{ __device__ __forceinline__ OffsetCalBwd( int64_t batch, const int64_t *batchOffset, const int *fLen, const int *gLen, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim) : batch(batch), batchOffset(batchOffset), maxFLen(maxFLen), maxGLen(maxGLen), fLen(fLen), gLen(gLen), hiddenSize(hiddenSize), packOutput(packOutput), bwdFasterDim(bwdFasterDim) {} int64_t batch; const int64_t *batchOffset; const int *fLen; const int *gLen; int64_t maxFLen; int64_t maxGLen; int64_t hiddenSize; bool packOutput; bool bwdFasterDim; // whether doing bwd on the faster moving dimension __device__ __forceinline__ int64_t getBatchOffset(){ return packOutput ? ((batch==0) ? 0 : batchOffset[batch-1])*hiddenSize : batch*maxFLen*maxGLen*hiddenSize; } __device__ __forceinline__ int64_t getMaxXLen(){ return bwdFasterDim ? maxGLen : maxFLen; } __device__ __forceinline__ auto getMyXLen() -> decltype(gLen[batch]){ return bwdFasterDim ? gLen[batch] : fLen[batch]; } __device__ __forceinline__ auto getMyYLen() -> decltype(gLen[batch]){ return bwdFasterDim ? fLen[batch] : gLen[batch]; } __device__ __forceinline__ int64_t getStrideX(){ return bwdFasterDim ? hiddenSize : ((packOutput ? gLen[batch] : maxGLen) * hiddenSize); } __device__ __forceinline__ int64_t getStrideY(){ return bwdFasterDim ? ((packOutput ? gLen[batch] : maxGLen) * hiddenSize) : hiddenSize; } }; // Vanila transducer joint forward kernel // Detail of this joint function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // f is a tensor of shape [batch, T, H] // g is a tensor of shape [batch, U, H] // the transducer joint does // sum = f.unsqueeze(dim=2) + g.unsqueeze(dim=1) // The resultant tensor is of shape [batch, T, U, H] // Each thread block is working on one "batch" of data in the output tensor, [batch, t, u, :] // This joint function can optionally pack the output where the output tensor with a shape of // [B, T, U, H] is packed into [B_packed, H]. // Don't-care region (t > fLen) or (u > gLen) is removed. // To enable packing, the starting offset for each batch need to be specified with batchOffset. template __global__ void transducer_joint_forward( const scalar_t *f, const scalar_t *g, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, scalar_t *sum) { const int batch = blockIdx.z; const int t = blockIdx.y; const int u = blockIdx.x; const auto myFLen = fLen[batch]; const auto myGLen = gLen[batch]; OffsetCal offsetCal(batch, batchOffset, maxFLen, maxGLen, myGLen, hiddenSize, packOutput); const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideF = offsetCal.getStrideF(); scalar_t const *myF = f + batch*maxFLen*hiddenSize + t*hiddenSize; scalar_t const *myG = g + batch*maxGLen*hiddenSize + u*hiddenSize; scalar_t *mySum = sum + myBatchOffset + t*strideF + u * hiddenSize; if (t < myFLen and u < myGLen){ #pragma unroll for (int h = threadIdx.x; h < hiddenSize; h += blockDim.x){ if (h < hiddenSize){ mySum[h] = myF[h] + myG[h]; } } } else if (packOutput == false and t < maxFLen and u < maxGLen){ // Need to write finite data to don't-care region because we instantiate the result tensor // with torch::empty for performance reasons. Even though it is don't-care region, the // contents need to be finite, otherwise could lead to NaN in WGRAD. // In packing mode, this write is no longer necessary as we remove the don't-care region // from the output. // Picking -1 (over 0) here for ease of testing. #pragma unroll for (int h = threadIdx.x; h < hiddenSize; h += blockDim.x){ if (h < hiddenSize){ mySum[h] = -1; } } } } /* Tiled version of the joint forward kernel Detail of this joint function can be found in: [1] Sequence Transduction with Recurrent Neural Networks. f is a tensor of shape [batch, T, H] g is a tensor of shape [batch, U, H] the transducer joint does sum = f.unsqueeze(dim=2) + g.unsqueeze(dim=1) The resultant tensor is of shape [batch, T, U, H] Each thread is working on a tile of the shape of tileF x tileG in the result tensor. The input for the tile is first loaded in the register and is reused tileG and tileF times. This joint function can optionally pack the output where the output tensor with a shape of [B, T, U, H] is packed into [B_packed, H]. Don't-care region (t > fLen) or (u > gLen) is removed. To enable packing, the starting offset for each batch need to be specified with batchOffset. Optionally this joint function performs ReLU and/or dropout on the joint output, which is controlled by arguments relu and dropout, respectively. philoxArgs is argument used for generating pseudorandom number. When at least one of operations in ReLU and dropout is activated, the joint function is a masked operation, which is controlled by the template argument masked. In this case, masks are saved to backward. */ template __global__ void transducer_joint_tiled_forward( const scalar_t *f, const scalar_t *g, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, int64_t hiddenPerBlock, bool packOutput, bool relu, bool dropout, float p, at::PhiloxCudaState philoxArgs, scalar_t *sum, uint8_t *mask) { static_assert(U == 4, "U has to be 4, as random numbers are generated in batch of 4"); const int batch = blockIdx.z; const int t = blockIdx.y * tileF; const int hiddenBlock = (hiddenSize + hiddenPerBlock - 1) / hiddenPerBlock; const int u = blockIdx.x / hiddenBlock * tileG; const int hOffset = (blockIdx.x % hiddenBlock) * hiddenPerBlock; const int h = threadIdx.x; const auto myFLen = fLen[batch]; const auto myGLen = gLen[batch]; OffsetCal offsetCal(batch, batchOffset, maxFLen, maxGLen, myGLen, hiddenSize, packOutput); const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideF = offsetCal.getStrideF(); scalar_t const *myF = f + batch*maxFLen*hiddenSize + t*hiddenSize + hOffset; scalar_t const *myG = g + batch*maxGLen*hiddenSize + u*hiddenSize + hOffset; scalar_t *mySum = sum + myBatchOffset + t*strideF + u*hiddenSize + hOffset; uint8_t *myMask = mask + myBatchOffset + t*strideF + u*hiddenSize + hOffset; // The following code is only needed for dropout. We try to bypass them as much as possible. auto seeds = masked ? at::cuda::philox::unpack(philoxArgs) : std::make_tuple(static_cast(0), static_cast(0)); uint64_t tid = masked ? (static_cast(blockIdx.z)*gridDim.y*gridDim.x + blockIdx.y*gridDim.x + blockIdx.x) * blockDim.x + threadIdx.x : 0; Philox ph(std::get<0>(seeds), tid, std::get<1>(seeds)); scalar_t scale = masked ? ((p == 0) ? 0 : 1 / p) : 0; bool dropoutMask[U]; if (t < myFLen and u < myGLen and hOffset+h < hiddenSize){ // register buffers for tiled input reuse scalar_t fBuffer[tileF], gBuffer[tileG]; for (int i = 0; i < tileF; ++i){ if (t + i < myFLen) fBuffer[i] = myF[i*hiddenSize + h]; } for (int j = 0; j < tileG; ++j){ if (u + j < myGLen) gBuffer[j] = myG[j*hiddenSize + h]; } #pragma unroll for (int i = 0; i < tileF; ++i){ if (t + i < myFLen){ #pragma unroll for (int j = 0; j < tileG; ++j){ int idx = i*tileG + j; if (masked and dropout and idx % U == 0){ // For performance, generate 4 random numbers in one shot // auto rand4 = curand_uniform4(&state); auto rand4 = uniform4(ph()); dropoutMask[0] = rand4.x < p; dropoutMask[1] = rand4.y < p; dropoutMask[2] = rand4.z < p; dropoutMask[3] = rand4.w < p; } if (u + j < myGLen){ scalar_t out = fBuffer[i] + gBuffer[j]; if (masked){ // Apply ReLU here when relu is True bool localMask = relu ? (out>0) : 1; localMask = dropout ? localMask & dropoutMask[idx%U] : localMask; out = dropout ? out*localMask*scale : out*localMask; myMask[i*strideF + j*hiddenSize + h] = static_cast(localMask); } mySum[i*strideF + j*hiddenSize + h] = out; } else if (packOutput == false and u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } else if (packOutput == false and t + i < maxFLen){ // Again need to write finite data to don't-care region #pragma unroll for (int j = 0; j < tileG; ++j){ if (u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } } } else if (packOutput == false and t < maxFLen and u < maxGLen and hOffset+h < hiddenSize){ // Only need to ensure the finity in normal mode #pragma unroll for (int i = 0; i < tileF; ++i){ if (t + i < maxFLen){ #pragma unroll for (int j = 0; j < tileG; ++j){ if (u + j < maxGLen) mySum[i*strideF + j*hiddenSize + h] = -1; } } } } } /* Bwd operation (reduction) on one input tensor. Since the operation performed for the two input tensors are exactly the same, only one kernel is needed, and the different indexing offsets and strides are handled by OffsetCalBwd. When packing is enabled in the fwd op, unpacking is needed to restore the gradients in a non-packed form. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __device__ void transducer_joint_single_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim, // whether bwd on the faster moving dimension (u) float scale, scalar_t *inGrad, int yBlockOffset=0) { const int batch = blockIdx.z; // For the second input tensor, this offset need to be subtracted because the first yBlockOffset // sets of thread blocks are for the first input tensor. const int x = blockIdx.y-yBlockOffset; const int hOffset = blockIdx.x*C10_WARP_SIZE; const int wid = threadIdx.y; const int lid = threadIdx.x; const int numWarp = blockDim.y; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); OffsetCal offsetCal(batch, batchOffset, fLen, gLen, maxFLen, maxGLen, hiddenSize, packOutput, bwdFasterDim); const auto maxXLen = offsetCal.getMaxXLen(); const auto myXLen = offsetCal.getMyXLen(); const auto myYLen = offsetCal.getMyYLen(); scalar_t *myInGrad = inGrad + batch*maxXLen*hiddenSize + x*hiddenSize + hOffset; if (x < myXLen){ const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideX = offsetCal.getStrideX(); const auto strideY = offsetCal.getStrideY(); const scalar_t *myGrad = grad + myBatchOffset + x*strideX + hOffset; const uint8_t *myMask = masked ? mask + myBatchOffset + x*strideX + hOffset : nullptr; // Each warp reduces numYPerWarp "y" first acc_t warpSum = 0; auto numYPerWarp = (myYLen+numWarp-1)/numWarp; #pragma unroll for (int warpY = 0; warpY < numYPerWarp; ++warpY){ auto y = wid*numYPerWarp + warpY; if (y < myYLen and (hOffset+lid) < hiddenSize) if (masked) warpSum += static_cast(myGrad[y*strideY + lid]) * myMask[y*strideY + lid] * scale; else warpSum += myGrad[y*strideY + lid]; } // transpose partial sum in SMEM and reduce further using warpReduce smem[lid*numWarp + wid] = warpSum; __syncthreads(); auto sum = smem[wid*C10_WARP_SIZE + lid]; sum = warpReduce(sum, numWarp); // a a b b c c d d // a a b b c c d d // a a b b c c d d // a a b b c c d d // example of 4 warps (a, b, c, d) with 8 threads per warp // Each warp need 8 / 4 = 2 threads to write the results. if (hOffset+wid*C10_WARP_SIZE/numWarp+lid/numWarp < hiddenSize){ if (lid % numWarp == 0){ myInGrad[wid*C10_WARP_SIZE/numWarp + lid/numWarp] = sum; } } } else if (wid == 0 and hOffset + lid < hiddenSize){ // Need to ensure the grad is zero for don't care region myInGrad[lid] = 0; } } /* Actual bwd (reduction) kernel get launched. Call transducer_joint_single_backward twice on two input tensors. The two bwd ops are launched together, the first op uses blockIdx.y < maxFLen, and the second op uses the rest. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __global__ void transducer_joint_combined_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, float scale, scalar_t *fGrad, scalar_t *gGrad) { if (blockIdx.y < maxFLen){ transducer_joint_single_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, false, scale, fGrad); } else{ transducer_joint_single_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, true, scale, gGrad, maxFLen); } } /* Vectorized version of transducer_joint_single_backward Doing exact same operation as transducer_joint_single_backward except the load and store are vectorized. When packing is enabled in the fwd op, unpacking is needed to restore the gradients in a non-packed form. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __device__ void transducer_joint_single_vec_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, bool bwdFasterDim, float scale, scalar_t *inGrad, int yBlockOffset=0){ const int batch = blockIdx.z; const int x = blockIdx.y - yBlockOffset; const int hOffset = blockIdx.x*C10_WARP_SIZE*V; const int wid = threadIdx.y; const int lid = threadIdx.x; const int numWarp = blockDim.y; // Figure out the vectorization type for mask using mvec_t = mvec_type; OffsetCal offsetCal(batch, batchOffset, fLen, gLen, maxFLen, maxGLen, hiddenSize, packOutput, bwdFasterDim); const auto maxXLen = offsetCal.getMaxXLen(); const auto myXLen = offsetCal.getMyXLen(); const auto myYLen = offsetCal.getMyYLen(); scalar_t *myInGrad = inGrad + batch*maxXLen*hiddenSize + x*hiddenSize + hOffset; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); acc_t warpSum[V]; scalar_t inBuffer[V]; uint8_t maskBuffer[V]; scalar_t outBuffer[V]; auto myInGradVec = reinterpret_cast(myInGrad); auto outBufferVec = reinterpret_cast(outBuffer); if (x < myXLen){ const auto myBatchOffset = offsetCal.getBatchOffset(); const auto strideX = offsetCal.getStrideX(); const auto strideY = offsetCal.getStrideY(); const scalar_t *myGrad = grad + myBatchOffset + x*strideX + hOffset; const uint8_t *myMask = masked ? mask + myBatchOffset + x*strideX + hOffset :nullptr; for (int i = 0; i < V; ++i) warpSum[i] = 0; // Each warp reduces numYPerWarp "y" first auto numYPerWarp = (myYLen+numWarp-1)/numWarp; for (int warpY = 0; warpY < numYPerWarp; ++warpY){ auto y = wid*numYPerWarp + warpY; auto myGradVec = reinterpret_cast(myGrad + y*strideY); auto myMaskVec = masked ? reinterpret_cast(myMask + y*strideY) : nullptr; auto inBufferVec = reinterpret_cast(inBuffer); auto maskBufferVec = reinterpret_cast(maskBuffer); if (hOffset + lid*V < hiddenSize and y < myYLen){ *inBufferVec = myGradVec[lid]; // vectorized load if (masked){ *maskBufferVec = myMaskVec[lid]; #pragma unroll for (int i = 0; i < V; ++i) warpSum[i] += static_cast(inBuffer[i]) * maskBuffer[i] * scale; } else{ #pragma unroll for (int i = 0; i < V; ++i) warpSum[i] += inBuffer[i]; } } } // transpose partial sum in SMEM and reduce further using warpReduce for (int i = 0; i < V; ++i){ smem[lid*numWarp + wid] = warpSum[i]; __syncthreads(); auto sum = smem[wid*C10_WARP_SIZE + lid]; if (hOffset+(wid*C10_WARP_SIZE/numWarp)*V < hiddenSize){ sum = warpReduce(sum, numWarp); if (lid % numWarp == 0){ outBuffer[i] = sum; } } __syncthreads(); } // a a b b c c d d // a a b b c c d d // a a b b c c d d // a a b b c c d d // example of 4 warps (a, b, c, d) with 8 threads per warp // Each warp need 8 / 4 = 2 threads to write the results. if (lid % numWarp == 0 and hOffset+(wid*C10_WARP_SIZE/numWarp + lid/numWarp)*V < hiddenSize) myInGradVec[wid*C10_WARP_SIZE/numWarp + lid/numWarp] = *outBufferVec; } else if (wid == 0 and hOffset + lid*V < hiddenSize){ // Need to ensure the grad is zero for don't care region myInGradVec[lid] = 0; } } /* Vecotrized version of transducer_joint_combined_backward Call transducer_joint_single_vec_backward twice on two input tensors. The two bwd ops are launched together, the first op uses blockIdx.y < maxFLen, and the second op uses the rest. When ReLU and/or dropout are performed in the fwd pass, this operation becomes a masked operation, and mask contains the mask information. */ template __global__ void transducer_joint_combined_vec_backward( const scalar_t *grad, const uint8_t *mask, const int *fLen, const int *gLen, const int64_t *batchOffset, int64_t maxFLen, int64_t maxGLen, int64_t hiddenSize, bool packOutput, float scale, scalar_t *fGrad, scalar_t *gGrad) { if (blockIdx.y < maxFLen){ transducer_joint_single_vec_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, false, scale, fGrad); } else{ transducer_joint_single_vec_backward( grad, mask, fLen, gLen, batchOffset, maxFLen, maxGLen, hiddenSize, packOutput, true, scale, gGrad, maxFLen); } } std::vector transducer_joint_cuda_forward( torch::Tensor f, torch::Tensor g, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int64_t packedBatch, int opt, bool packOutput, bool relu, bool dropout, float dropoutProb, int tileSize){ auto tensorOpt = f.options(); auto dtype = f.scalar_type(); const auto batchSize = f.size(0); const auto maxFLen = f.size(1); const auto maxGLen = g.size(1); const auto hiddenSize = f.size(2); bool masked = dropout or relu; int64_t *batchOffsetPtr = nullptr; torch::Tensor sum, mask; auto maskOpt = tensorOpt.dtype(torch::kUInt8); if (!packOutput){ sum = torch::empty({batchSize, maxFLen, maxGLen, hiddenSize}, tensorOpt); batchOffsetPtr = nullptr; if (masked) mask = torch::empty({batchSize, maxFLen, maxGLen, hiddenSize}, maskOpt); } else{ sum = torch::empty({packedBatch, hiddenSize}, tensorOpt); batchOffsetPtr = batchOffset.data_ptr(); if (masked) mask = torch::empty({packedBatch, hiddenSize}, maskOpt); } uint8_t *maskPtr = masked ? mask.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); TORCH_CHECK(opt == 0 or opt == 1, "Got an invalid optimization level ", opt); // Simple heuristics const int numThread = std::min(128, (static_cast(hiddenSize)+C10_WARP_SIZE-1) / C10_WARP_SIZE * C10_WARP_SIZE); if (opt == 0){ // vanilla kernel const int threads = numThread; const dim3 blocks(maxGLen, maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_forward", ([&] { transducer_joint_forward <<>>( f.data_ptr(), g.data_ptr(), fLen.data_ptr(), gLen.data_ptr(), batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, sum.data_ptr()); })); } if (opt == 1){ // tiled version. For simplicity, assume tileF == tileG, even though the kernel can // support more general cases. const int threads = numThread; const int hiddenPerBlock = numThread; const int hiddenBlock = (hiddenSize + hiddenPerBlock - 1) / hiddenPerBlock; const dim3 blocks( (maxGLen+tileSize-1)/tileSize * hiddenBlock, (maxFLen+tileSize-1)/tileSize, batchSize); TORCH_CHECK(tileSize == 1 or tileSize == 2 or tileSize == 4, "Expected tileSize to be in [1, 2, 4], but got ", tileSize); at::PhiloxCudaState rng_engine_inputs; if (masked){ // set up PRG when the input is masked. rng_engine_inputs will be used as a space filler // for non-masked calls. // Therefore no need to initialize. c10::optional gen_; auto gen = at::get_generator_or_default(gen_, at::cuda::detail::getDefaultCUDAGenerator()); // counterOffset records how many cuRAND calls each thread makes. For a tiled kernel, // each thread processes tileF * tileG output elements. int64_t counterOffset = tileSize * tileSize; { std::lock_guard lock(gen->mutex_); rng_engine_inputs = gen->philox_cuda_state(counterOffset); } } AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_forward", ([&] { void(*kernel)(const scalar_t*, const scalar_t*, const int*, const int*, const int64_t*, int64_t, int64_t, int64_t, int64_t, bool, bool, bool, float, at::PhiloxCudaState, scalar_t*, uint8_t*); if (masked){ switch (tileSize){ case 2: kernel = &transducer_joint_tiled_forward; break; case 4: kernel = &transducer_joint_tiled_forward; break; } } else{ switch (tileSize){ case 1: kernel = &transducer_joint_tiled_forward; break; case 2: kernel = &transducer_joint_tiled_forward; break; case 4: kernel = &transducer_joint_tiled_forward; break; } } kernel<<>>( f.data_ptr(), g.data_ptr(), fLen.data_ptr(), gLen.data_ptr(), batchOffsetPtr, maxFLen, maxGLen, hiddenSize, hiddenPerBlock, packOutput, relu, dropout, 1.0f - dropoutProb, rng_engine_inputs, sum.data_ptr(), maskPtr); })); } THCudaCheck(cudaGetLastError()); if (masked) return {sum, mask}; else return {sum}; } std::vector transducer_joint_cuda_backward( std::vector in, torch::Tensor fLen, torch::Tensor gLen, torch::Tensor batchOffset, int maxFLen, int maxGLen, bool packOutput, float scale){ auto grad = in[0]; bool masked = (in.size() == 2); uint8_t *maskPtr = masked ? in[1].data_ptr() : nullptr; auto tensorOpt = grad.options(); auto dtype = grad.scalar_type(); const int batchSize = fLen.size(0); const int hiddenSize = grad.size(-1); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const int maxNumWarp = deviceProperties->maxThreadsPerBlock / C10_WARP_SIZE; torch::Tensor fGrad = torch::empty({batchSize, maxFLen, hiddenSize}, tensorOpt); torch::Tensor gGrad = torch::empty({batchSize, maxGLen, hiddenSize}, tensorOpt); int64_t *batchOffsetPtr = (!packOutput) ? nullptr : batchOffset.data_ptr(); // The number "y" I would like each thread to work on const int workPerThread = 32; // Since the bwd for f and g have the same thread block size, we need to use the max of the two. int numWarp = largestPowerOfTwo((std::max(maxFLen, maxGLen) + workPerThread-1) / workPerThread); // Would like to have at least 2 warps numWarp = std::max(2, numWarp); // cap on the maximum number of warps allowed numWarp = std::min(maxNumWarp, numWarp); // Need smem for transposing the partial sum. The partial sum is in a matrix of the shape // numWarp x warpSize const int smemSize = numWarp * C10_WARP_SIZE; const dim3 threads(C10_WARP_SIZE, numWarp, 1); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_joint_cuda_backward_kernel", ([&] { auto gradPtr = grad.data_ptr(); auto fLenPtr = fLen.data_ptr(); auto gLenPtr = gLen.data_ptr(); auto fGradPtr = fGrad.data_ptr(); auto gGradPtr = gGrad.data_ptr(); // resolve the acc_t type using acc_t = at::acc_type; using vec_t = uint64_t; constexpr int vectFactor = sizeof(vec_t) / sizeof(scalar_t); constexpr int vecAlignment = std::alignment_of::value; // if all input and output tensors meet the alignment requirement bool memAlign = (reinterpret_cast(gradPtr) % vecAlignment == 0) and (reinterpret_cast(fGradPtr) % vecAlignment == 0) and (reinterpret_cast(gGradPtr) % vecAlignment == 0); if (vectFactor > 1 and hiddenSize%vectFactor == 0 and memAlign){ // If vectorization helps and the alignment requirement is met, use the vectorized // kernel. For simplicity, hiddenSize needs to be a multiple vecFactor. const dim3 blocks( (hiddenSize+C10_WARP_SIZE*vectFactor-1)/(C10_WARP_SIZE*vectFactor), maxFLen+maxGLen, batchSize); if (masked){ transducer_joint_combined_vec_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } else{ transducer_joint_combined_vec_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } } else{ const dim3 blocks((hiddenSize+C10_WARP_SIZE-1)/C10_WARP_SIZE, maxFLen + maxGLen, batchSize); if (masked){ transducer_joint_combined_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } else{ transducer_joint_combined_backward <<>>( gradPtr, maskPtr, fLenPtr, gLenPtr, batchOffsetPtr, maxFLen, maxGLen, hiddenSize, packOutput, scale, fGradPtr, gGradPtr); } } })); return {fGrad, gGrad}; } ================================================ FILE: KoSimCSE/apex/contrib/csrc/transducer/transducer_loss.cpp ================================================ #include #include #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector transducer_loss_cuda_forward( torch::Tensor x, torch::Tensor label, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput); torch::Tensor transducer_loss_cuda_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput); std::vector transducer_loss_forward( torch::Tensor x, torch::Tensor label, torch::Tensor fLen, torch::Tensor yLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput ) { CHECK_INPUT(x); CHECK_INPUT(label); CHECK_INPUT(fLen); CHECK_INPUT(yLen); if (packedInput) CHECK_INPUT(batchOffset); return transducer_loss_cuda_forward( x, label, fLen, yLen, batchOffset, maxFLen, blankIdx, opt, packedInput); } torch::Tensor transducer_loss_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor fLen, torch::Tensor yLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput){ CHECK_INPUT(x); CHECK_INPUT(label); CHECK_INPUT(lossGrad); CHECK_INPUT(alpha); CHECK_INPUT(beta); CHECK_INPUT(fLen); CHECK_INPUT(yLen); if (packedInput) CHECK_INPUT(batchOffset); return transducer_loss_cuda_backward( x, lossGrad, alpha, beta, fLen, yLen, label, batchOffset, maxFLen, blankIdx, opt, fuseSoftmaxBackward, packedInput); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &transducer_loss_forward, "transducer loss forward (CUDA)"); m.def("backward", &transducer_loss_backward, "transducer loss backward (CUDA)"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/transducer/transducer_loss_kernel.cu ================================================ #include #include #include #include #include #include #include #include template __device__ __forceinline__ scalar_t logSumExp(scalar_t a, scalar_t b) { // standard log-sum-exp trick is used here to provide better numerical stability return (a >= b) ? a + std::log1p(exp(b-a)) : b + std::log1p(exp(a-b)); } // Vanilla transducer loss function (i.e. forward-backward algorithm) // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // Forward (alpha) and backward (beta) path are launched together. Input is assumed to be converted // into log scale by the preceding log_softmax layer // Diagonal wavefront advancing usually used in dynamic programming is leveraged here. // alpha and beta are of acc_t type, as they are essentially accumulators. // This loss function supports packed input where a tensor of shape [B, T, U, H] is packed into // [B_packed, H]. // Don't-care region (t > audLen) or (u > txtLen) is removed. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_forward( const scalar_t* x, const int* label, const int* audLen, const int* txtLen, const int64_t* batchOffset, int64_t dictSize, // 64-bit indexing for data tensor int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, acc_t* alpha, acc_t* beta, scalar_t* loss) { const int batch = blockIdx.y; const int tid = threadIdx.x; const auto myFLen = audLen[batch]; // Note that start of the sentence is added as 1 here const auto myGLen = txtLen[batch] + 1; const auto myLabel = label + batch * (maxGLen-1); const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; const scalar_t* myX = x + myBatchOffset * dictSize; int u = tid; if (blockIdx.x == 0){ // alpha path acc_t* myAlpha = alpha + batch*maxFLen*maxGLen; if (u == 0) myAlpha[0] = 0; __syncthreads(); for (int64_t step = 1; step < myFLen+myGLen-1; ++step){ // Move along the diagonal wavefront to leverage available parallelism for (u = tid; u < myGLen; u += blockDim.x){ int64_t t = step - u; if (t >= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(16) in [1] if (u == 0){ // alpha(t, u) = alpha(t-1, u) * null(t-1, u) myAlpha[t*maxGLen + u] = myAlpha[(t-1)*maxGLen] + myX[((t-1)*myStrideT) * dictSize + blankIdx]; } else if (t == 0){ // alpha(t, u-1) = alpha(t, u-1) * y(t, u-1) myAlpha[u] = myAlpha[u - 1] + myX[(u - 1) * dictSize + myLabel[u - 1]]; } else{ // alpha(t, u) = alpha(t-1, u) * null(t-1, u) + alpha(t, u-1) * y(t, u-1) acc_t current = myAlpha[(t-1)*maxGLen + u] + myX[((t-1)*myStrideT + u) * dictSize + blankIdx]; acc_t next = myAlpha[t*maxGLen + u - 1] + myX[(t*myStrideT + u - 1) * dictSize + myLabel[u - 1]]; myAlpha[t*maxGLen + u] = logSumExp(next, current); } } } __syncthreads(); } } else if (blockIdx.x == 1){ // beta path acc_t* myBeta = beta + batch*maxFLen*maxGLen; if (u == 0){ myBeta[(myFLen-1)*maxGLen + myGLen - 1] = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; } __syncthreads(); for (int64_t step = myFLen+myGLen - 3; step >= 0; --step){ for (u = tid; u < myGLen; u += blockDim.x){ int64_t t = step - u; if (t >= 0 and t < myFLen and u >=0 and u < myGLen){ // Eq(18) in [1] if (u == myGLen - 1){ // beta(t, u) = beta(t+1, u) * null(t, u) myBeta[t*maxGLen + u] = myBeta[(t+1)*maxGLen + u] + myX[(t*myStrideT + u) * dictSize + blankIdx]; } else if (t == myFLen - 1){ // beta(t, u) = beta(t, u+1) * y(t, u) myBeta[t*maxGLen + u] = myBeta[t*maxGLen + u + 1] + myX[(t*myStrideT + u) * dictSize + myLabel[u]]; } else{ // beta(t, u) = beta(t+1, u)*null(t, u) + beta(t, u+1)*y(t, u) acc_t current = myBeta[(t+1)*maxGLen + u] + myX[(t*myStrideT + u) * dictSize + blankIdx]; acc_t next = myBeta[t*maxGLen + u + 1] + myX[(t*myStrideT + u) * dictSize + myLabel[u]]; myBeta[t*maxGLen + u] = logSumExp(next, current); } } } __syncthreads(); } if (tid == 0) loss[batch] = -myBeta[0]; } } // transudcer loss function (i.e. forward-backward algorithm) with batch loading optimization. // Compared to the vanilla version, there are two optimizations: // 1. load x in batch through loop unrolling to reduce the latency. // 2. Use registers and shared memory to hold alpha and beta values passed from one step the next. // For simplicity, this kernel currently only supports U <= maxThread, which should be the common // case. For cases where U > maxThread, the vanilla kernel is used as a fallback option. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // Forward (alpha) and backward (beta) path are launched together. Input is assumed to be converted // into log scale by the preceding log_softmax layer // Diagonal wavefront advancing usually used in dynamic programming is leveraged here. // alpha and beta are of acc_t type, as they are essentially accumulators. // This loss function supports packed input where a tensor of shape [B, T, U, H] is packed into // [B_packed, H]. // Don't-care region (t > audLen) or (u > txtLen) is removed. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_batch_load_forward( const scalar_t* x, const int* label, const int* audLen, const int* txtLen, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, acc_t* alpha, acc_t* beta, scalar_t* loss) { const int batch = blockIdx.y; int u = threadIdx.x; const auto myFLen = audLen[batch]; const auto myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; const scalar_t* myX = x + myBatchOffset * dictSize; scalar_t next[batchLdSize], current[batchLdSize]; extern __shared__ char smem8[]; auto smem = reinterpret_cast(smem8); if (blockIdx.x == 0){ // alpha path acc_t* myAlpha = alpha + batch*maxFLen*maxGLen; // two SMEM regions for double buffering read and write data to avoid data race acc_t * const sharedAlpha[2] = {smem, smem+maxGLen}; sharedAlpha[0][u] = 0; __syncthreads(); if (u == 0) myAlpha[0] = 0; auto myAlphaLabel = (u == 0) ? 0 : label[batch*(maxGLen-1) + u - 1]; // register used to pass value to the next step for the same thread acc_t prvStepAlpha = 0; for (int64_t step = 1; step < myFLen+myGLen-1+batchLdSize; step += batchLdSize){ // Move along the diagonal wavefront to leverage available parallelism // Batch loading X through loop unrolling #pragma unroll for (int i = 0; i < batchLdSize; ++i){ if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ if (u == 0){ current[i] = myX[currentId]; } else if (t == 0){ next[i] = myX[nextId]; } else{ current[i] = myX[currentId]; next[i] = myX[nextId]; } } } } // main computing loop for (int i = 0; i < batchLdSize; ++i){ // swap the pointer for double buffering auto sharedAlphaRd = sharedAlpha[(step+i-1)%2]; auto sharedAlphaWr = sharedAlpha[(step+i)%2]; if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(16) in [1] if (u == 0) prvStepAlpha = prvStepAlpha+current[i]; else if (t == 0) prvStepAlpha = sharedAlphaRd[u-1]+next[i]; else prvStepAlpha = logSumExp(prvStepAlpha+current[i], sharedAlphaRd[u-1] + next[i]); sharedAlphaWr[u] = prvStepAlpha; myAlpha[t*maxGLen + u] = prvStepAlpha; } } __syncthreads(); } } } else if (blockIdx.x == 1){ // beta path acc_t* myBeta = beta + batch*maxFLen*maxGLen; // two SMEM regions for double buffering read and write data to avoid data race acc_t * const sharedBeta[2] = {smem, smem + maxGLen}; sharedBeta[0][u] = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; __syncthreads(); auto myBetaLabel = (u == maxGLen - 1) ? 0 : label[batch*(maxGLen-1) + u]; // register used to pass value to the next step for the same thread acc_t prvStepBeta = myX[((myFLen-1)*myStrideT + myGLen - 1) * dictSize + blankIdx]; if (u == 0) myBeta[(myFLen-1)*maxGLen + myGLen - 1] = prvStepBeta; for (int64_t step = 1; step < myFLen+myGLen-1; step += batchLdSize){ // Move along the diagonal wavefront to leverage available parallelism // Batch loading X #pragma unroll for (int i = 0; i < batchLdSize; ++i){ if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ if (u == myGLen - 1){ current[i] = myX[currentId]; } else if (t == myFLen - 1){ next[i] = myX[nextId]; } else{ current[i] = myX[currentId]; next[i] = myX[nextId]; } } } } // main computing loop for (int i = 0; i < batchLdSize; ++i){ // swap the pointer for double buffering auto sharedBetaRd = sharedBeta[(step+i-1)%2]; auto sharedBetaWr = sharedBeta[(step+i)%2]; if (step+i= 0 and t < myFLen and u >= 0 and u < myGLen){ // Eq(18) in [1] if (u == myGLen - 1) prvStepBeta = prvStepBeta+current[i]; else if (t == myFLen - 1) prvStepBeta = sharedBetaRd[u+1]+next[i]; else prvStepBeta = logSumExp(prvStepBeta+current[i], sharedBetaRd[u+1] + next[i]); sharedBetaWr[u] = prvStepBeta; myBeta[t*maxGLen + u] = prvStepBeta; } } __syncthreads(); } } if (u == 0) loss[batch] = -prvStepBeta; } } // Vanilla transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // For this backward kernel, bwd op for the preceding softmax is assumed to be handled elsewhere, // hence only Eq(20) in [1] is implemented in this kernel. // Each thread block works on [batch, t, :, :] of data. Each thread works on a specific u at a time // Since only gradients for the correct token and null token need to be updated, gradients at other // locations are initialized to 0. // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int t = blockIdx.x; const int batch = blockIdx.y; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; auto myX = x + (myBatchOffset + t*myStrideT)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT)*dictSize; auto myLabel = label + batch*(maxGLen-1); int64_t u = tid; while (t < myFLen and u < myGLen){ // Do the update // loss = -ln(Pr(y*|x)) acc_t grad = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; if (u != myGLen - 1) myXGrad[u*dictSize + myLabel[u]] = -std::exp(grad + myBeta[t*maxGLen + u + 1] + myX[u*dictSize + myLabel[u]]); if (t == myFLen - 1 and u == myGLen - 1) myXGrad[u*dictSize + blankIdx] = -std::exp(grad + myX[u*dictSize + blankIdx]); else if (t != myFLen - 1) myXGrad[u*dictSize + blankIdx] = -std::exp(grad + myBeta[(t+1)*maxGLen + u] + myX[u*dictSize + blankIdx]); u += blockDim.x; } } // Fused transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // The bwd op of the preceding softmax layer is fused in this kernel. // Each thread block works on [batch, t, u, :] of data. Each thread works on a specific h at a time // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_fused_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int u = blockIdx.x; const int t = blockIdx.y; const int batch = blockIdx.z; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; __shared__ acc_t commonFactor, myBetaTU, myBetaTUp1, myBetaTp1U, myLabelShared; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT +u)*dictSize; if (t < myFLen and u < myGLen){ auto myX = x + (myBatchOffset + t*myStrideT +u)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myLabel = label + batch*(maxGLen-1); // load and store shared variables in SMEM if (tid == 0){ commonFactor = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; myBetaTU = myBeta[t*maxGLen + u]; myBetaTUp1 = myBeta[t*maxGLen + u + 1]; myBetaTp1U = myBeta[(t+1)*maxGLen + u]; myLabelShared = myLabel[u]; } __syncthreads(); for (int64_t h = tid; h < dictSize; h += blockDim.x){ // Do the update acc_t grad = commonFactor + myX[h]; // loss = -ln(Pr(y*|x)) acc_t myGrad = std::exp(grad + myBetaTU); if (u != myGLen - 1 and h == myLabelShared){ myGrad -= std::exp(grad + myBetaTUp1); } else if (h == blankIdx){ if (t == myFLen - 1 and u == myGLen - 1) myGrad -= std::exp(grad); else if (t != myFLen - 1) myGrad -= std::exp(grad + myBetaTp1U); } myXGrad[h] = myGrad; } } else if (!packedInput){ // In non-pack mode, need to make sure the gradients for don't-care regions are zero. for (int64_t h = tid; h < dictSize; h += blockDim.x){ myXGrad[h] = 0; } } } // Vectorized version of fused transudcer loss backward operation. // Detail of this loss function can be found in: // [1] Sequence Transduction with Recurrent Neural Networks. // The bwd op of the preceding softmax layer is fused in this kernel. // Each thread block works on [batch, t, u, :] of data. Each thread works on a specific h at a time // To support the packed input, the starting offsets for each batch need to be specified with // batchOffset. template __global__ void transducer_loss_fused_vec_backward( const scalar_t* x, const scalar_t* lossGrad, const int* audLen, const int* txtLen, const int* label, const acc_t* alpha, const acc_t* beta, const int64_t* batchOffset, int64_t dictSize, int64_t blankIdx, int64_t maxFLen, int64_t maxGLen, bool packedInput, scalar_t* xGrad) { const int tid = threadIdx.x; const int u = blockIdx.x; const int t = blockIdx.y; const int batch = blockIdx.z; const int64_t myFLen = audLen[batch]; const int64_t myGLen = txtLen[batch] + 1; const int64_t myBatchOffset = packedInput ? (batch == 0 ? 0 : batchOffset[batch-1]) : batch * maxFLen * maxGLen; const int64_t myStrideT = packedInput ? myGLen : maxGLen; __shared__ acc_t commonFactor, myBetaTU, myBetaTUp1, myBetaTp1U, myLabelShared; auto myXGrad = xGrad + (myBatchOffset + t*myStrideT +u)*dictSize; auto myX = x + (myBatchOffset + t*myStrideT +u)*dictSize; auto myAlpha = alpha + batch*maxFLen*maxGLen; auto myBeta = beta + batch*maxFLen*maxGLen; auto myLabel = label + batch*(maxGLen-1); // Variabels for vectorization scalar_t myXBuffer[V], myXGradBuffer[V]; auto myXVec = reinterpret_cast(myX); auto myXGradVec = reinterpret_cast(myXGrad); auto myXBufferVec = reinterpret_cast(myXBuffer); auto myXGradBufferVec = reinterpret_cast(myXGradBuffer); if (t < myFLen and u < myGLen){ // load and store shared variables in SMEM if (tid == 0){ commonFactor = std::log(lossGrad[batch]) + myAlpha[t*maxGLen + u] - myBeta[0]; myBetaTU = myBeta[t*maxGLen + u]; if (t != myFLen - 1) myBetaTp1U = myBeta[(t+1)*maxGLen + u]; if (u != myGLen - 1){ myBetaTUp1 = myBeta[t*maxGLen + u + 1]; myLabelShared = myLabel[u]; } } __syncthreads(); #pragma unroll for (int64_t h0 = tid*V; h0 < dictSize; h0 += blockDim.x*V){ // Load myX in a vector form *myXBufferVec = myXVec[h0/V]; // Do the update for a vector of input #pragma unroll for (int i = 0; i < V; ++i){ auto h = h0 + i; acc_t grad = commonFactor + myXBuffer[i]; // loss = -ln(Pr(y*|x)) acc_t myGrad = std::exp(grad + myBetaTU); if (u != myGLen - 1 and h == myLabelShared){ myGrad -= std::exp(grad + myBetaTUp1); } else if (h == blankIdx){ if (t == myFLen - 1 and u == myGLen - 1) myGrad -= std::exp(grad); else if (t != myFLen - 1) myGrad -= std::exp(grad + myBetaTp1U); } myXGradBuffer[i] = myGrad; } // Store myXGrad in a vector form myXGradVec[h0/V] = *myXGradBufferVec; } } else if (!packedInput){ // In non-pack mode, need to make sure the gradients for don't-care regions are zero. for (int64_t h0 = tid*V; h0 < dictSize; h0 += blockDim.x*V){ myXGradVec[h0/V] = 0; } } } std::vector transducer_loss_cuda_forward( torch::Tensor x, torch::Tensor label, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool packedInput){ auto scalarType = x.scalar_type(); auto tensorOpt = x.options(); const int batchSize = label.size(0); const int maxGLen = label.size(1) + 1; const int dictSize = x.size(-1); TORCH_CHECK(blankIdx >= 0 and blankIdx < dictSize, "Expected blank index to be in the range of 0 to ", dictSize-1, ", but got ", blankIdx); TORCH_CHECK(opt == -1 or opt == 0 or opt == 1, "Got an invalid optimization level ", opt); // The data type of alpha and beta will be resolved at dispatch time, // hence defined here and assigned later torch::Tensor alpha; torch::Tensor beta; torch::Tensor loss = torch::empty({batchSize}, tensorOpt); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const auto maxThreadPerBlock = deviceProperties->maxThreadsPerBlock; const auto maxSmemPerBlock = deviceProperties->sharedMemPerBlock; const auto batchOffsetPtr = packedInput ? batchOffset.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); AT_DISPATCH_FLOATING_TYPES_AND_HALF(scalarType, "transducer_loss_cuda_forward", ([&] { // resolve accumulation type using acc_t = at::acc_type; auto accType = c10::CppTypeToScalarType::value; auto accTensorOpt = tensorOpt.dtype(accType); alpha = torch::empty({batchSize, maxFLen, maxGLen}, accTensorOpt); beta = torch::empty({batchSize, maxFLen, maxGLen}, accTensorOpt); // decide what kernel to launch based on the problem size // if the required SMEM size or number threads exceeds the limit, fall back to the vanilla // kernel. const auto smemSize = 2*maxGLen*sizeof(acc_t); const auto optFallBack = (maxGLen > maxThreadPerBlock or smemSize > maxSmemPerBlock) ? 0 : (opt == -1) ? 1 : opt; const int threads = std::min(maxThreadPerBlock, maxGLen); const dim3 blocks(2, batchSize, 1); if (optFallBack == 0) transducer_loss_forward<<>>( x.data_ptr(), label.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, alpha.data_ptr(), beta.data_ptr(), loss.data_ptr()); else if (optFallBack == 1) transducer_loss_batch_load_forward <<>>( x.data_ptr(), label.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, alpha.data_ptr(), beta.data_ptr(), loss.data_ptr()); })); THCudaCheck(cudaGetLastError()); return {alpha, beta, loss}; } torch::Tensor transducer_loss_cuda_backward( torch::Tensor x, torch::Tensor lossGrad, torch::Tensor alpha, torch::Tensor beta, torch::Tensor audLen, torch::Tensor txtLen, torch::Tensor label, torch::Tensor batchOffset, int maxFLen, int blankIdx, int opt, bool fuseSoftmaxBackward, bool packedInput){ auto dtype = x.scalar_type(); torch::Tensor xGrad; const int batchSize = label.size(0); const int maxGLen = label.size(1) + 1; const int dictSize = x.size(-1); const auto deviceProperties = at::cuda::getCurrentDeviceProperties(); const int maxThreadPerBlock = deviceProperties->maxThreadsPerBlock; const int warpSize = deviceProperties->warpSize; const auto batchOffsetPtr = packedInput ? batchOffset.data_ptr() : nullptr; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); if (fuseSoftmaxBackward){ // alloc empty tensors for performance, hence need to ensure zeros are writtern to // don't-care region in the kernel. xGrad = torch::empty_like(x); // Would like each thread to work on 4 hidden units const int workPerThread = 4; // Don't want to have more than 128 threads per thread block const int maxThreadPerElmt = std::min(128, maxThreadPerBlock); const int threads = std::min(maxThreadPerElmt, std::max(warpSize, (dictSize+workPerThread-1)/workPerThread)); const dim3 blocks(maxGLen, maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_loss_cuda_backward", ([&] { using vec_t = uint64_t; using acc_t = at::acc_type; constexpr int vectFactor = sizeof(vec_t) / sizeof(scalar_t); constexpr int vecAlignment = std::alignment_of::value; // if all input and output tensors meet the alignment requirement bool memAlign = reinterpret_cast(x.data_ptr()) % vecAlignment == 0 and reinterpret_cast(xGrad.data_ptr()) % vecAlignment == 0; if (vectFactor > 1 and dictSize%vectFactor == 0 and memAlign){ transducer_loss_fused_vec_backward <<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); } else{ transducer_loss_fused_backward<<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); } })); } else{ // for non-fused kernel, the gradients need to be writtern are very sparse, hence initialize // the tensor with all zeros. xGrad = torch::zeros_like(x); // don't launch more threads than needed. const int threads = std::min(maxThreadPerBlock, maxGLen); const dim3 blocks(maxFLen, batchSize); AT_DISPATCH_FLOATING_TYPES_AND_HALF(dtype, "transducer_loss_cuda_backward", ([&] { using acc_t = at::acc_type; transducer_loss_backward<<>>( x.data_ptr(), lossGrad.data_ptr(), audLen.data_ptr(), txtLen.data_ptr(), label.data_ptr(), alpha.data_ptr(), beta.data_ptr(), batchOffsetPtr, dictSize, blankIdx, maxFLen, maxGLen, packedInput, xGrad.data_ptr()); })); } THCudaCheck(cudaGetLastError()); return xGrad; } ================================================ FILE: KoSimCSE/apex/contrib/csrc/xentropy/interface.cpp ================================================ #include // CUDA forward declarations std::vector softmax_xentropy_cuda( const at::Tensor &input, const at::Tensor &labels, const float smoothing, const bool half_to_float); at::Tensor softmax_xentropy_backward_cuda( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing); // C++ interface #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) std::vector softmax_xentropy_forward( const at::Tensor &input, const at::Tensor &labels, const float smoothing, const bool half_to_float) { CHECK_CUDA(input); CHECK_INPUT(labels); return softmax_xentropy_cuda(input, labels, smoothing, half_to_float); } at::Tensor softmax_xentropy_backward( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing) { CHECK_CUDA(grad_loss); CHECK_CUDA(logits); CHECK_INPUT(max_log_sum_exp); CHECK_INPUT(labels); return softmax_xentropy_backward_cuda(grad_loss, logits, max_log_sum_exp, labels, smoothing); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("forward", &softmax_xentropy_forward, "Softmax cross entropy loss with label smoothing forward (CUDA)"); m.def("backward", &softmax_xentropy_backward, "Softmax cross entropy loss with label smoothing backward (CUDA)"); } ================================================ FILE: KoSimCSE/apex/contrib/csrc/xentropy/xentropy_kernel.cu ================================================ /** * From PyTorch: * * Copyright (c) 2016- Facebook, Inc (Adam Paszke) * Copyright (c) 2014- Facebook, Inc (Soumith Chintala) * Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) * Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) * Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) * Copyright (c) 2011-2013 NYU (Clement Farabet) * Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) * Copyright (c) 2006 Idiap Research Institute (Samy Bengio) * Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) * * From Caffe2: * * Copyright (c) 2016-present, Facebook Inc. All rights reserved. * * All contributions by Facebook: * Copyright (c) 2016 Facebook Inc. * * All contributions by Google: * Copyright (c) 2015 Google Inc. * All rights reserved. * * All contributions by Yangqing Jia: * Copyright (c) 2015 Yangqing Jia * All rights reserved. * * All contributions from Caffe: * Copyright(c) 2013, 2014, 2015, the respective contributors * All rights reserved. * * All other contributions: * Copyright(c) 2015, 2016 the respective contributors * All rights reserved. * * Caffe2 uses a copyright model similar to Caffe: each contributor holds * copyright over their contributions to Caffe2. The project versioning records * all such contribution and copyright details. If a contributor wants to further * mark their specific copyright on a particular contribution, they should * indicate their copyright solely in the commit message of the change when it is * committed. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America * and IDIAP Research Institute nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include "type_shim.h" #include "compat.h" #define ALIGN_BYTES 16 using Tensor = at::Tensor; using TensorList = at::TensorList; using ScalarType = at::ScalarType; using at::acc_type; template struct LogSoftMaxForwardEpilogue { __device__ __forceinline__ LogSoftMaxForwardEpilogue(AccumT max_input, AccumT sum) : logsum(max_input + std::log(sum)) {} __device__ __forceinline__ LogSoftMaxForwardEpilogue(AccumT max_log_sum_exp) : logsum(max_log_sum_exp) {} __device__ __forceinline__ OutT operator()(T input) const { return static_cast(input - logsum); } const AccumT logsum; }; template struct LogSoftMaxBackwardEpilogue { __device__ __forceinline__ LogSoftMaxBackwardEpilogue(AccumT sum) : sum(sum) {} __device__ __forceinline__ T operator()(OutT gradOutput, OutT output) const { return static_cast(gradOutput - std::exp(static_cast(output)) * sum); } const AccumT sum; }; const int max_threads = 1024; inline dim3 SoftMax_getBlockSize(int ILP, uint64_t dim_size) { uint64_t block_size = 1; uint64_t max_block_size = std::min(dim_size / ILP, static_cast(max_threads)); while (block_size < (max_block_size/2)) block_size *= 2; // Launch at least a single warp - the kernel assumes that. block_size = std::max(block_size, static_cast(32)); return dim3(block_size); } template struct Add { __device__ __forceinline__ T operator()(T a, T b) const { return a + b; } }; template struct Max { __device__ __forceinline__ T operator()(T a, T b) const { return a < b ? b : a; } }; //////////////////////////////////////////////////////////////////////////////// // Regular kernel (fast when dim_size is large; requires inner_size == 1) //////////////////////////////////////////////////////////////////////////////// template struct MaxFloat { __device__ __forceinline__ AccumT operator()(AccumT max, T v) const { return ::max(max, (AccumT)v); } }; template struct AddFloat { __device__ __forceinline__ AccumT operator()(AccumT sum, T v) const { return sum + v; } }; template struct SumExpFloat { __device__ __forceinline__ SumExpFloat(AccumT v) : max_k(v) {} __device__ __forceinline__ AccumT operator()(AccumT sum, T v) const { return sum + std::exp(v - max_k); } const AccumT max_k; }; template class Reduction, typename AccumT> __device__ __forceinline__ AccumT blockReduce(AccumT* smem, AccumT val, const Reduction& r, AccumT defaultVal) { // To avoid RaW races from chaining blockReduce calls together, we need a sync here __syncthreads(); smem[threadIdx.x] = val; __syncthreads(); AccumT warpVal = defaultVal; // First warp will perform per-warp reductions for the remaining warps uint32_t mask = (((uint64_t)1) << (blockDim.x / 32)) - 1; if (threadIdx.x < 32) { int lane = threadIdx.x % 32; if (lane < blockDim.x / 32) { #pragma unroll for (int i = 0; i < 32; ++i) { warpVal = r(warpVal, smem[lane * 32 + i]); } __syncwarp(mask); smem[lane] = warpVal; } } __syncthreads(); // First thread will perform a reduction of the above per-warp reductions AccumT blockVal = defaultVal; if (threadIdx.x == 0) { for (int i = 0; i < blockDim.x / 32; ++i) { blockVal = r(blockVal, smem[i]); } smem[0] = blockVal; } // Sync and broadcast __syncthreads(); return smem[0]; } template class Reduction1, template class Reduction2, typename AccumT> __device__ __forceinline__ void blockReduce(AccumT* smem, AccumT* reducVal1, AccumT val1, const Reduction1& r1, AccumT defaultVal1, AccumT* reducVal2, AccumT val2, const Reduction2& r2, AccumT defaultVal2) { // To avoid RaW races from chaining blockReduce calls together, we need a sync here __syncthreads(); smem[threadIdx.x] = val1; smem[blockDim.x + threadIdx.x] = val2; __syncthreads(); AccumT warpVal1 = defaultVal1; AccumT warpVal2 = defaultVal2; // First warp will perform per-warp reductions for the remaining warps uint32_t mask = (((uint64_t)1) << (blockDim.x / 32)) - 1; if (threadIdx.x < 32) { int lane = threadIdx.x % 32; if (lane < blockDim.x / 32) { #pragma unroll for (int i = 0; i < 32; ++i) { warpVal1 = r1(warpVal1, smem[lane * 32 + i]); warpVal2 = r2(warpVal2, smem[lane * 32 + i + blockDim.x]); } __syncwarp(mask); smem[lane] = warpVal1; smem[lane + blockDim.x] = warpVal2; } } __syncthreads(); // First thread will perform a reduction of the above per-warp reductions AccumT blockVal1 = defaultVal1; AccumT blockVal2 = defaultVal2; if (threadIdx.x == 0) { for (int i = 0; i < blockDim.x / 32; ++i) { blockVal1 = r1(blockVal1, smem[i]); blockVal2 = r2(blockVal2, smem[i + blockDim.x]); } smem[0] = blockVal1; smem[blockDim.x] = blockVal2; } // Sync and broadcast __syncthreads(); *reducVal1 = smem[0]; *reducVal2 = smem[blockDim.x]; __syncthreads(); } template class Reduction, int ILP, typename T, typename AccumT> __device__ __forceinline__ AccumT ilpReduce(int shift, T* data, int size, const Reduction& r, AccumT defaultVal) { typedef typename std::aligned_storage::type LoadT; AccumT threadVal = defaultVal; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ data -= shift; size += shift; if(threadIdx.x >= shift){ threadVal = r(threadVal, data[offset]); } size -= blockDim.x; data += blockDim.x; } int last = size % (ILP * blockDim.x); T v[ILP]; LoadT* value = reinterpret_cast(&v); for (; offset * ILP < (size - last); offset += blockDim.x) { *value = reinterpret_cast(data)[offset]; for (int j = 0; j < ILP; ++j) { threadVal = r(threadVal, v[j]); } } offset = size - last + threadIdx.x; // Epilogue for (; offset < size; offset += blockDim.x) threadVal = r(threadVal, data[offset]); return threadVal; } template class Reduction1, template class Reduction2, int ILP, typename T, typename AccumT> __device__ __forceinline__ void ilpReduce(int shift, T* data, int size, AccumT* reducVal1, const Reduction1& r1, AccumT defaultVal1, AccumT* reducVal2, const Reduction2& r2, AccumT defaultVal2) { typedef typename std::aligned_storage::type LoadT; AccumT threadVal1 = defaultVal1; AccumT threadVal2 = defaultVal2; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ data -= shift; size += shift; if(threadIdx.x >= shift){ threadVal1 = r1(threadVal1, data[offset]); threadVal2 = r2(threadVal2, data[offset]); } size -= blockDim.x; data += blockDim.x; } int last = size % (ILP * blockDim.x); T v[ILP]; LoadT* value = reinterpret_cast(&v); for (; offset * ILP < (size - last); offset += blockDim.x) { *value = reinterpret_cast(data)[offset]; for (int j = 0; j < ILP; ++j) { threadVal1 = r1(threadVal1, v[j]); threadVal2 = r2(threadVal2, v[j]); } } offset = size - last + threadIdx.x; // Epilogue for (; offset < size; offset += blockDim.x) { threadVal1 = r1(threadVal1, data[offset]); threadVal2 = r2(threadVal2, data[offset]); } *reducVal1 = threadVal1; *reducVal2 = threadVal2; } template class Epilogue> __global__ void cunn_SoftMaxXEntropyForward( accscalar_t *losses, outscalar_t *max_log_sum_exp, scalar_t *input, int64_t *labels, int64_t classes, const float smoothing) { extern __shared__ unsigned char smem[]; auto sdata = reinterpret_cast(smem); // forward pointers to batch[blockIdx.x] // each block handles a sample in the mini-batch input += blockIdx.x * classes; //output += blockIdx.x * classes; const int shift = ((uint64_t)input) % ALIGN_BYTES / sizeof(scalar_t); int64_t label = labels[blockIdx.x]; // find the max and sum accscalar_t threadMax, threadSum, max_k, sum_k; ilpReduce( shift, input, classes, &threadMax, MaxFloat(), -at::numeric_limits::max(), &threadSum, AddFloat(), static_cast(0)); blockReduce( sdata, &max_k, threadMax, Max(), -at::numeric_limits::max(), &sum_k, threadSum, Add(), static_cast(0)); accscalar_t threadExp = ilpReduce(shift, input, classes, SumExpFloat(max_k), static_cast(0)); accscalar_t sumAll = blockReduce( sdata, threadExp, Add(), static_cast(0)); Epilogue epilogue(max_k, sumAll); // calculate per element loss with label smoothing // reserve max + log_sum_exp for bprop if (threadIdx.x == 0) { accscalar_t log_prob = epilogue(static_cast(input[label])); losses[blockIdx.x] = (max_k + std::log(sumAll) - sum_k / classes) \ * smoothing - log_prob * (1 - smoothing); max_log_sum_exp[blockIdx.x] = max_k + std::log(sumAll); } } template __device__ __forceinline__ void apply(scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { accscalar_t smooth_positives = 1.0 - smoothing; accscalar_t smooth_negatives = smoothing / classes; accscalar_t tmpGradOutput = gradOutput[blockIdx.x]; int64_t label = labels[blockIdx.x]; accscalar_t coeff = max_log_sum_exp[blockIdx.x]; int offset = threadIdx.x; int last = classes % (ILP * blockDim.x); for (; offset < classes - last; offset += blockDim.x * ILP) { accscalar_t tmpLogits[ILP]; #pragma unroll for (int j = 0; j < ILP; ++j) { tmpLogits[j] = static_cast(logits[offset + j * blockDim.x]); } #pragma unroll for (int j = 0; j < ILP; ++j) gradInput[offset + j * blockDim.x] = tmpGradOutput * ( std::exp(tmpLogits[j] - coeff) - static_cast( (offset + j * blockDim.x == label) ? 1 : 0) * smooth_positives - smooth_negatives); } for (; offset < classes; offset += blockDim.x) gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast((offset == label) ? 1 : 0) * smooth_positives - smooth_negatives); } template __device__ __forceinline__ void aligned_apply(int shift, scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { accscalar_t smooth_positives = 1.0 - smoothing; accscalar_t smooth_negatives = smoothing / classes; accscalar_t tmpGradOutput = gradOutput[blockIdx.x]; int64_t label = labels[blockIdx.x]; accscalar_t coeff = max_log_sum_exp[blockIdx.x]; int offset = threadIdx.x; // shift and do 1 if(shift > 0){ logits -= shift; gradInput -= shift; classes += shift; if(threadIdx.x >= shift){ gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast(((offset - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } classes -= blockDim.x; gradInput += blockDim.x; logits += blockDim.x; shift -= blockDim.x; } int last = classes % (ILP * blockDim.x); typedef typename std::aligned_storage::type LoadT; // input scalar_t v[ILP]; LoadT* value = reinterpret_cast(&v); // output scalar_t r[ILP]; LoadT* result = reinterpret_cast(&r); for (; offset * ILP < (classes - last); offset += blockDim.x) { *value = reinterpret_cast(logits)[offset]; #pragma unroll for (int j = 0; j < ILP; ++j) { r[j] = tmpGradOutput * (std::exp( static_cast(v[j]) - coeff) - static_cast(((ILP * offset + j - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } reinterpret_cast(gradInput)[offset] = *result; } offset = classes - last + threadIdx.x; for (; offset < classes; offset += blockDim.x) gradInput[offset] = tmpGradOutput * (std::exp( static_cast(logits[offset]) - coeff) - static_cast(((offset - shift) == label) ? 1 : 0) * smooth_positives - smooth_negatives); } template class Epilogue> __global__ void cunn_SoftMaxXEntropyBackward( scalar_t *gradInput, scalar_t *logits, outscalar_t *max_log_sum_exp, outscalar_t *gradOutput, int64_t *labels, const float smoothing, int classes) { gradInput += blockIdx.x * classes; logits += blockIdx.x * classes; // Do vectorized load/store when input/output have same alignment const int shift = ((uint64_t)logits) % ALIGN_BYTES / sizeof(scalar_t); const int shift_ = ((uint64_t)gradInput) % ALIGN_BYTES / sizeof(scalar_t); if (shift == shift_){ aligned_apply(shift, gradInput, logits, max_log_sum_exp, gradOutput, labels, smoothing, classes); } else { apply(gradInput, logits, max_log_sum_exp, gradOutput, labels, smoothing, classes); } } template class Epilogue> std::vector host_softmax_xentropy( const Tensor & input_, const Tensor & labels_, const float smoothing, const bool half_to_float){ if (half_to_float) AT_ASSERTM(input_.type().scalarType() == ScalarType::Half,"conversion is supported for Half type only"); AT_ASSERTM(labels_.type().scalarType() == ScalarType::Long,"Label type should be CUDA Long"); auto input = input_.contiguous(); Tensor max_log_sum_exp = at::empty_like(labels_, half_to_float ? input.options().dtype(ScalarType::Float) : input.options()); Tensor losses = at::empty_like(labels_, input_.options().dtype(ScalarType::Float)); static_assert(std::is_same, float>::value || std::is_same, double>::value, "accscalar_t for half should be float or double"); AT_ASSERTM(input.dim() == 2, "Currently only 2 dim input supported"); AT_ASSERTM(labels_.dim() == 1, "Labels should be 1 dimensional"); AT_ASSERTM(input.size(0) == labels_.size(0), "Input and label should have same number of examples"); AT_ASSERTM(input.numel() > 0, "Number of classes in input should not be 0"); const int64_t dim = 1; int64_t outer_size = 1; int64_t dim_size = input.size(dim); int64_t inner_size = 1; cudaStream_t stream = at::cuda::getCurrentCUDAStream(); for (int64_t i = 0; i < dim; ++i) outer_size *= input.size(i); for (int64_t i = dim + 1; i < input.dim(); ++i) inner_size *= input.size(i); // This kernel spawns a block per each element in the batch. // XXX: it assumes that inner_size == 1 TORCH_CHECK(inner_size == 1, "Currently only inner size 1 supported"); dim3 grid(outer_size); using namespace at; DISPATCH_FLOAT_AND_HALF(input.scalar_type(), 0, "host_softmax_xentropy", using accscalar_t = at::acc_type; const int ILP = sizeof(float4)/sizeof(scalar_t_0); dim3 block = SoftMax_getBlockSize(ILP, dim_size); if (!half_to_float) { cunn_SoftMaxXEntropyForward <<>>( losses.DATA_PTR(), max_log_sum_exp.DATA_PTR(), input.DATA_PTR(), labels_.DATA_PTR(), dim_size, smoothing ); } else { cunn_SoftMaxXEntropyForward <<>>( losses.DATA_PTR(), max_log_sum_exp.DATA_PTR(), input.DATA_PTR(), labels_.DATA_PTR(), dim_size, smoothing ); } ); THCudaCheck(cudaGetLastError()); std::vector ret = {losses, max_log_sum_exp}; return ret; } template class Epilogue> Tensor host_softmax_xentropy_backward( const at::Tensor &grad_loss, const at::Tensor &logits_, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing, bool half_to_float) { const int64_t dim = 1; Tensor gI = at::empty_like(logits_); if (grad_loss.numel() == 0) { return gI; } auto grad = grad_loss.contiguous(); auto logits = logits_.contiguous(); static_assert(std::is_same, float>::value || std::is_same, double>::value, "accscalar_t for half should be float or double"); if (grad.dim() == 0) grad = grad.view(1); AT_ASSERTM(logits_.dim() == 2, "Currently only 2 dim input supported"); AT_ASSERTM(labels.dim() == 1, "Labels should be 1 dimensional"); AT_ASSERTM(logits_.numel() > 0, "Number of classes in input should not be 0"); AT_ASSERTM(logits_.size(0) == labels.size(0), "Input and label should have same number of examples"); AT_ASSERTM(labels.size(0) == grad.size(0), "Label and loss should have same number of examples"); int64_t outer_size = 1; int64_t dim_size = logits.size(dim); int64_t inner_size = 1; for (int64_t i = 0; i < dim; ++i) outer_size *= logits.size(i); for (int64_t i = dim + 1; i < logits.dim(); ++i) inner_size *= logits.size(i); // See descriptions of kernels above. cudaStream_t stream = at::cuda::getCurrentCUDAStream(); TORCH_CHECK(inner_size == 1, "Currently only inner size 1 supported"); dim3 grid(outer_size); DISPATCH_FLOAT_AND_HALF(gI.scalar_type(), 0, "host_softmax_xentropy_backward", using accscalar_t = acc_type; const int ILP = sizeof(float4)/sizeof(scalar_t_0); dim3 block = SoftMax_getBlockSize(ILP, dim_size); if (!half_to_float) { cunn_SoftMaxXEntropyBackward <<>>( gI.DATA_PTR(), logits.DATA_PTR(), max_log_sum_exp.DATA_PTR(), grad.DATA_PTR(), labels.DATA_PTR(), smoothing, dim_size ); } else { cunn_SoftMaxXEntropyBackward <<>>( gI.DATA_PTR(), logits.DATA_PTR(), max_log_sum_exp.DATA_PTR(), grad.DATA_PTR(), labels.DATA_PTR(), smoothing, dim_size ); } ); THCudaCheck(cudaGetLastError()); return gI; } std::vector softmax_xentropy_cuda(const Tensor &input, const Tensor &labels, const float smoothing, const bool half_to_float){ return host_softmax_xentropy(input, labels, smoothing, half_to_float); } at::Tensor softmax_xentropy_backward_cuda( const at::Tensor &grad_loss, const at::Tensor &logits, const at::Tensor &max_log_sum_exp, const at::Tensor &labels, const float smoothing) { bool half_to_float = grad_loss.type().scalarType() != logits.type().scalarType(); if (half_to_float) { AT_ASSERTM((grad_loss.type().scalarType() == ScalarType::Float && logits.type().scalarType() == ScalarType::Half), "expected input and grad types to match, or input to be at::Half and grad to be at::Float"); } return host_softmax_xentropy_backward(grad_loss, logits, max_log_sum_exp, labels, smoothing, half_to_float); } ================================================ FILE: KoSimCSE/apex/contrib/examples/multihead_attn/func_test_multihead_attn.py ================================================ import torch import torch.nn.functional as F import argparse from apex.contrib.multihead_attn import SelfMultiheadAttn from apex.contrib.multihead_attn import EncdecMultiheadAttn parser = argparse.ArgumentParser(description='Multihead Attention Standalone Test') parser.add_argument('--seq-length', default=64, type=int, help='Sequence Length of Input') parser.add_argument('--num-seqs-start', default=5, type=int, help='Start Range of Number of Sequences') parser.add_argument('--num-seqs-stop', default=80, type=int, help='Stop Range of Number of Sequences') parser.add_argument('--num-seqs-inc', default=5, type=int, help='Range Increment of Number of Sequences') parser.add_argument('--trials', default=20, type=int, help='Number of Trials to Execute') parser.add_argument('--warmup-trials', default=5, type=int, help='Warmup Trials to discard') parser.add_argument('--layers', default=18, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--seed-start', default=1, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--seed-end', default=100, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--hidden-dim', default=1024, type=int, help='Multihead Attention hidden dimension') parser.add_argument('--heads', default=16, type=int, help='Number of Multihead Attention heads') parser.add_argument('--encdec-attn', action='store_true', help='Use Encoder-Decoder Attention instead of Self Attention.') parser.add_argument('--norm-add', action='store_true', help='Include Layer Norm and Dropout-Add in Multihead Attention block.') parser.add_argument('--ref', action='store_true', help='Reference implementation in python pytorch.') parser.add_argument('--native', action='store_true', help='torch.nn.MultitheadAttention Version.') parser.add_argument('--fwd', action='store_true', help='Only execute Fwd Pass.') parser.add_argument('--eval', action='store_true', help='Inference only, no backward pass.') args = parser.parse_args() assert args.seq_length % 64 == 0, "Sequence Length should be a multiple of 64!" if not torch.cuda.is_available(): raise NotImplementedError('Running on CPU is not supported') torch.cuda.set_device(0) dropout_prob = 0.1 for seed in range(args.seed_start, args.seed_end+1) : torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) ref_layer = None if args.encdec_attn : ref_layer = EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='default') else : ref_layer = SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='default') ref_layer.cuda() ref_layer.half() ref_layer.reset_parameters() ref_inputs = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) ref_inputs_kv = None if args.encdec_attn : ref_inputs_kv = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) ref_grads = torch.randn_like(ref_inputs) ref_outputs,_ = ref_layer.forward(ref_inputs, ref_inputs_kv, ref_inputs_kv, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=(not args.eval)) ref_outputs.backward(ref_grads) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) tst_layer = None if args.encdec_attn : tst_layer = EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='fast') else: tst_layer = SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=dropout_prob, bias=False, include_norm_add=args.norm_add, impl='fast') tst_layer.cuda() tst_layer.half() tst_layer.reset_parameters() tst_inputs = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) tst_inputs_kv = None if args.encdec_attn : tst_inputs_kv = torch.randn(args.seq_length, args.num_seqs_start, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) assert torch.equal(ref_inputs,tst_inputs), "ERROR: Inputs are different!" tst_grads = torch.randn_like(tst_inputs) tst_outputs,_ = tst_layer.forward(tst_inputs, tst_inputs_kv, tst_inputs_kv, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=(not args.eval)) tst_outputs.backward(tst_grads) fwd_close = torch.equal(ref_outputs, tst_outputs) bwd_close = torch.equal(ref_inputs.grad, tst_inputs.grad) diff_fwd = ref_outputs - tst_outputs diff_cnt_fwd = diff_fwd.ne(0.0).sum() diff_accum_fwd = diff_fwd.abs().sum() diff_bwd = ref_inputs.grad - tst_inputs.grad diff_cnt_bwd = diff_bwd.ne(0.0).sum() diff_accum_bwd = diff_bwd.abs().sum() print(">>> Seed: ", seed, fwd_close, diff_cnt_fwd.item(), diff_accum_fwd.item(), bwd_close, diff_cnt_bwd.item(), diff_accum_bwd.item()) ================================================ FILE: KoSimCSE/apex/contrib/examples/multihead_attn/perf_test_multihead_attn.py ================================================ import torch import torch.nn.functional as F import argparse from apex.contrib.multihead_attn import SelfMultiheadAttn from apex.contrib.multihead_attn import EncdecMultiheadAttn parser = argparse.ArgumentParser(description='Multihead Attention Standalone Test') parser.add_argument('--seq-length', default=64, type=int, help='Sequence Length of Input') parser.add_argument('--num-seqs-start', default=10, type=int, help='Start Range of Number of Sequences') parser.add_argument('--num-seqs-stop', default=120, type=int, help='Stop Range of Number of Sequences') parser.add_argument('--num-seqs-inc', default=5, type=int, help='Range Increment of Number of Sequences') parser.add_argument('--trials', default=20, type=int, help='Number of Trials to Execute') parser.add_argument('--warmup-trials', default=5, type=int, help='Warmup Trials to discard') parser.add_argument('--layers', default=18, type=int, help='Attention Layers to Execute to Gain CPU/GPU Time Overlap') parser.add_argument('--hidden-dim', default=1024, type=int, help='Multihead Attention hidden dimension') parser.add_argument('--heads', default=16, type=int, help='Number of Multihead Attention heads') parser.add_argument('--encdec-attn', action='store_true', help='Use Encoder-Decoder Attention instead of Self Attention.') parser.add_argument('--norm-add', action='store_true', help='Include Layer Norm and Dropout-Add in Multihead Attention block.') parser.add_argument('--ref', action='store_true', help='Reference implementation in python pytorch.') parser.add_argument('--native', action='store_true', help='torch.nn.MultitheadAttention Version.') parser.add_argument('--fwd', action='store_true', help='Only execute Fwd Pass.') parser.add_argument('--biases', action='store_true', help='Execute multihead attention with Linear Biases.') args = parser.parse_args() if not torch.cuda.is_available(): raise NotImplementedError('Running on CPU is not supported') torch.cuda.set_device(0) torch.manual_seed(111) if torch.cuda.is_available(): torch.cuda.manual_seed_all(111) attn_layers = [] for idx in range(0, args.layers) : if args.encdec_attn : if args.ref : attn_layers.append(EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=False, impl='default')) else : attn_layers.append(EncdecMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='fast')) else : if args.native : attn_layers.append(torch.nn.MultiheadAttention(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases)) elif args.ref : attn_layers.append(SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='default')) else : attn_layers.append(SelfMultiheadAttn(args.hidden_dim, args.heads, dropout=0.1, bias=args.biases, include_norm_add=args.norm_add, impl='fast')) attn_layers[idx].cuda() attn_layers[idx].half() if not args.native : attn_layers[idx].reset_parameters() start_evt_fwd = [] start_evt_bwd = [] stop_evt_bwd = [] for recorded_trial in range(0, args.trials) : start_evt_fwd.append(torch.cuda.Event(enable_timing=True)) start_evt_bwd.append(torch.cuda.Event(enable_timing=True)) stop_evt_bwd.append(torch.cuda.Event(enable_timing=True)) for sequences in range(args.num_seqs_start, args.num_seqs_stop + args.num_seqs_inc, args.num_seqs_inc) : inputs = torch.randn(args.seq_length, sequences, args.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) grads = torch.randn_like(inputs) for trial in range(0, args.trials + args.warmup_trials) : layer_inputs = inputs evt_idx = trial - args.warmup_trials if evt_idx >= 0 : start_evt_fwd[evt_idx].record() for lyr_idx in range(0, args.layers) : if args.native : outputs,_ = attn_layers[lyr_idx].forward(layer_inputs, layer_inputs, layer_inputs, key_padding_mask=None, need_weights=False, attn_mask=None) else : outputs,_ = attn_layers[lyr_idx].forward(layer_inputs, layer_inputs, layer_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) layer_inputs = outputs if evt_idx >= 0 : start_evt_bwd[evt_idx].record() if not args.fwd : layer_inputs.backward(grads) if evt_idx >= 0 : stop_evt_bwd[evt_idx].record() torch.cuda.synchronize() elapsed_time_fwd = 0.0 elapsed_time_bwd = 0.0 for evt_idx in range(0, args.trials) : elapsed_time_fwd += start_evt_fwd[evt_idx].elapsed_time(start_evt_bwd[evt_idx]) elapsed_time_bwd += start_evt_bwd[evt_idx].elapsed_time(stop_evt_bwd[evt_idx]) print("[ {} Attn {} ]Total Tokens: {:4d} Sequences: {:3d} Sequence Length: {:3d} Fwd Time / Layer: {:.3f} ms Bwd Time / Layer: {:.3f} ms".format( 'Encdec' if args.encdec_attn else 'Self', \ 'Norm&Add' if args.norm_add else '', \ sequences*args.seq_length, \ sequences, \ args.seq_length, \ elapsed_time_fwd / ( args.trials * args.layers ), \ elapsed_time_bwd / ( args.trials * args.layers ))) ================================================ FILE: KoSimCSE/apex/contrib/fmha/__init__.py ================================================ from .fmha import FMHAFun ================================================ FILE: KoSimCSE/apex/contrib/fmha/fmha.py ================================================ ############################################################################### # Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################### import torch import torch.nn.functional as F import fmhalib as mha class FMHAFun(torch.autograd.Function): @staticmethod def forward(ctx, qkv, cu_seqlens, p_dropout, max_s, is_training): batch_size = cu_seqlens.numel() - 1 if batch_size < 4: context, S_dmask = mha.fwd_nl(qkv, cu_seqlens, p_dropout, max_s, is_training, None) else: context, S_dmask = mha.fwd(qkv, cu_seqlens, p_dropout, max_s, is_training, None) ctx.save_for_backward(qkv, S_dmask) ctx.cu_seqlens = cu_seqlens ctx.p_dropout = p_dropout ctx.max_s = max_s return context @staticmethod def backward(ctx, dout): qkv, S_dmask = ctx.saved_tensors batch_size = ctx.cu_seqlens.numel() - 1 if batch_size < 4: dqkv, dp, _ = mha.bwd_nl(dout, qkv, S_dmask, ctx.cu_seqlens, ctx.p_dropout, ctx.max_s) else: dqkv, dp = mha.bwd(dout, qkv, S_dmask, ctx.cu_seqlens, ctx.p_dropout, ctx.max_s) return dqkv, None, None, None, None, None, None class FMHA(torch.nn.Module): def __init__(self, config): super(FMHA, self).__init__() self.p_dropout = config.attention_probs_dropout_prob self.h = config.num_attention_heads self.hidden_size = config.hidden_size self.d = self.hidden_size // self.h assert self.d * self.h == self.hidden_size, "Invalid hidden size/num_heads" def forward(self, qkv, cu_seqlens, max_s, is_training=True): ctx = FMHAFun.apply(qkv.view(-1, 3, self.h, self.d), cu_seqlens, self.p_dropout, max_s, is_training) return ctx.view(-1, self.hidden_size) ================================================ FILE: KoSimCSE/apex/contrib/groupbn/__init__.py ================================================ try: import torch import bnp from .batch_norm import BatchNorm2d_NHWC del torch del bnp del batch_norm except ImportError as err: print("apex was installed without --bnp flag, contrib.groupbn is not available") ================================================ FILE: KoSimCSE/apex/contrib/groupbn/batch_norm.py ================================================ import torch import numpy as np from torch.nn.modules.batchnorm import _BatchNorm import bnp class bn_NHWC_impl(torch.autograd.Function): @staticmethod def forward(ctx, x, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, is_train, bn_group, my_data, pair_data, magic, pair_data2, pair_data3, fwd_occup, fwd_grid_x, bwd_occup, bwd_grid_x, multi_stream): if is_train: ctx.save_for_backward(x, s, b, rm, riv, mini_m, mini_riv) ctx.epsilon = epsilon ctx.momentum = mom ctx.ret_cta = ret_cta ctx.fuse_relu = fuse_relu ctx.my_data = my_data ctx.pair_data = pair_data ctx.magic = magic ctx.pair_data2 = pair_data2 ctx.pair_data3 = pair_data3 ctx.bn_group = bn_group ctx.bwd_occup = bwd_occup ctx.bwd_grid_x = bwd_grid_x ctx.multi_stream = multi_stream res = bnp.bn_fwd_nhwc(x, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, fwd_occup, fwd_grid_x, multi_stream) return res else: return bnp.bn_fwd_eval_nhwc(x, s, b, rm, riv, ret_cta, bn_group, mom, epsilon, fuse_relu) @staticmethod def backward(ctx, grad_y): x, s, b, rm, riv, mini_m, mini_riv = ctx.saved_variables epsilon = ctx.epsilon mom = ctx.momentum ret_cta = ctx.ret_cta fuse_relu = ctx.fuse_relu my_data = ctx.my_data pair_data = ctx.pair_data magic = ctx.magic pair_data2 = ctx.pair_data2 pair_data3 = ctx.pair_data3 bn_group = ctx.bn_group bwd_occup = ctx.bwd_occup bwd_grid_x = ctx.bwd_grid_x multi_stream = ctx.multi_stream dx, dscale, dbias = bnp.bn_bwd_nhwc(x, grad_y, s, b, rm, riv, mini_m, mini_riv, ret_cta, mom, epsilon, fuse_relu, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, bwd_occup, bwd_grid_x, multi_stream) return dx, dscale, dbias, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None class bn_addrelu_NHWC_impl(torch.autograd.Function): @staticmethod def forward(ctx, x, z, s, b, rm, riv, mini_m, mini_riv, grid_dim_y, ret_cta, mom, epsilon, is_train, bn_group, my_data, pair_data, magic, pair_data2, pair_data3, fwd_occup, fwd_grid_x, bwd_occup, bwd_grid_x, multi_stream): if is_train: bitmask = torch.cuda.IntTensor(((x.numel()+31)//32) * 2 * grid_dim_y) ctx.save_for_backward(x, s, b, rm, riv, mini_m, mini_riv, bitmask) ctx.epsilon = epsilon ctx.momentum = mom ctx.ret_cta = ret_cta ctx.my_data = my_data ctx.pair_data = pair_data ctx.magic = magic ctx.pair_data2 = pair_data2 ctx.pair_data3 = pair_data3 ctx.bn_group = bn_group ctx.bwd_occup = bwd_occup ctx.bwd_grid_x = bwd_grid_x ctx.multi_stream = multi_stream res = bnp.bn_addrelu_fwd_nhwc(x, z, s, b, rm, riv, mini_m, mini_riv, bitmask, ret_cta, mom, epsilon, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, fwd_occup, fwd_grid_x, multi_stream) return res else: return bnp.bn_addrelu_fwd_eval_nhwc(x, z, s, b, rm, riv, ret_cta, bn_group, mom, epsilon) @staticmethod def backward(ctx, grad_y): x, s, b, rm, riv, mini_m, mini_riv, bitmask = ctx.saved_variables epsilon = ctx.epsilon mom = ctx.momentum ret_cta = ctx.ret_cta my_data = ctx.my_data pair_data = ctx.pair_data magic = ctx.magic pair_data2 = ctx.pair_data2 pair_data3 = ctx.pair_data3 bn_group = ctx.bn_group bwd_occup = ctx.bwd_occup bwd_grid_x = ctx.bwd_grid_x multi_stream = ctx.multi_stream dx, dz, dscale, dbias = bnp.bn_addrelu_bwd_nhwc(x, grad_y, s, b, rm, riv, mini_m, mini_riv, bitmask, ret_cta, mom, epsilon, my_data, pair_data, pair_data2, pair_data3, bn_group, magic, bwd_occup, bwd_grid_x, multi_stream) return dx, dz, dscale, dbias, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None class BatchNorm2d_NHWC(_BatchNorm): # if using BatchNorm2d_NHWC simultaneously with multiple streams set multi_stream to True def __init__(self, num_features, fuse_relu=False, bn_group=1, max_cta_per_sm=2, cta_launch_margin=12, multi_stream=False): super(BatchNorm2d_NHWC, self).__init__(num_features) self.fuse_relu = fuse_relu self.multi_stream = multi_stream self.minibatch_mean = torch.cuda.FloatTensor(num_features) self.minibatch_riv = torch.cuda.FloatTensor(num_features) #defaut to distributed bn disabled self.bn_group = bn_group self.max_cta_per_sm = max_cta_per_sm #used only in training fwd and bwd self.cta_launch_margin = cta_launch_margin #used only in training fwd and bwd self.my_data = None self.pair_data = None self.pair_data2 = None self.pair_data3 = None self.local_rank = 0 self.magic = torch.IntTensor([0]) #calculate cta per sm occupancies assert(max_cta_per_sm>0) # won't be able to do much with 0 CTAs :) self.fwd_occupancy = min(bnp.bn_fwd_nhwc_occupancy(), max_cta_per_sm) self.bwd_occupancy = min(bnp.bn_bwd_nhwc_occupancy(), max_cta_per_sm) self.addrelu_fwd_occupancy = min(bnp.bn_addrelu_fwd_nhwc_occupancy(), max_cta_per_sm) self.addrelu_bwd_occupancy = min(bnp.bn_addrelu_bwd_nhwc_occupancy(), max_cta_per_sm) #calculate grid dimentions based on occupancy numbers mp_count = torch.cuda.get_device_properties(None).multi_processor_count self.fwd_grid_dim_x = max(mp_count*self.fwd_occupancy - cta_launch_margin , 1) self.bwd_grid_dim_x = max(mp_count*self.bwd_occupancy - cta_launch_margin , 1) self.addrelu_fwd_grid_dim_x = max(mp_count*self.addrelu_fwd_occupancy - cta_launch_margin , 1) self.addrelu_bwd_grid_dim_x = max(mp_count*self.addrelu_bwd_occupancy - cta_launch_margin , 1) self.grid_dim_y = (num_features + 63) // 64 # allocate scratch space used by implementation # TODO: scratch space that is not supposed to be exposed at user code. We only need one time initialization, the # same buffer could be reused in future iterations. Currently we exposed it here instead of requesting new # buffer from cache allocator to avoid unnecessary initialization at future iterations. self.ret_cta = torch.cuda.ByteTensor(8192).fill_(0) #FIXME: turn pair handles into an array if bn_group>1: local_rank = torch.distributed.get_rank() world_size = torch.distributed.get_world_size() assert(world_size >= bn_group) assert(world_size % bn_group == 0) bn_sync_steps = 1 if (bn_group==4): bn_sync_steps = 2 if (bn_group==8): bn_sync_steps = 3 self.ipc_buffer = torch.cuda.ByteTensor(bnp.get_buffer_size(bn_sync_steps)) self.my_data = bnp.get_data_ptr(self.ipc_buffer) # we are walking on very thin ice here by utilizing internal `_share_cuda_()` self.storage = self.ipc_buffer.storage() self.share_cuda = self.storage._share_cuda_() internal_cuda_mem = self.share_cuda # internal_cuda_mem[1]: ipc_mem_handle my_handle = torch.cuda.ByteTensor(np.frombuffer(internal_cuda_mem[1], dtype=np.uint8)) # internal_cuda_mem[3]: offset my_offset = torch.cuda.IntTensor([internal_cuda_mem[3]]) handles_all = torch.empty(world_size, my_handle.size(0), dtype=my_handle.dtype, device=my_handle.device) handles_l = list(handles_all.unbind(0)) torch.distributed.all_gather(handles_l, my_handle) offsets_all = torch.empty(world_size, my_offset.size(0), dtype=my_offset.dtype, device=my_offset.device) offsets_l = list(offsets_all.unbind(0)) torch.distributed.all_gather(offsets_l, my_offset) #whom do I actually care about? that would be local_rank XOR 1 self.pair_handle = handles_l[local_rank ^ 1].cpu().contiguous() pair_offset = offsets_l[local_rank ^ 1].cpu() self.pair_data = bnp.get_remote_data_ptr(self.pair_handle, pair_offset) if bn_group>2: self.pair_handle2 = handles_l[local_rank ^ 2].cpu().contiguous() pair_offset2 = offsets_l[local_rank ^ 2].cpu() self.pair_data2 = bnp.get_remote_data_ptr(self.pair_handle2, pair_offset2) if bn_group>4: self.pair_handle3 = handles_l[local_rank ^ 4].cpu().contiguous() pair_offset3 = offsets_l[local_rank ^ 4].cpu() self.pair_data3 = bnp.get_remote_data_ptr(self.pair_handle3, pair_offset3) #FIXME: get magic value into C code and eliminate from here self.magic = torch.IntTensor([2]) self.local_rank = local_rank def forward(self, x, z=None): if z is not None: assert(self.fuse_relu==True) return bn_addrelu_NHWC_impl.apply(x, z, self.weight, self.bias, self.running_mean, self.running_var, self.minibatch_mean, self.minibatch_riv, self.grid_dim_y, self.ret_cta, self.momentum, self.eps, self.training, self.bn_group, self.my_data, self.pair_data, (self.magic), self.pair_data2, self.pair_data3, self.addrelu_fwd_occupancy, self.addrelu_fwd_grid_dim_x, self.addrelu_bwd_occupancy, self.addrelu_bwd_grid_dim_x, self.multi_stream) else: return bn_NHWC_impl.apply(x, self.weight, self.bias, self.running_mean, self.running_var, self.minibatch_mean, self.minibatch_riv, self.ret_cta, self.momentum, self.eps, self.fuse_relu, self.training, self.bn_group, self.my_data, self.pair_data, (self.magic), self.pair_data2, self.pair_data3, self.fwd_occupancy, self.fwd_grid_dim_x, self.bwd_occupancy, self.bwd_grid_dim_x, self.multi_stream) def __del__(self): if self.bn_group>1: bnp.close_remote_data(self.pair_handle) if self.bn_group>2: bnp.close_remote_data(self.pair_handle2) if self.bn_group>4: bnp.close_remote_data(self.pair_handle3) ================================================ FILE: KoSimCSE/apex/contrib/layer_norm/__init__.py ================================================ from .layer_norm import FastLayerNorm ================================================ FILE: KoSimCSE/apex/contrib/layer_norm/layer_norm.py ================================================ import torch from torch.nn import init import fast_layer_norm class FastLayerNormFN(torch.autograd.Function): @staticmethod def forward(ctx, x, gamma, beta, epsilon): x = x.contiguous() gamma = gamma.contiguous() beta = beta.contiguous() hidden_size = gamma.numel() xmat = x.view((-1, hidden_size)) ymat, mu, rsigma = fast_layer_norm.ln_fwd(xmat, gamma, beta, epsilon) ctx.save_for_backward(x, gamma, mu, rsigma) return ymat.view(x.shape) @staticmethod def backward(ctx, dy): #assert dy.is_contiguous() dy = dy.contiguous() # this happens! x, gamma, mu, rsigma = ctx.saved_tensors hidden_size = gamma.numel() xmat = x.view((-1, hidden_size)) dymat = dy.view(xmat.shape) dxmat, dgamma, dbeta = fast_layer_norm.ln_bwd(dymat, xmat, mu, rsigma, gamma) dx = dxmat.view(x.shape) return dx, dgamma, dbeta, None class FastLayerNorm(torch.nn.Module): def __init__(self, hidden_size, eps=1e-5): super(FastLayerNorm, self).__init__() self.epsilon = eps self.weight = torch.nn.Parameter(torch.Tensor(hidden_size)) self.bias = torch.nn.Parameter(torch.Tensor(hidden_size)) self.reset_parameters() def reset_parameters(self): init.ones_(self.weight) init.zeros_(self.bias) def forward(self, x): return FastLayerNormFN.apply(x, self.weight, self.bias, self.epsilon) ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/README.md ================================================ # Fast Multihead Attention This implementation has two main features : * A C++ implementation to avoid the CPU overheads of Pytorch found with smaller batch sizes. * The removal of all copies and transposes found in standard implementations of Multihead Attention. | | Python Version | C++ Version | | :----------------------------------------- | :------------: | :---------: | | Layer Norm and Residual Add Variant | X | X | | Includes Linear Biases | X | | | Reduces CPU Overheads | | X | | Fuses masking with Softmax | | X | | Removes Transposes and Copies | X | X | | Includes Self and Encoder/Decoder Variants | X | X | ## How to Instantiate `SelfMultiheadAttn(` _hidden dim_, _heads_, _dropout=prob_, _bias=bool_, _include_norm_add=bool_, _impl='fast'_ `)` `EncdecMultiheadAttn(` _hidden dim_, _heads_, _dropout=prob_, _bias=bool_, _include_norm_add=bool_, _impl='fast'_ `)` `impl` has two options: * `fast` uses C++ Version * `default` uses Python Version ## Instructions to build on Linux ``` $ git clone https://github.com/NVIDIA/apex $ cd apex $ pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" --global-option="--fast_multihead_attn" ./ ``` ## Try Performance Tests Yourself! Perf test script is found here! ``` cd contrib/examples/multihead_attn ``` #### Fast Multihead Attention ``` python perf_test_multihead_attn.py --ref ``` #### Fast Multihead Attention with C++ Implementation ``` python perf_test_multihead_attn.py ``` #### Compare with `torch.nn.MultiheadAttn` ``` python perf_test_multihead_attn.py --native ``` #### Test your own range! ``` python perf_test_multihead_attn.py --seq-length 64 --num-seqs-start 10 --num-seqs-stop 120 --num-seqs-inc 5 ``` ## Performance Comparisons * Performance was measured with 64 token sequence lengths on an NVIDIA TitanV card. * Time is measured across multiple layers to simulate an in model scenario. ![Multihead Attention Forward](MHA_fwd.png) ![Multihead Attention Backward](MHA_bwd.png) ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/__init__.py ================================================ from .self_multihead_attn import SelfMultiheadAttn from .encdec_multihead_attn import EncdecMultiheadAttn from .mask_softmax_dropout_func import fast_mask_softmax_dropout_func ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/encdec_multihead_attn.py ================================================ import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .encdec_multihead_attn_func import encdec_attn_func from .fast_encdec_multihead_attn_func import fast_encdec_attn_func from .fast_encdec_multihead_attn_norm_add_func import fast_encdec_attn_norm_add_func from apex.normalization.fused_layer_norm import FusedLayerNorm if hasattr(torch._C, '_jit_set_profiling_executor') : torch._C._jit_set_profiling_executor(False) if hasattr(torch._C, '_jit_set_profiling_mode') : torch._C._jit_set_profiling_mode(False) @torch.jit.script def jit_dropout_add(x, residual, prob, is_training): # type: (Tensor, Tensor, float, bool) -> Tensor out = F.dropout(x, p=prob, training=True) out = residual + out return out class EncdecMultiheadAttn(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, dropout=0., bias=False, include_norm_add=False, impl='fast'): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.bias = bias self.include_norm_add = include_norm_add self.impl = impl self.scaling = self.head_dim**-0.5 self.in_proj_weight_q = Parameter(torch.Tensor(embed_dim, embed_dim)) self.in_proj_weight_kv = Parameter(torch.Tensor(2*embed_dim, embed_dim)) self.out_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) if self.bias: assert impl != 'fast', "ERROR! The Fast implementation does not support biases!" self.in_proj_bias_q = Parameter(torch.Tensor(embed_dim)) self.in_proj_bias_kv = Parameter(torch.Tensor(2*embed_dim)) self.out_proj_bias = Parameter(torch.Tensor(embed_dim)) else: self.register_parameter('in_proj_bias_q', None) self.register_parameter('in_proj_bias_kv', None) self.in_proj_bias_q = None self.in_proj_bias_kv = None self.out_proj_bias = None if self.include_norm_add: if impl == 'fast': self.lyr_nrm_gamma_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm_beta_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm = None else: self.register_parameter('lyr_norm_gamma_weights', None) self.register_parameter('lyr_norm_beta_weights', None) self.lyr_nrm_gamma_weights = None self.lyr_nrm_beta_weights = None self.lyr_nrm = FusedLayerNorm(embed_dim) self.reset_parameters() if self.include_norm_add: if impl == 'fast' : self.attn_func = fast_encdec_attn_norm_add_func elif impl == 'default' : self.attn_func = encdec_attn_func else : assert False, "Unsupported impl: {} !".format(impl) else: if impl == 'fast' : self.attn_func = fast_encdec_attn_func elif impl == 'default' : self.attn_func = encdec_attn_func else : assert False, "Unsupported impl: {} !".format(impl) def reset_parameters(self): nn.init.xavier_uniform_(self.in_proj_weight_q) # in_proj_weight_kv has shape [2 * hidden, hidden] but it should be # initialized like a [hidden, hidden] matrix. # sqrt(6 / (hidden + hidden)) / sqrt(6 / (2 * hidden + hidden)) = sqrt(1.5) # therefore xavier_uniform gain should be set to sqrt(1.5). nn.init.xavier_uniform_(self.in_proj_weight_kv, gain=math.sqrt(1.5)) nn.init.xavier_uniform_(self.out_proj_weight) if self.bias: nn.init.constant_(self.in_proj_bias_q, 0.) nn.init.constant_(self.in_proj_bias_kv, 0.) nn.init.constant_(self.out_proj_bias, 0.) if self.include_norm_add: if self.impl == 'fast' : nn.init.ones_(self.lyr_nrm_gamma_weights) nn.init.zeros_(self.lyr_nrm_beta_weights) else: self.lyr_nrm.reset_parameters() def forward(self, query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ if key_padding_mask is not None: assert (attn_mask is None), "ERROR attn_mask and key_padding_mask should not be both defined!" mask = key_padding_mask elif attn_mask is not None: mask = attn_mask else: mask = None if self.include_norm_add: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, key, self.lyr_nrm_gamma_weights, self.lyr_nrm_beta_weights, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, mask, self.dropout) else: lyr_nrm_results = self.lyr_nrm(query) outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, lyr_nrm_results, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, self.in_proj_bias_q, self.in_proj_bias_kv, self.out_proj_bias, mask, self.dropout) if is_training: outputs = jit_dropout_add(outputs, query, self.dropout, is_training) else: outputs = outputs + query else: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, mask, self.dropout) else: outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, query, key, self.in_proj_weight_q, self.in_proj_weight_kv, self.out_proj_weight, self.in_proj_bias_q, self.in_proj_bias_kv, self.out_proj_bias, mask, self.dropout) return outputs,None ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/encdec_multihead_attn_func.py ================================================ import torch import torch.nn.functional as F class EncdecAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, scale, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, input_biases_q, input_biases_kv, output_biases, mask, dropout_prob): use_biases_t = torch.tensor([input_biases_q is not None]) heads_t = torch.tensor([heads]) scale_t = torch.tensor([scale]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) head_dim = inputs_q.size(2) // heads # Input Linear GEMM Q # input1: (activations) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim (1024), embed_dim (1024)] (transpose [0,1]) # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) if use_biases_t[0]: input_lin_q_results = torch.addmm(input_biases_q, inputs_q.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), input_weights_q.transpose(0,1), beta=1., alpha=1.) else: input_lin_q_results = torch.mm(inputs_q.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), input_weights_q.transpose(0,1)) input_lin_q_results = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1), input_weights_q.size(0)) # Input Linear GEMM KV # input1: (activations) [seql_k, seqs, embed_dim(1024)] # input2: (weights) [embed_dim*2 (2048), embed_dim (1024)] (transpose [0,1]) # output: [seql_k, seqs, embed_dim*2] # GEMM: ( (seql_k*seqs) x embed_dim ) x ( embed_dim x embed_dim*2 ) = (seql_k*seqs x embed_dim*2) if use_biases_t[0]: input_lin_kv_results = torch.addmm(input_biases_kv, inputs_kv.view(inputs_kv.size(0) * inputs_kv.size(1), inputs_kv.size(2)), input_weights_kv.transpose(0,1), beta=1., alpha=1.) else: input_lin_kv_results = torch.mm(inputs_kv.view(inputs_kv.size(0) * inputs_kv.size(1), inputs_kv.size(2)), input_weights_kv.transpose(0,1)) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1), input_weights_kv.size(0)) # Slice out k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_kv_results: [seql_k, seqs, heads(16), 2, head_dim(64)] # input_lin_kv_results: [seql_k, batches=seqs*heads, 2, head_dim] queries = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1)*heads, head_dim) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1)*heads, 2, head_dim) keys = input_lin_kv_results[:,:,0,:] values = input_lin_kv_results[:,:,1,:] # Matmul1 Batched GEMMs # The output tensor is specified prior to the Batch GEMM because baddbmm requires its specification # baddbmm is used to apply the scale parameter via the Batched GEMM's alpha parameter instead of # a separate elementwise operation. # Input1: (Queries) [seql_q, seqs*heads, head_dim] tranpose(0,1) # Input2: (Keys) [seql_k, seqs*heads, head_dim] transpose(0,1) # output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul1_results = torch.empty((queries.size(1),queries.size(0),keys.size(0)), dtype=queries.dtype, device=torch.device('cuda')) matmul1_results = torch.baddbmm(matmul1_results, queries.transpose(0,1), keys.transpose(0,1).transpose(1,2), out=matmul1_results, beta=0.0, alpha=scale_t[0]) if mask is not None: # Self Attention Time Mask if use_time_mask: assert (len(mask.size()) == 2), "Timing mask is not 2D!" assert (mask.size(0) == mask.size(1)), "Sequence length should match!" mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask, float('-inf')) # Key Padding Mask else: batches,seql_q,seql_k = matmul1_results.size() seqs = int(batches / heads) matmul1_results = matmul1_results.view(seqs, heads, seql_q, seql_k) mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask.unsqueeze(1).unsqueeze(2), float('-inf')) matmul1_results = matmul1_results.view(seqs*heads, seql_q, seql_k) softmax_results = F.softmax(matmul1_results, dim=-1) # Dropout - is not executed for inference if is_training: dropout_results,dropout_mask = torch._fused_dropout(softmax_results, p=(1.-dropout_prob_t[0])) else: dropout_results = softmax_results dropout_mask = null_tensor # Matmul2 Batched GEMMs # The output tensor specification is needed here to specify the non-standard output. # Given that pytorch cannot currently perform autograd with an output tensor specified, # this requires a backward pass specified. # Input1: from_softmax [seqs*heads, seql_q, seql_k] # Input2: (values) [seql_v, seqs*heads, head_dim] transpose(0,1) # Output: [seql_q, seqs*heads, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = (seql_q x head_dim) matmul2_results = torch.empty((dropout_results.size(1), dropout_results.size(0), values.size(2)), dtype=dropout_results.dtype, device=torch.device('cuda')).transpose(1,0) matmul2_results = torch.bmm(dropout_results, values.transpose(0,1), out=matmul2_results) matmul2_results = matmul2_results.transpose(0, 1).contiguous().view(inputs_q.size(0), inputs_q.size(1), inputs_q.size(2)) # Output Linear GEMM # Input1: (activations) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] transpose(0,1) # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) if use_biases_t[0]: outputs = torch.addmm(output_biases, matmul2_results.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), output_weights.transpose(0,1), beta=1., alpha=1.) else: outputs = torch.mm(matmul2_results.view(inputs_q.size(0) * inputs_q.size(1), inputs_q.size(2)), output_weights.transpose(0,1)) outputs = outputs.view(inputs_q.size(0), inputs_q.size(1), output_weights.size(0)) ctx.save_for_backward(use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors head_dim = inputs_q.size(2) // heads_t[0] # Slice out k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_kv_results: [seql_k, seqs, heads(16), 2, head_dim(64)] # input_lin_kv_results: [seql_k, batches=seqs*heads, 2, head_dim] queries = input_lin_q_results.view(inputs_q.size(0), inputs_q.size(1)*heads_t[0], head_dim) input_lin_kv_results = input_lin_kv_results.view(inputs_kv.size(0), inputs_kv.size(1)*heads_t[0], 2, head_dim) keys = input_lin_kv_results[:,:,0,:] values = input_lin_kv_results[:,:,1,:] # Slice out k,v from one big set of gradients entering the input linear's bprop (should only impact meta data, no copies!) # The gradients are identical in size to the Input Linear outputs. # The tensor is declared before hand to properly slice out query, key, and value grads. input_lin_kv_results_grads = torch.empty_like(input_lin_kv_results) queries_grads = torch.empty_like(queries) keys_grads = input_lin_kv_results_grads[:,:,0,:] values_grads = input_lin_kv_results_grads[:,:,1,:] # Output Linear GEMM - DGRAD # Input1: (data grads) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) output_lin_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), output_weights) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1), output_weights.size(1)) # Output Linear GEMM - WGRAD # Input1: (data grads) [seql_q*seqs, embed_dim=heads*head_dim] transpose(0,1) # Input2: (activations) [seql_q*seqs, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = ( embed_dim x embed_dim ) output_weight_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)).transpose(0,1), matmul2_results.view(matmul2_results.size(0) * matmul2_results.size(1), matmul2_results.size(2))) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1)*heads_t[0], head_dim).transpose(0,1) if use_biases_t[0]: output_bias_grads = torch.sum(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), 0) else: output_bias_grads = None # Matmul2 - DGRAD1 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul2_dgrad1 = torch.bmm(output_lin_grads, values.transpose(0,1).transpose(1,2)) # Matmul2 - DGRAD2 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) values_grads = torch.bmm(dropout_results.transpose(1,2), output_lin_grads, out=values_grads.transpose(0,1)) # Mask and Scaling for Dropout (not a publically documented op) dropout_grads = torch._masked_scale(matmul2_dgrad1, dropout_mask, 1.0/(1.0-dropout_prob_t[0])) # Softmax Grad (not a publically documented op) softmax_grads = torch._softmax_backward_data(dropout_grads, softmax_results, -1, softmax_results) # Matmul1 - DGRAD1 # Input1: (data grads) [seqs*heads, seql_q, seql_k] # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_q, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = ( seql_q x head_dim ) queries_grads = torch.baddbmm(queries_grads.transpose(0,1), softmax_grads, keys.transpose(0,1), out=queries_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Matmul1 - DGRAD2 # Input1: (data grads) [seqs*heads, seql_q, seql_k] transpose(1,2) # Input2: (activations) [seql_q, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_k, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_k x seql_q ) x ( seql_q x head_dim ) = ( seql_k x head_dim ) keys_grads = torch.baddbmm(keys_grads.transpose(0,1), softmax_grads.transpose(1,2), queries.transpose(0,1), out=keys_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Input Q Linear GEMM - DGRAD # input1: (data grads) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim (1024), embed_dim (1024)] # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) queries_grads = queries_grads.transpose(0,1).view(inputs_q.size(0)*inputs_q.size(1), heads_t[0]*head_dim) input_q_grads = torch.mm(queries_grads, input_weights_q) input_q_grads = input_q_grads.view(inputs_q.size(0), inputs_q.size(1), inputs_q.size(2)) # Input KV Linear GEMM - DGRAD # input1: (data grads) [seql_k, seqs, 2*embed_dim(2048)] # input2: (weights) [embed_dim*2 (2048), embed_dim (1024)] # output: [seql_k, seqs, embed_dim] # GEMM: ( (seql_k*seqs) x 2*embed_dim ) x ( 2*embed_dim x embed_dim ) = (seql_k*seqs x embed_dim) input_lin_kv_results_grads = input_lin_kv_results_grads.view(inputs_kv.size(0)*inputs_kv.size(1), heads_t[0]*2*head_dim) input_kv_grads = torch.mm(input_lin_kv_results_grads, input_weights_kv) input_kv_grads = input_kv_grads.view(inputs_kv.size(0), inputs_kv.size(1), inputs_kv.size(2)) # Input Q Linear GEMM - WGRAD # input1: (data grads) [seql_q*seqs, embed_dim(1024)] # input2: (activations) [seql_q*seqs, embed_dim(1024)] # output: [embed_dim, embed_dim] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = (embed_dim x embed_dim) input_weight_q_grads = torch.mm(queries_grads.transpose(0,1), inputs_q.view(inputs_q.size(0)*inputs_q.size(1), inputs_q.size(2))) # Input KV Linear GEMM - WGRAD # input1: (data grads) [seql_k*seqs, 2*embed_dim(2048)] # input2: (activations) [seql_k*seqs, embed_dim(1024)] # output: [2*embed_dim, embed_dim] # GEMM: ( 2*embed_dim x seql_k*seqs ) x ( seql_k*seqs x embed_dim ) = (2*embed_dim x embed_dim) input_weight_kv_grads = torch.mm(input_lin_kv_results_grads.transpose(0,1), inputs_kv.view(inputs_kv.size(0)*inputs_kv.size(1), inputs_kv.size(2))) if use_biases_t[0]: input_bias_grads_q = torch.sum(queries_grads, 0) input_bias_grads_kv = torch.sum(input_lin_kv_results_grads, 0) else: input_bias_grads_q = None input_bias_grads_kv = None return None, None, None, None, \ input_q_grads, input_kv_grads, \ input_weight_q_grads, input_weight_kv_grads, output_weight_grads, \ input_bias_grads_q, input_bias_grads_kv, output_bias_grads, \ None, None encdec_attn_func = EncdecAttnFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/fast_encdec_multihead_attn_func.py ================================================ import torch import fast_encdec_multihead_attn class FastEncdecAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs_q, inputs_kv, input_weights_q, input_weights_kv, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) input_lin_q_results, \ input_lin_kv_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_encdec_multihead_attn.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors input_q_grads, \ input_kv_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads = \ fast_encdec_multihead_attn.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ inputs_q, \ inputs_kv, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) return None, None, None, input_q_grads, input_kv_grads, input_weight_q_grads, input_weight_kv_grads, output_weight_grads, None, None fast_encdec_attn_func = FastEncdecAttnFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/fast_encdec_multihead_attn_norm_add_func.py ================================================ # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import fast_encdec_multihead_attn_norm_add class FastEncdecAttnNormAddFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs_q, inputs_kv, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights_q, input_weights_kv, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ input_lin_q_results, \ input_lin_kv_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ dropout_add_mask, \ outputs = \ fast_encdec_multihead_attn_norm_add.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t = ctx.saved_tensors input_q_grads, \ input_kv_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads = \ fast_encdec_multihead_attn_norm_add.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_q_results, \ input_lin_kv_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs_q, \ inputs_kv, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights_q, \ input_weights_kv, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t[0]) #import pdb; pdb.set_trace() return None, None, None, \ input_q_grads, \ input_kv_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_q_grads, \ input_weight_kv_grads, \ output_weight_grads, \ None, None fast_encdec_attn_norm_add_func = FastEncdecAttnNormAddFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/fast_self_multihead_attn_func.py ================================================ import torch import fast_self_multihead_attn import fast_self_multihead_attn_bias import fast_self_multihead_attn_bias_additive_mask class FastSelfAttnFunc(torch.autograd.Function) : @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, pad_mask, mask_additive, dropout_prob): use_biases_t = torch.tensor([input_biases is not None]) heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) mask_additive_t= torch.tensor([mask_additive]) if use_biases_t[0]: if not mask_additive: input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn_bias.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ input_biases, \ output_biases, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ null_tensor, \ null_tensor, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) else: input_lin_results, \ bmm1_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn_bias_additive_mask.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ input_biases, \ output_biases, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ null_tensor, \ bmm1_results, \ pad_mask, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) else: input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ outputs = \ fast_self_multihead_attn.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ input_weights, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ null_tensor, \ null_tensor, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ bmm1_results, \ pad_mask, \ mask_additive_t, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors if use_biases_t[0]: if not mask_additive_t[0]: input_grads, \ input_weight_grads, \ output_weight_grads, \ input_bias_grads, \ output_bias_grads = \ fast_self_multihead_attn_bias.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) else: input_grads, \ input_weight_grads, \ output_weight_grads, \ input_bias_grads, \ output_bias_grads = \ fast_self_multihead_attn_bias_additive_mask.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ bmm1_results, \ pad_mask, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) else: input_bias_grads = None output_bias_grads = None input_grads, \ input_weight_grads, \ output_weight_grads = \ fast_self_multihead_attn.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t[0]) return None, None, None, input_grads, input_weight_grads, output_weight_grads,input_bias_grads, output_bias_grads, None, None, None fast_self_attn_func = FastSelfAttnFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/fast_self_multihead_attn_norm_add_func.py ================================================ import torch import fast_self_multihead_attn_norm_add class FastSelfAttnNormAddFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, inputs, lyr_nrm_gamma_weights, lyr_nrm_beta_weights, input_weights, output_weights, pad_mask, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ input_lin_results, \ softmax_results, \ dropout_results, \ dropout_mask, \ matmul2_results, \ dropout_add_mask, \ outputs = \ fast_self_multihead_attn_norm_add.forward( \ use_mask, \ use_time_mask, \ is_training, \ heads, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward(heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): heads_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t = ctx.saved_tensors input_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_grads, \ output_weight_grads = \ fast_self_multihead_attn_norm_add.backward( \ heads_t[0], \ output_grads, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ lyr_nrm_results, \ lyr_nrm_mean, \ lyr_nrm_invvar, \ inputs, \ lyr_nrm_gamma_weights, \ lyr_nrm_beta_weights, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_add_mask, \ dropout_prob_t[0]) return None, None, None, \ input_grads, \ lyr_nrm_gamma_grads, \ lyr_nrm_beta_grads, \ input_weight_grads, \ output_weight_grads, \ None, None fast_self_attn_norm_add_func = FastSelfAttnNormAddFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/mask_softmax_dropout_func.py ================================================ import torch import fast_mask_softmax_dropout import fast_additive_mask_softmax_dropout class MaskSoftmaxDropout(torch.autograd.Function) : @staticmethod def forward(ctx, is_training, heads, inputs, pad_mask, mask_additive, dropout_prob): heads_t = torch.tensor([heads]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) use_mask = (pad_mask is not None) use_mask_t = torch.tensor([use_mask]) mask_additive_t = torch.tensor([mask_additive]) if mask_additive: dropout_results, \ dropout_mask, \ softmax_results = \ fast_additive_mask_softmax_dropout.forward( \ use_mask, \ is_training, \ heads, \ inputs, \ pad_mask if use_mask else null_tensor, \ dropout_prob) else: dropout_results, \ dropout_mask, \ softmax_results = \ fast_mask_softmax_dropout.forward( \ use_mask, \ is_training, \ heads, \ inputs, \ pad_mask if use_mask else null_tensor, \ dropout_prob) ctx.save_for_backward( use_mask_t, \ heads_t, \ softmax_results, \ dropout_mask, \ pad_mask if use_mask else null_tensor, \ mask_additive_t, \ dropout_prob_t) return dropout_results.detach() @staticmethod def backward(ctx, output_grads): use_mask_t, \ heads_t, \ softmax_results, \ dropout_mask, \ pad_mask, \ mask_additive_t, \ dropout_prob_t = ctx.saved_tensors if mask_additive_t[0]: input_grads = \ fast_additive_mask_softmax_dropout.backward( \ use_mask_t[0], \ heads_t[0], \ output_grads, \ softmax_results, \ dropout_mask, \ dropout_prob_t[0]) else: input_grads = \ fast_mask_softmax_dropout.backward( \ use_mask_t[0], \ heads_t[0], \ output_grads, \ softmax_results, \ dropout_mask, \ pad_mask, \ dropout_prob_t[0]) return None, None, input_grads, None, None, None fast_mask_softmax_dropout_func = MaskSoftmaxDropout.apply ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/self_multihead_attn.py ================================================ import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .self_multihead_attn_func import self_attn_func from .fast_self_multihead_attn_func import fast_self_attn_func from .fast_self_multihead_attn_norm_add_func import fast_self_attn_norm_add_func from apex.normalization.fused_layer_norm import FusedLayerNorm if hasattr(torch._C, '_jit_set_profiling_executor') : torch._C._jit_set_profiling_executor(False) if hasattr(torch._C, '_jit_set_profiling_mode') : torch._C._jit_set_profiling_mode(False) @torch.jit.script def jit_dropout_add(x, residual, prob, is_training): # type: (Tensor, Tensor, float, bool) -> Tensor out = F.dropout(x, p=prob, training=True) out = residual + out return out class SelfMultiheadAttn(nn.Module): """Multi-headed attention. See "Attention Is All You Need" for more details. """ def __init__(self, embed_dim, num_heads, dropout=0., bias=False, include_norm_add=False, impl='fast', separate_qkv_params=False, mask_additive=False): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.bias = bias self.include_norm_add = include_norm_add self.impl = impl self.scaling = self.head_dim**-0.5 self.separate_qkv_params = separate_qkv_params self.mask_additive = mask_additive if mask_additive: assert self.include_norm_add == False, "additive mask not supported with layer norm" assert impl == 'default' or (impl == 'fast' and bias), "additive mask not supported for fast mode without bias" if separate_qkv_params: self.q_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) self.k_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) self.v_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) else: self.in_proj_weight = Parameter(torch.Tensor(3*embed_dim, embed_dim)) self.out_proj_weight = Parameter(torch.Tensor(embed_dim, embed_dim)) if self.bias: if separate_qkv_params: self.q_bias = Parameter(torch.Tensor(embed_dim)) self.k_bias = Parameter(torch.Tensor(embed_dim)) self.v_bias = Parameter(torch.Tensor(embed_dim)) else: self.in_proj_bias = Parameter(torch.Tensor(3*embed_dim)) self.out_proj_bias = Parameter(torch.Tensor(embed_dim)) else: if separate_qkv_params: self.register_parameter('q_bias', None) self.register_parameter('k_bias', None) self.register_parameter('v_bias', None) self.q_bias = None self.k_bias = None self.v_bias = None else: self.register_parameter('in_proj_bias', None) self.in_proj_bias = None self.register_parameter('out_proj_bias', None) self.out_proj_bias = None if self.include_norm_add: if impl == 'fast': self.lyr_nrm_gamma_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm_beta_weights = Parameter(torch.Tensor(embed_dim)) self.lyr_nrm = None else: self.register_parameter('lyr_norm_gamma_weights', None) self.register_parameter('lyr_norm_beta_weights', None) self.lyr_nrm_gamma_weights = None self.lyr_nrm_beta_weights = None self.lyr_nrm = FusedLayerNorm(embed_dim) self.reset_parameters() if self.include_norm_add: if impl == 'fast' : self.attn_func = fast_self_attn_norm_add_func elif impl == 'default' : self.attn_func = self_attn_func else : assert False, "Unsupported impl: {} !".format(impl) else: if impl == 'fast' : self.attn_func = fast_self_attn_func elif impl == 'default' : self.attn_func = self_attn_func else : assert False, "Unsupported impl: {} !".format(impl) def reset_parameters(self): if self.separate_qkv_params: nn.init.xavier_uniform_(self.q_weight) nn.init.xavier_uniform_(self.k_weight) nn.init.xavier_uniform_(self.v_weight) else: # in_proj_weight has shape [3 * hidden, hidden] but it should be # initialized like a [hidden, hidden] matrix. # sqrt(6 / (hidden + hidden)) / sqrt(6 / (3 * hidden + hidden)) = sqrt(2) # therefore xavier_uniform gain should be set to sqrt(2). nn.init.xavier_uniform_(self.in_proj_weight, gain=math.sqrt(2)) nn.init.xavier_uniform_(self.out_proj_weight) if self.bias: if self.separate_qkv_params: nn.init.constant_(self.q_bias, 0.) nn.init.constant_(self.k_bias, 0.) nn.init.constant_(self.v_bias, 0.) else: nn.init.constant_(self.in_proj_bias, 0.) nn.init.constant_(self.out_proj_bias, 0.) if self.include_norm_add: if self.impl == 'fast': nn.init.ones_(self.lyr_nrm_gamma_weights) nn.init.zeros_(self.lyr_nrm_beta_weights) else: self.lyr_nrm.reset_parameters() def forward(self, query, key, value, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ if self.separate_qkv_params: input_weights = torch.cat([self.q_weight.view(self.num_heads,1,self.head_dim,self.embed_dim), self.k_weight.view(self.num_heads,1,self.head_dim,self.embed_dim), self.v_weight.view(self.num_heads,1,self.head_dim,self.embed_dim)], dim=1).reshape(3*self.embed_dim,self.embed_dim).contiguous() else: input_weights = self.in_proj_weight if self.bias: if self.separate_qkv_params: input_bias = torch.cat([self.q_bias.view(self.num_heads,1,self.head_dim), self.k_bias.view(self.num_heads,1,self.head_dim), self.v_bias.view(self.num_heads,1,self.head_dim)],dim=1).reshape(3*self.embed_dim).contiguous() else: input_bias = self.in_proj_bias else: input_bias=None if key_padding_mask is not None: assert (attn_mask is None), "ERROR attn_mask and key_padding_mask should not be both defined!" mask = key_padding_mask elif attn_mask is not None: assert self.mask_additive == False, "additive mask not supported for time mask" mask = attn_mask else: mask = None if self.include_norm_add: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, self.lyr_nrm_gamma_weights, self.lyr_nrm_beta_weights, input_weights, self.out_proj_weight, mask, self.dropout) else: lyr_nrm_results = self.lyr_nrm(query) outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, lyr_nrm_results, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.dropout) if is_training: outputs = jit_dropout_add(outputs, query, self.dropout, is_training) else: outputs = outputs + query else: if self.impl == 'fast': outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, query, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.mask_additive, self.dropout) else: outputs = self.attn_func(attn_mask is not None, is_training, self.num_heads, self.scaling, query, input_weights, self.out_proj_weight, input_bias, self.out_proj_bias, mask, self.mask_additive, self.dropout) return outputs,None ================================================ FILE: KoSimCSE/apex/contrib/multihead_attn/self_multihead_attn_func.py ================================================ import torch import torch.nn.functional as F class SelfAttnFunc(torch.autograd.Function): @staticmethod def forward(ctx, use_time_mask, is_training, heads, scale, inputs, input_weights, output_weights, input_biases, output_biases, mask, is_additive_mask, dropout_prob): use_biases_t = torch.tensor([input_biases is not None]) heads_t = torch.tensor([heads]) scale_t = torch.tensor([scale]) dropout_prob_t = torch.tensor([dropout_prob]) null_tensor = torch.tensor([]) head_dim = inputs.size(2) // heads # Input Linear GEMM # input1: (activations) [seql_q, seqs, embed_dim(1024)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] (transpose [0,1]) # output: [seql_q, seqs, embed_dim*3] # GEMM: ( (seql_q*seqs) x embed_dim ) x ( embed_dim x embed_dim*3 ) = (seql_q*seqs x embed_dim*3) if use_biases_t[0]: input_lin_results = torch.addmm(input_biases, inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0,1), beta=1., alpha=1.) else: input_lin_results = torch.mm(inputs.view(inputs.size(0) * inputs.size(1), inputs.size(2)), input_weights.transpose(0,1)) input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1), input_weights.size(0)) # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1)*heads, 3, head_dim) queries = input_lin_results[:,:,0,:] keys = input_lin_results[:,:,1,:] values = input_lin_results[:,:,2,:] # Matmul1 Batched GEMMs # The output tensor is specified prior to the Batch GEMM because baddbmm requires its specification # baddbmm is used to apply the scale parameter via the Batched GEMM's alpha parameter instead of # a separate elementwise operation. # Input1: (Queries) [seql_q, seqs*heads, head_dim] tranpose(0,1) # Input2: (Keys) [seql_k, seqs*heads, head_dim] transpose(0,1) # output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul1_results = torch.empty((queries.size(1),queries.size(0),keys.size(0)), dtype=queries.dtype, device=torch.device('cuda')) matmul1_results = torch.baddbmm(matmul1_results, queries.transpose(0,1), keys.transpose(0,1).transpose(1,2), out=matmul1_results, beta=0.0, alpha=scale_t[0]) if mask is not None: # Self Attention Time Mask if use_time_mask: assert (len(mask.size()) == 2), "Timing mask is not 2D!" assert (mask.size(0) == mask.size(1)), "Sequence length should match!" mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask, float('-inf')) # Key Padding Mask else: batches,seql_q,seql_k = matmul1_results.size() seqs = int(batches / heads) matmul1_results = matmul1_results.view(seqs, heads, seql_q, seql_k) if is_additive_mask: matmul1_results = matmul1_results + mask.unsqueeze(1).unsqueeze(2) else: mask = mask.to(torch.bool) matmul1_results = matmul1_results.masked_fill_(mask.unsqueeze(1).unsqueeze(2), float('-inf')) matmul1_results = matmul1_results.view(seqs*heads, seql_q, seql_k) softmax_results = F.softmax(matmul1_results, dim=-1) # Dropout - is not executed for inference if is_training: dropout_results,dropout_mask = torch._fused_dropout(softmax_results, p=(1.-dropout_prob_t[0])) else: dropout_results = softmax_results dropout_mask = null_tensor # Matmul2 Batched GEMMs # The output tensor specification is needed here to specify the non-standard output. # Given that pytorch cannot currently perform autograd with an output tensor specified, # this requires a backward pass specified. # Input1: from_softmax [seqs*heads, seql_q, seql_k] # Input2: (values) [seql_v, seqs*heads, head_dim] transpose(0,1) # Output: [seql_q, seqs*heads, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = (seql_q x head_dim) matmul2_results = torch.empty((dropout_results.size(1), dropout_results.size(0), values.size(2)), dtype=dropout_results.dtype, device=torch.device('cuda')).transpose(1,0) matmul2_results = torch.bmm(dropout_results, values.transpose(0,1), out=matmul2_results) matmul2_results = matmul2_results.transpose(0, 1).contiguous().view(inputs.size(0), inputs.size(1), inputs.size(2)) # Output Linear GEMM # Input1: (activations) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] transpose(0,1) # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) if use_biases_t[0]: outputs = torch.addmm(output_biases, matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0,1), beta=1., alpha=1.) else: outputs = torch.mm(matmul2_results.view(inputs.size(0) * inputs.size(1), inputs.size(2)), output_weights.transpose(0,1)) outputs = outputs.view(inputs.size(0), inputs.size(1), output_weights.size(0)) ctx.save_for_backward(use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t) return outputs.detach() @staticmethod def backward(ctx, output_grads): use_biases_t, \ heads_t, \ scale_t, \ matmul2_results, \ dropout_results, \ softmax_results, \ input_lin_results, \ inputs, \ input_weights, \ output_weights, \ dropout_mask, \ dropout_prob_t = ctx.saved_tensors head_dim = inputs.size(2) // heads_t[0] # Slice out q,k,v from one big Input Linear outuput (should only impact meta data, no copies!) # Sequences and heads are combined to make the batch of the Batched GEMM # input_lin_results: [seql_q, seqs, heads(16), 3, head_dim(64)] # input_lin_results: [seql_q, batches=seqs*heads, 3, head_dim] input_lin_results = input_lin_results.view(inputs.size(0), inputs.size(1)*heads_t[0], 3, head_dim) queries = input_lin_results[:,:,0,:] keys = input_lin_results[:,:,1,:] values = input_lin_results[:,:,2,:] # Slice out q,k,v from one big set of gradients entering the input linear's bprop (should only impact meta data, no copies!) # The gradients are identical in size to the Input Linear outputs. # The tensor is declared before hand to properly slice out query, key, and value grads. input_lin_results_grads = torch.empty_like(input_lin_results) queries_grads = input_lin_results_grads[:,:,0,:] keys_grads = input_lin_results_grads[:,:,1,:] values_grads = input_lin_results_grads[:,:,2,:] # Output Linear GEMM - DGRAD # Input1: (data grads) [seql_q, seqs, embed_dim=heads*head_dim] # Input2: (weights) [ embed_dim, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( seql_q*seqs x embed_dim ) x ( embed_dim x embed_dim ) = ( seql_q*seqs x embed_dim ) output_lin_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), output_weights) output_lin_grads = output_lin_grads.view(output_grads.size(0), output_grads.size(1), output_weights.size(1)) # Output Linear GEMM - WGRAD # Input1: (data grads) [seql_q*seqs, embed_dim=heads*head_dim] transpose(0,1) # Input2: (activations) [seql_q*seqs, embed_dim ] # Output: [ seql_q, seqs, embed_dim ] # GEMM: ( embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = ( embed_dim x embed_dim ) output_weight_grads = torch.mm(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)).transpose(0,1), matmul2_results.view(matmul2_results.size(0) * matmul2_results.size(1), matmul2_results.size(2))) output_lin_grads = output_lin_grads.view(inputs.size(0), inputs.size(1)*heads_t[0], head_dim).transpose(0,1) if use_biases_t[0]: output_bias_grads = torch.sum(output_grads.view(output_grads.size(0) * output_grads.size(1), output_grads.size(2)), 0) else: output_bias_grads = None # Matmul2 - DGRAD1 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) matmul2_dgrad1 = torch.bmm(output_lin_grads, values.transpose(0,1).transpose(1,2)) # Matmul2 - DGRAD2 # Input1: (data grads) [seql_q, seqs*heads, head_dim] transpose(0,1) # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1).transpose(1,2) # Output: [seqs*heads, seql_q, seql_k] # GEMM: Per batch: ( seql_q x head_dim ) x ( head_dim x seql_k ) = ( seql_q x seql_k ) values_grads = torch.bmm(dropout_results.transpose(1,2), output_lin_grads, out=values_grads.transpose(0,1)) # Mask and Scaling for Dropout (not a publically documented op) dropout_grads = torch._masked_scale(matmul2_dgrad1, dropout_mask, 1.0/(1.0-dropout_prob_t[0])) # Softmax Grad (not a publically documented op) softmax_grads = torch._softmax_backward_data(dropout_grads, softmax_results, -1, softmax_results) # Matmul1 - DGRAD1 # Input1: (data grads) [seqs*heads, seql_q, seql_k] # Input2: (activations) [seql_k, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_q, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_q x seql_k ) x ( seql_k x head_dim ) = ( seql_q x head_dim ) queries_grads = torch.baddbmm(queries_grads.transpose(0,1), softmax_grads, keys.transpose(0,1), out=queries_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Matmul1 - DGRAD2 # Input1: (data grads) [seqs*heads, seql_q, seql_k] transpose(1,2) # Input2: (activations) [seql_q, seqs*heads, head_dim] transpose(0,1) # Output: [seqs*heads, seql_k, head_dim] transpose(0,1) # GEMM: Per batch: ( seql_k x seql_q ) x ( seql_q x head_dim ) = ( seql_k x head_dim ) keys_grads = torch.baddbmm(keys_grads.transpose(0,1), softmax_grads.transpose(1,2), queries.transpose(0,1), out=keys_grads.transpose(0,1), beta=0.0, alpha=scale_t[0]) # Input Linear GEMM - DGRAD # input1: (data grads) [seql_q, seqs, 3*embed_dim(3072)] # input2: (weights) [embed_dim*3 (3072), embed_dim (1024)] # output: [seql_q, seqs, embed_dim] # GEMM: ( (seql_q*seqs) x 3*embed_dim ) x ( 3*embed_dim x embed_dim ) = (seql_q*seqs x embed_dim) input_lin_results_grads = input_lin_results_grads.view(inputs.size(0)*inputs.size(1), heads_t[0]*3*head_dim) input_grads = torch.mm(input_lin_results_grads, input_weights) input_grads = input_grads.view(inputs.size(0), inputs.size(1), inputs.size(2)) # Input Linear GEMM - WGRAD # input1: (data grads) [seql_q*seqs, 3*embed_dim(3072)] # input2: (activations) [seql_q*seqs, embed_dim(1024)] # output: [3*embed_dim, embed_dim] # GEMM: ( 3*embed_dim x seql_q*seqs ) x ( seql_q*seqs x embed_dim ) = (3*embed_dim x embed_dim) input_weight_grads = torch.mm(input_lin_results_grads.transpose(0,1), inputs.view(inputs.size(0)*inputs.size(1), inputs.size(2))) if use_biases_t[0]: input_bias_grads = torch.sum(input_lin_results_grads, 0) else: input_bias_grads = None return None, None, None, None, \ input_grads, \ input_weight_grads, output_weight_grads, \ input_bias_grads, output_bias_grads, \ None, None self_attn_func = SelfAttnFunc.apply ================================================ FILE: KoSimCSE/apex/contrib/optimizers/__init__.py ================================================ from .fp16_optimizer import FP16_Optimizer from .fused_adam import FusedAdam from .fused_lamb import FusedLAMB ================================================ FILE: KoSimCSE/apex/contrib/optimizers/distributed_fused_adam.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier import torch.distributed.distributed_c10d as c10d class DistributedFusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) step_supports_amp_scaling(boolean, optional): whether to use customized gradient unscaling logic (default: True) num_process_groups (integer, optional): number of process groups in the app (default: 1) current_process_group (object, optional): the process group to work on (default: None) process_group_id (integer, optional): process group id (default: 0) process_group_size (integer, optional): size of process group (default: 0) clip_grad_norm (boolean, optional): whether to handle gradient clipping (default: True) model_parallel (boolean, optional): whether model parallelism is used (default: False) .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt=False, weight_decay=0., max_grad_norm=0., amsgrad=False, flat_mt=False, overlap_reductions=True, compute_L2_grad_norm=False, dwu_group_size=0, dwu_num_blocks=4, dwu_num_chunks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, predivide=True, e5m2_allgather=False, do_not_flatten_model=False, step_supports_amp_scaling=True, num_process_groups=1, current_process_group=None, process_group_id=0, process_group_size=0, clip_grad_norm=True, model_parallel=False): global fused_adam_cuda, distributed_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") distributed_adam_cuda = importlib.import_module("distributed_adam_cuda") self.multi_tensor_l2norm = amp_C.multi_tensor_l2norm if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdam, self).__init__(params, defaults) # Misc self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False self._step_supports_amp_scaling = step_supports_amp_scaling self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._compute_L2_grad_norm = compute_L2_grad_norm self._L2_grad_norm = None self._flat_mt = flat_mt self._init_done = False self._resume_from_checkpoint = False self._step = 0 # Process group related self._clip_grad_norm = clip_grad_norm self._model_parallel = model_parallel self._num_process_groups = num_process_groups self._current_process_group = current_process_group if current_process_group is not None else c10d._get_default_group() self._available_ranks = list(c10d._pg_group_ranks[self._current_process_group].keys()) self._process_group_id = process_group_id self._process_group_size = torch.cuda.device_count() if process_group_size <= 0 else process_group_size self._world_size = self._process_group_size # world: the current process group self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._num_groups = self._world_size // self._group_size self._global_rank = torch.distributed.get_rank() self._world_rank = self._global_rank // self._num_process_groups self._group_rank = self._world_rank % self._group_size #print("world_size:", self._world_size, ", group_size:", self._group_size, ", num_groups:", self._num_groups, ", global_rank:", self._global_rank, ", world_rank:", self._world_rank, ", group_rank:", self._group_rank) self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg # Master weight, moment, gradient buffers self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_p, self._fp16_g = None, None, None, None, None def _first_step_init(self): p_offset = 0 p_i = 0 self._model_params = [] self._grads_info = [] self._grad_accs = [] self._group_properties = [] for group in self.param_groups: self._param_group = group prev = None beta1, beta2 = group['betas'] bias_correction = 1 if group['bias_correction'] else 0 eps = group['eps'] weight_decay = group['weight_decay'] for p in group['params']: # broadcast from rank 0 of current process group torch.distributed.broadcast(p, src=self._available_ranks[0], group=self._current_process_group) if not p.requires_grad: continue self._model_params.append(p) # Multiple param groups support: # store one hyperparam item per parameter tensor self._group_properties.append(( beta1, beta2, bias_correction, eps, weight_decay )) p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._grads = [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._chunk_size = self._block_size // self._num_chunks self._shard_size = self._chunk_size // self._group_size #print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._chunk_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._chunk_size,self._shard_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i #print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._shard_size # initialize master weights, moments buffers if not loaded from checkpoint if self._fp32_p is None: self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') self._individual_flat_grads = [] for p_i, (grads_info, p) in enumerate(zip(self._grads_info, self._model_params)): self._individual_flat_grads.append(self._flat_grads[grads_info["param_offset"]:grads_info["param_offset"]+grads_info["param_grads_size"]].view_as(p)) def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_chunks = [__chunkify(block) for block in list_of_blocks] list_of_list_of_list_of_shards = [[__shardify(chunk) for chunk in chunks] for chunks in list_of_list_of_chunks] return list_of_blocks, list_of_list_of_chunks, list_of_list_of_list_of_shards self._flat_grads_blocks, self._flat_grads_chunks, self._flat_grads_shards = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._shard_size:(block_id+1)*self._num_chunks*self._shard_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._shard_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): # in the packed format, each chunk contains one shard, so packed_chunk_size == self._shard_size return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params = [] self._contrib_tensor_list = [] self._contrib_group_properties = [] self._non_parallel_grads = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): flat_shard_start = (((block_id * self._num_chunks + chunk_id) * self._group_size) + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for (p, grads_info, group_props) in zip(self._model_params, self._grads_info, self._group_properties): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_chunks[shard_id][block_id][chunk_id][shard_offset:shard_offset+grad_length] self._packed_flat_to_model_params.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._group_rank: # copy model parameters into master buffer master_param_fragment = self._fp32_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_m_fragment = self._fp32_m_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_v_fragment = self._fp32_v_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_g_fragment = self._fp16_g_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_p_fragment = self._fp16_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] #print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) if not self._resume_from_checkpoint: master_param_fragment.copy_(model_param_fragment) self._contrib_group_properties.append(group_props) self._contrib_tensor_list.append((master_param_fragment, opti_state_m_fragment, opti_state_v_fragment, opti_state_g_fragment, opti_state_p_fragment)) # p, m, v, g, p_copy if self._model_parallel and hasattr(p, 'model_parallel') and not p.model_parallel: self._non_parallel_grads.append(opti_state_g_fragment) p, m, v, g, p_copy = list(zip(*self._contrib_tensor_list)) self._contrib_tensor_list = [p, m, v, g, p_copy] math_type = self._fp32_p.dtype beta1, beta2, bias_correction, epsilon, decay = list(zip(*self._contrib_group_properties)) self._contrib_beta1 = torch.tensor(beta1, dtype=math_type, device='cuda') self._contrib_beta2 = torch.tensor(beta2, dtype=math_type, device='cuda') self._contrib_bias_correction = torch.tensor(bias_correction, dtype=torch.int, device='cuda') self._contrib_epsilon = torch.tensor(epsilon, dtype=math_type, device='cuda') self._contrib_weight_decay = torch.tensor(decay, dtype=math_type, device='cuda') p_in, p_out = zip(*self._packed_flat_to_model_params) self._packed_flat_to_model_params = [p_in, p_out] if self._num_groups > 1: self._ar_pg = [] for i in range(self._num_process_groups): # gather global ranks of all members of the current process group ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._group_size): ar_idx = [j+k*self._group_size for k in range(self._num_groups)] ar_rank = [ranks[k] for k in ar_idx] #if self._global_rank in ar_rank: # print("group for all reduce, ranks:", ar_rank) for _ in range(self._num_ar_pg): grp = torch.distributed.new_group(ranks=ar_rank) if self._global_rank in ar_rank: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] for ar_pg in self._ar_pg: torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) self._rs_pg, rs_ranks = [],[] for i in range(self._num_process_groups): ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._num_groups): rs_idx = [j*self._group_size+k for k in range(self._group_size)] rs_rank = [ranks[k] for k in rs_idx] #if self._global_rank in rs_rank: # print("group for reduce scatter, ranks:", rs_rank) for _ in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=rs_rank) if self._global_rank in rs_rank: self._rs_pg.append(grp) if self._compute_L2_grad_norm: l2_grad_norm_pg = torch.distributed.new_group(ranks=rs_rank) if self._global_rank in rs_rank: self._l2_grad_norm_pg = l2_grad_norm_pg torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] for rs_pg in self._rs_pg: torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for i in range(self._num_process_groups): ranks = [i+k*self._num_process_groups for k in range(self._process_group_size)] for j in range(self._num_groups): ag_rank = rs_ranks[j] #if self._global_rank in ag_rank: # print("group for all gather, ranks:", ag_rank) for _ in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ag_rank) if self._global_rank in ag_rank: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] for ag_pg in self._ag_pg: torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() if self._compute_L2_grad_norm else None self._completion_st = torch.cuda.Stream() self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" def _init_everything(self): if not self._init_done: self._first_step_init() self._init_done = True def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Optionally compute L2 grad norm if self._compute_L2_grad_norm and block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) # for model_parallel_rank=0, keep all gradients # for the rest, subtract non_parallel gradients if self._model_parallel and self._process_group_id: # non zero model_parallel_rank non_parallel_grad_norm_sq = torch.zeros([1], device='cuda') if len(self._non_parallel_grads): # non parallel grads exit non_parallel_grad_norm_sq = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._non_parallel_grads], False)[0]**2 torch.distributed.all_reduce(non_parallel_grad_norm_sq, group=self._l2_grad_norm_pg) l2_grad_norm_sq = l2_grad_norm_sq - non_parallel_grad_norm_sq self._L2_grad_norm = l2_grad_norm_sq.sqrt().item() def __launch_step_kernel(self): # If self._clip_grad_norm is False, we assume gradient clipping already # happened outside the optimizer and self._global_scale has already # been set to the combined scale, i.e. it's no longer the current loss # scale used by the loss scaler. # For model parallelism cases in which we need to get global gradient # norm via all-reduce outside the optimizer to do the clipping. combined_scale = self._global_scale if self._clip_grad_norm and self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) self._step += 1 multi_tensor_applier(distributed_adam_cuda.multi_tensor_fused_adam, self._overflow_buf, self._contrib_tensor_list, # p, m, v, g, p_copy self._contrib_beta1, self._contrib_beta2, self._contrib_bias_correction, self._contrib_epsilon, self._contrib_weight_decay, self._param_group['lr'], combined_scale, self._step, self.eps_mode) def _pipeline_step(self): # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel() torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def has_overflow(self): """Check if overflows were detected by any call to step(...) method. Clears the overflow flag. """ has_overflow = self._has_overflow self._has_overflow = False return has_overflow @property def peek_overflow(self): """Check if overflows were detected by any call to step(...) method. Does not clear overflow flag. """ return self._has_overflow def strided_check_finite(self, output_params, stride=1, start=-1, end=-1, clear=True): """Strided check for overflow. You can get status by calling has_overflow. """ if start >= 0 and start < end: out_p = output_params[start:end] else: out_p = output_params fused_adam_cuda.strided_check_finite(self._overflow_buf, out_p, stride, 1 if clear else 0) self._has_overflow = False if self._overflow_buf.item() == 0 else True return self._has_overflow @property def L2_grad_norm(self): if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm else: return None def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ self._init_everything() if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None): loss = None if closure is not None: loss = closure() self._pipeline_step() with torch.cuda.stream(self._completion_st): # Copy self._new_params to model params multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss def state_dict(self): """ Returns a dict containing the current state of this :class:`DistributedFusedAdam` instance. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ # save step, master weights and first/second moments state_dict = {} state_dict['step'] = self._step state_dict['fp32_p'] = self._fp32_p state_dict['fp32_m'] = self._fp32_m state_dict['fp32_v'] = self._fp32_v return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If an DistributedFusedAdam instance was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``optimizer.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # restore step, master weights and first/second moments self._step = state_dict['step'] self._fp32_p = state_dict['fp32_p'].to(device="cuda") self._fp32_m = state_dict['fp32_m'].to(device="cuda") self._fp32_v = state_dict['fp32_v'].to(device="cuda") self._resume_from_checkpoint = True ================================================ FILE: KoSimCSE/apex/contrib/optimizers/distributed_fused_adam_v2.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier class DistributedFusedAdamV2(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) num_prestats (integer, optional): number of fp64 stats that will be reduced during first fp16 gradient reduction block. .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0, overlap_reductions=True, full_pipeline=True, compute_L2_grad_norm=False, distributed_weight_update=0, dwu_group_size=0, dwu_num_blocks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, revert_method=1, flat_mt=False, dwu_num_chunks=4, predivide=True, e5m2_allgather=False, do_not_flatten_model=False): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._amp_scale_adjustment = amp_scale_adjustment if use_mt: raise RuntimeError('DistributedFusedAdam does not support use_mt.') if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdamV2, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False assert (len(self.param_groups) == 1), "More than one parameter group is not supported." # Way to revert a step # 3 -> undo kernel + double buffer (debug, print norm of difference) # 2 -> double buffer fp32 parameters # 1 -> undo kernel self._revert_method = revert_method if self._revert_method > 1: print("revert_method -> double buffer fp32 parameters, will consume more memory") self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._full_pipeline = full_pipeline self._compute_L2_grad_norm = compute_L2_grad_norm self._L2_grad_norm = None self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size p_offset = 0 p_i = 0 self._param_state = None self._model_params = [] self._grads_info = [] self._grad_accs = [] for group in self.param_groups: self._param_group = group prev = None for p in group['params']: torch.distributed.broadcast(p,0) if not p.requires_grad: continue self._model_params.append(p) state = self.state[p] if len(state) == 0: state['step'] = 0 if self._param_state is None: self._param_state = state p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._flat_mt = flat_mt self._grads = [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._shard_size = self._block_size // self._group_size self._chunk_size = self._shard_size // self._num_chunks print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._shard_size=%d, self._chunk_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._shard_size,self._chunk_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._chunk_size self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') self._individual_flat_grads = [] for p_i, (grads_info, p) in enumerate(zip(self._grads_info, self._model_params)): self._individual_flat_grads.append(self._flat_grads[grads_info["param_offset"]:grads_info["param_offset"]+grads_info["param_grads_size"]].view_as(p)) def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_shards = [__shardify(block) for block in list_of_blocks] list_of_list_of_list_of_chunks = [[__chunkify(shard) for shard in shards] for shards in list_of_list_of_shards] return list_of_blocks, list_of_list_of_shards, list_of_list_of_list_of_chunks self._flat_grads_blocks, self._flat_grads_shards, self._flat_grads_chunks = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._chunk_size:(block_id+1)*self._num_chunks*self._chunk_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._chunk_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) # current arrangement # # self._flat_grads # self._flat_grads_blocks [x self._num_blocks, self._block_size] # self._flat_grads_chunks [x self._num_chunks, self._chunk_size] # self._flat_grads_shards [x self._group_size, self._shard_size] # # self._new_params # self._new_params_mega_shards [x self._group_size, self._num_blocks*self._num_chunks*self._shard_size] # self._new_params_mega_blocks [x self._num_blocks, self._num_chunks*self._shard_size] # self._new_params_mega_chunks [x self._num_chunks, self._shard_size] # # self._fp32_p # self._fp32_p_blocks [x self._num_blocks, self._num_chunks*self._shard_size] # self._fp32_p_chunks [x self._num_chunks, self._shard_size] # each chunk contains one shard # same for self._fp32_m, self._fp32_v, self._fp16_p and self._fp16_g # # Usage: # # for chunk_id in range(self._num_chunks): # works[chunk_id] = torch.distributed.reduce_scatter(self._flat_grads_chunks[block_id][chunk_id], self._fp16_g_chunks[block_id][chunk_id], ...) # # ---------------------------------------------------------------------------------------- # # new arrangement # # NB! New equations for self._shard_size and self._chunk_size # # self._flat_grads # self._flat_grads_blocks [x self._num_blocks, self._block_size] # self._flat_grads_shards [x self._group_size, self._shard_size] # self._flat_grads_chunks [x self._num_chunks, self._chunk_size] # # self._new_params # self._new_params_mega_shards [x self._group_size, self._num_blocks*self._num_chunks*self._chunk_size] # self._new_params_mega_blocks [x self._num_blocks, self._num_chunks*self._chunk_size] # self._new_params_mega_chunks [x self._num_chunks, self._chunk_size] # # self._fp32_p # self._fp32_p_blocks [x self._num_blocks, self._num_chunks*self._chunk_size] # self._fp32_p_chunks [x self._num_chunks, self._chunk_size] # same for self._fp32_m, self._fp32_v, self._fp16_p and self._fp16_g # # Usage: # # work = torch.distributed.reduce_scatter(self._flat_grads_blocks[block_id], self._fp16_g[block_id], ...) # for chunk_id in range(self._num_chunks): # work.wait() # works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id], ...) # or # work.wait() # works[0] = torch.distributed.all_reduce(self._fp16_g_blocks[block_id], ...) # # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): flat_shard_start = (block_id * self._group_size + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for p, grads_info in zip(self._model_params, self._grads_info): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_blocks[shard_id][block_id][shard_offset:shard_offset+grad_length] self._packed_flat_to_model_params.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._rank_in_group: # copy model parameters into master buffer master_param_fragment = self._fp32_p_blocks[block_id][shard_offset:shard_offset+grad_length] print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) master_param_fragment.copy_(model_param_fragment) p_in, p_out = zip(*self._packed_flat_to_model_params) self._packed_flat_to_model_params = [p_in, p_out] self._distributed_weight_update = distributed_weight_update # Is this still needed? self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg if self._num_groups > 1: self._ar_pg = [] for dev_i in range(self._group_size): ranks = [dev_i+j*self._group_size for j in range(self._num_groups)] for i in range(self._num_ar_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] for ar_pg in self._ar_pg: torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) rs_ranks = [] for group_i in range(self._num_groups): rs_ranks.append([group_i*self._group_size+j for j in range(self._group_size)]) self._rs_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._rs_pg.append(grp) if self._compute_L2_grad_norm and torch.distributed.get_rank() in ranks: self._l2_grad_norm_pg = torch.distributed.new_group(ranks=ranks) torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] for rs_pg in self._rs_pg: torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] for ag_pg in self._ag_pg: torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() if self._compute_L2_grad_norm else None self._completion_st = torch.cuda.Stream() self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks rs_stream = self._rs_st[block_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): rs_work = torch.distributed.reduce_scatter(self._fp16_g_blocks[block_id],self._flat_grads_shards[block_id],group=self._rs_pg[block_id%self._num_rs_pg],async_op=True,no_copy=True) for chunk_id in range(self._num_chunks): works[chunk_id] = rs_work # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): rs_work.wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Optionally compute L2 grad norm if self._compute_L2_grad_norm and block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) self._L2_grad_norm = l2_grad_norm_sq.sqrt().item() def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def _pipeline_block_step(self, block_id): # Call step kernel once per block ag_stream = self._ag_st[block_id%self._num_ag_pg] with torch.cuda.stream(ag_stream): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel( self._fp32_p_blocks[block_id], self._fp16_p_blocks[block_id], self._fp32_m_blocks[block_id], self._fp32_v_blocks[block_id], self._fp16_g_blocks[block_id]) # Call all-gather once per step. # FIXME: Determine which is faster, one all-gather per block or a single all-gather at end if block_id == 0: for other_ag_stream in self._ag_st: self._completion_st.wait_stream(other_ag_stream) with torch.cuda.stream(self._completion_st): torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _pipeline_step(self): # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() self.__launch_step_kernel( self._fp32_p, self._fp16_p, self._fp32_m, self._fp32_v, self._fp16_g) torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) if self._full_pipeline: self._pipeline_block_step(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def has_overflow(self): """Check if overflows were detected by any call to step(...) method. Clears the overflow flag. """ has_overflow = self._has_overflow self._has_overflow = False return has_overflow @property def peek_overflow(self): """Check if overflows were detected by any call to step(...) method. Does not clear overflow flag. """ return self._has_overflow def strided_check_finite(self, output_params, stride=1, start=-1, end=-1, clear=True): """Strided check for overflow. You can get status by calling has_overflow. """ if start >= 0 and start < end: out_p = output_params[start:end] else: out_p = output_params fused_adam_cuda.strided_check_finite(self._overflow_buf, out_p, stride, 1 if clear else 0) self._has_overflow = False if self._overflow_buf.item() == 0 else True return self._has_overflow @property def L2_grad_norm(self): if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm else: return None def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) if self._compute_L2_grad_norm: torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def revert_step(self): """Revert effect of previously calling partial_step. """ # Call undo kernel once per step combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.maybe_adam_undo( torch.empty([0]), self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def step(self, closure=None, skip_overflow_check=False): loss = None if closure is not None: loss = closure() if self._last_step or not self._overlap_reductions or not self._full_pipeline: self._pipeline_step() with torch.cuda.stream(self._completion_st): # Check for overflow # Store state for loss scaler calculation has_overflow = False if skip_overflow_check else self.strided_check_finite(self._new_params, stride=self._shard_size, start=0, end=self._net_total_param_size) if has_overflow: self.revert_step() else: # Copy self._new_params to model params for p in self._model_params: self.state[p]['step'] += 1 multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss ================================================ FILE: KoSimCSE/apex/contrib/optimizers/distributed_fused_adam_v3.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier class DistributedFusedAdamV3(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) overlap_reductions(boolean, optional): whether to overlap reductions with bprop (default: True) num_prestats (integer, optional): number of fp64 stats that will be reduced during first fp16 gradient reduction block. .. _Adam\: A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0, overlap_reductions=True, full_pipeline=True, compute_L2_grad_norm=False, distributed_weight_update=0, dwu_group_size=0, dwu_num_blocks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, revert_method=1, flat_mt=False, dwu_num_chunks=4, predivide=True, e5m2_allgather=False, do_not_flatten_model=False): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._amp_scale_adjustment = amp_scale_adjustment if use_mt: raise RuntimeError('DistributedFusedAdam does not support use_mt.') if amsgrad: raise RuntimeError('DistributedFusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(DistributedFusedAdamV3, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 self._overflow_buf = torch.cuda.IntTensor([0]) assert (len(self.param_groups) == 1), "More than one parameter group is not supported." # Way to revert a step # 3 -> undo kernel + double buffer (debug, print norm of difference) # 2 -> double buffer fp32 parameters # 1 -> undo kernel self._revert_method = revert_method if self._revert_method > 1: print("revert_method -> double buffer fp32 parameters, will consume more memory") self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._predivide = predivide self._e5m2_allgather = e5m2_allgather self._do_not_flatten_model = do_not_flatten_model self._full_pipeline = full_pipeline self._L2_grad_norm = None self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size p_offset = 0 p_i = 0 self._param_state = None self._model_params = [] self._grads_info = [] self._grad_accs = [] for group in self.param_groups: self._param_group = group prev = None for p in group['params']: torch.distributed.broadcast(p,0) if not p.requires_grad: continue self._model_params.append(p) state = self.state[p] if len(state) == 0: state['step'] = 0 if self._param_state is None: self._param_state = state p_grads_size = p.numel() def wrapper(param, param_i, param_grads_size, param_offset): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): self._do_overlapped_reduction(param_i, param_grads_size, param_offset, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) wrapper(p, p_i, p_grads_size, p_offset) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._grads_info) self._flat_mt = flat_mt self._grads = [] self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._shard_size = self._total_param_size // self._group_size print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._shard_size)) self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i print(self._low_param_i) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._flat_params = torch.zeros_like(self._flat_grads) def _flat_split(flat): def __flat_blockify(flat): return [flat[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __flat_shardify(flat): return [flat[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] return __flat_blockify(flat), __flat_shardify(flat) self._flat_grads_blocks, self._flat_grads_shards = _flat_split(self._flat_grads) self._flat_params_blocks, self._flat_params_shards = _flat_split(self._flat_params) # master params self._fp32_p = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._shard_size], dtype=torch.float32, device='cuda') # copy model params to flat_params and set_ model params to flat_params. self._individual_flat_grads = [] with torch.no_grad(): for p, grads_info in zip(self._model_params, self._grads_info): start = grads_info["param_offset"] end = start + grads_info["param_grads_size"] flat_p = self._flat_params[start:end].view_as(p) flat_p.copy_(p) p.set_(flat_p) flat_grad = self._flat_grads[start:end] self._individual_flat_grads.append(flat_grad) self._fp32_p.copy_(self._flat_params_shards[self._rank_in_group].float()) self._dwu_st = torch.cuda.Stream() self._l2_grad_norm_st = torch.cuda.Stream() for group_i in range(self._num_groups): ranks = [group_i*self._group_size+local_rank for local_rank in range(self._group_size)] pg = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg = pg torch.distributed.all_reduce(self._overflow_buf, group=self._ag_pg) import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" @property def has_overflow(self): return True if not self.L2_grad_norm is None and not math.isfinite(self.L2_grad_norm) else False def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def __launch_step_kernel(self, p, p_copy, m, v, g): combined_scale = self._global_scale if self._param_group['max_grad_norm'] > 0 and math.isfinite(self.L2_grad_norm): combined_scale = self._param_group['max_grad_norm'] / (self.L2_grad_norm / self._global_scale + 1e-6) combined_scale = self._global_scale / min(1, combined_scale) bias_correction = 1 if self._param_group['bias_correction'] else 0 beta1, beta2 = self._param_group['betas'] fused_adam_cuda.reversible_adam( p, p_copy, m, v, g, self._param_group['lr'], beta1, beta2, self._param_group['eps'], combined_scale, self._param_state['step']+1, self.eps_mode, bias_correction, self._param_group['weight_decay']) def _flatten_grad_mt(self, scale): if self._flat_mt and len(self._grads) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads)), scale) self._grads = [] def _do_overlapped_reduction(self, param_i, param_grads_size, param_offset, param): # handle overlapped reductions if self._flat_mt: self._grads.append( (param.grad, self._individual_flat_grads[param_i]) ) else: torch.div(param.grad, self._world_size if self._predivide else 1.0, out=self._individual_flat_grads[param_i]) self._grads_generated[param_i]=True if not self._last_step and self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._dwu_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._dwu_st): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) torch.distributed.all_reduce(self._flat_grads_blocks[block_id]) if block_id == 0: self._l2_grad_norm_st.wait_stream(self._dwu_st) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float32, p=2).item() flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def L2_grad_norm(self): torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, flat_grad in enumerate(self._individual_flat_grads): if not self._grads_generated[param_i]: flat_grad.zero_() self._grads_generated[param_i] = True if self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions self._dwu_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._dwu_st): self._flatten_grad_mt(1.0/self._world_size if self._predivide else 1.0) torch.distributed.all_reduce(self._flat_grads) self._l2_grad_norm_st.wait_stream(self._dwu_st) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float32, p=2).item() self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None, skip_overflow_check=False): loss = None if closure is not None: loss = closure() with torch.cuda.stream(self._dwu_st): self.__launch_step_kernel( self._fp32_p, self._flat_params_shards[self._rank_in_group], self._fp32_m, self._fp32_v, self._flat_grads_shards[self._rank_in_group]) torch.distributed.all_gather(self._flat_params_shards, self._flat_params_shards[self._rank_in_group], group=self._ag_pg, no_copy=True) for p in self._model_params: self.state[p]['step'] += 1 torch.cuda.current_stream().wait_stream(self._dwu_st) return loss ================================================ FILE: KoSimCSE/apex/contrib/optimizers/distributed_fused_lamb.py ================================================ import math import torch import importlib import amp_C from apex.multi_tensor_apply import multi_tensor_applier import torch.distributed.distributed_c10d as c10d class DistributedFusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) use_nvlamb (boolean, optional): Apply adaptive learning rate to 0.0 weight decay parameter (default: False) step_supports_amp_scaling(boolean, optional): whether to use customized gradient unscaling logic (default: True) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ class AtomicCounter(object): def __init__(self): self.value = 0 self.order = [] import threading self._lock = threading.Lock() def add(self, idx): with self._lock: self.value += 1 self.order.append(idx) def __init__(self, params, lr=1e-3, bias_correction = True, grad_averaging=True, betas=(0.9, 0.999), eps=1e-8, weight_decay=0., max_grad_norm=0., adam_w_mode=True, use_nvlamb=False, step_supports_amp_scaling=True, overlap_reductions=True, dwu_group_size=0, dwu_num_blocks=4, dwu_num_chunks=4, dwu_num_rs_pg=1, dwu_num_ar_pg=4, dwu_num_ag_pg=0, e5m2_allgather=False, verbose=False, clip_after_ar=True): defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(DistributedFusedLAMB, self).__init__(params, defaults) global fused_adam_cuda, distributed_lamb_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") distributed_lamb_cuda = importlib.import_module("distributed_lamb_cuda") self._overflow_buf = torch.cuda.IntTensor([0]) self._has_overflow = False self.multi_tensor_lamb_compute_update_term = distributed_lamb_cuda.multi_tensor_lamb_compute_update_term self.multi_tensor_lamb_update_weights = distributed_lamb_cuda.multi_tensor_lamb_update_weights import amp_C self.multi_tensor_l2norm = amp_C.multi_tensor_l2norm self._grad_averaging = grad_averaging self._adam_w_mode = 1 if adam_w_mode else 0 self._use_nvlamb = use_nvlamb self._step_supports_amp_scaling = step_supports_amp_scaling self._is_accumulation_step = False self._last_step = False self._overlap_reductions = overlap_reductions self._global_scale = None self._num_blocks = dwu_num_blocks self._num_chunks = dwu_num_chunks self._e5m2_allgather = e5m2_allgather self._verbose = verbose self._clip_after_ar = clip_after_ar self._L2_grad_norm = None self._current_process_group = c10d._get_default_group() self._available_ranks = list(c10d._pg_group_ranks[self._current_process_group].keys()) self._group_size = torch.cuda.device_count() if dwu_group_size <= 0 else dwu_group_size self._world_size = torch.distributed.get_world_size() self._num_groups = self._world_size // self._group_size self._rank_in_group = torch.distributed.get_rank() % self._group_size self._lr = torch.tensor(0.0, dtype=torch.float32, device='cuda') self._resume_from_checkpoint = False self._step = torch.cuda.IntTensor([0]) # Master weight, moment, gradient buffers self._fp32_p, self._fp32_m, self._fp32_v, self._fp16_p, self._fp16_g = None, None, None, None, None import inspect assert ('no_copy' in inspect.getfullargspec(torch.distributed.reduce_scatter).args), "This version of c10d does not support no_copy option" self._num_rs_pg = dwu_num_rs_pg self._num_ar_pg = dwu_num_ar_pg self._num_ag_pg = dwu_num_ag_pg if self._num_groups > 1: self._ar_pg = [] for dev_i in range(self._group_size): ranks = [dev_i+j*self._group_size for j in range(self._num_groups)] for i in range(self._num_ar_pg): if self._verbose: print(f"creating new group {i}: {ranks}") grp = torch.distributed.new_group(ranks=ranks) if grp != torch.distributed.GroupMember.NON_GROUP_MEMBER: if self._verbose: print(f"group {i}: init barrier (device: {torch.cuda.current_device()})") torch.distributed.barrier(group=grp, device_ids=[torch.cuda.current_device()]) if self._verbose: print(f"created new group {i}") if torch.distributed.get_rank() in ranks: self._ar_pg.append(grp) self._ar_st = [torch.cuda.Stream() for _ in range(self._num_ar_pg)] #for ar_pg in self._ar_pg: # torch.distributed.all_reduce(self._overflow_buf,group=ar_pg) rs_ranks = [] for group_i in range(self._num_groups): rs_ranks.append([group_i*self._group_size+j for j in range(self._group_size)]) self._rs_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_rs_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._rs_pg.append(grp) l2_grad_norm_pg = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._l2_grad_norm_pg = l2_grad_norm_pg #torch.distributed.all_reduce(self._overflow_buf,group=self._l2_grad_norm_pg) self._rs_st = [torch.cuda.Stream() for _ in range(self._num_rs_pg)] #for rs_pg in self._rs_pg: # torch.distributed.all_reduce(self._overflow_buf,group=rs_pg) if self._num_ag_pg == 0: self._ag_pg = self._rs_pg self._ag_st = self._rs_st self._num_ag_pg = self._num_rs_pg else: self._ag_pg = [] for group_i in range(self._num_groups): ranks = rs_ranks[group_i] for i in range(self._num_ag_pg): grp = torch.distributed.new_group(ranks=ranks) if torch.distributed.get_rank() in ranks: self._ag_pg.append(grp) self._ag_st = [torch.cuda.Stream() for _ in range(self._num_ag_pg)] #for ag_pg in self._ag_pg: # torch.distributed.all_reduce(self._overflow_buf,group=ag_pg) self._l2_grad_norm_st = torch.cuda.Stream() self._completion_st = torch.cuda.Stream() self._step.record_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks self._one = torch.cuda.IntTensor([1]) self._first_step = True self._lazy_init_stage1_done, self._lazy_init_stage2_done = False, False self._param_order = self.AtomicCounter() def _lazy_init_stage1(self): if self._lazy_init_stage1_done: return p_offset = 0 p_i = 0 self._model_params = [] self._grad_accs = [] self._group_properties = [] for group in self.param_groups: prev = None beta1, beta2 = group['betas'] beta3 = 1.0 - beta1 if self._grad_averaging else 1.0 bias_correction = 1 if group['bias_correction'] else 0 eps = group['eps'] weight_decay = group['weight_decay'] for p in group['params']: torch.distributed.broadcast(p, 0) if not p.requires_grad: continue self._model_params.append(p) self._group_properties.append(( weight_decay, bias_correction, beta1, beta2, beta3, eps )) p_grads_size = p.numel() def wrapper(param, param_i): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): if self._first_step: # first time self._param_order.add(param_i) else: idx = self._param_order.order.index(param_i) self._do_overlapped_reduction(idx, param) grad_acc.register_hook(allreduce_hook) self._grad_accs.append(grad_acc) wrapper(p, p_i) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p p_i += 1 self._grads_generated = [False]*len(self._model_params) self._grads_fp16, self._grads_fp32 = [], [] if self._overlap_reductions: self._current_block = self._num_blocks self._net_total_param_size = p_offset self._total_param_size = p_offset dwu_min_page_size = 256 * self._num_blocks * self._num_chunks * self._group_size self._total_param_size = ((self._total_param_size + dwu_min_page_size - 1) // dwu_min_page_size) * dwu_min_page_size self._block_size = self._total_param_size // self._num_blocks self._chunk_size = self._block_size // self._num_chunks self._shard_size = self._chunk_size // self._group_size #print("self._net_total_param_size=%d, self._total_param_size=%d, dwu_min_page_size=%d, self._block_size=%d, self._chunk_size=%d, self._shard_size=%d" % (self._net_total_param_size, self._total_param_size,dwu_min_page_size,self._block_size,self._chunk_size,self._shard_size)) self._flat_grads = torch.zeros([self._total_param_size], dtype=torch.float16, device='cuda') self._new_params = torch.zeros([self._total_param_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._mega_shard_size = self._num_blocks * self._num_chunks * self._shard_size # initialize master weights, moments buffers if not loaded from checkpoint if self._fp32_p is None: self._fp32_p = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_m = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_v = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') self._fp32_u = torch.zeros([self._mega_shard_size], dtype=torch.float32, device='cuda') # FIXME: Rethink fp16 label since it's either uint8 or fp16 self._fp16_p = torch.zeros([self._mega_shard_size], dtype=torch.uint8 if self._e5m2_allgather else torch.float16, device='cuda') self._fp16_g = torch.zeros([self._mega_shard_size], dtype=torch.float16, device='cuda') def _flat_split(p): def __blockify(p): return [p[block_id*self._block_size:(block_id+1)*self._block_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._chunk_size:(chunk_id+1)*self._chunk_size] for chunk_id in range(self._num_chunks)] def __shardify(p): return [p[shard_id*self._shard_size:(shard_id+1)*self._shard_size] for shard_id in range(self._group_size)] list_of_blocks = __blockify(self._flat_grads) list_of_list_of_chunks = [__chunkify(block) for block in list_of_blocks] list_of_list_of_list_of_shards = [[__shardify(chunk) for chunk in chunks] for chunks in list_of_list_of_chunks] return list_of_blocks, list_of_list_of_chunks, list_of_list_of_list_of_shards self._flat_grads_blocks, self._flat_grads_chunks, self._flat_grads_shards = _flat_split(self._flat_grads) def _full_packed_split(p): def __shardify(p): return [p[mega_shard*self._mega_shard_size:(mega_shard+1)*self._mega_shard_size] for mega_shard in range(self._group_size)] def __blockify(p): return [p[block_id*self._num_chunks*self._shard_size:(block_id+1)*self._num_chunks*self._shard_size] for block_id in range(self._num_blocks)] def __chunkify(p): return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_mega_shards = __shardify(p) list_of_list_of_mega_blocks = [__blockify(mega_shard) for mega_shard in list_of_mega_shards] list_of_list_of_list_of_mega_chunks = [[__chunkify(mega_block) for mega_block in mega_blocks] for mega_blocks in list_of_list_of_mega_blocks] return list_of_mega_shards, list_of_list_of_mega_blocks, list_of_list_of_list_of_mega_chunks self._new_params_mega_shards, self._new_params_mega_blocks, self._new_params_mega_chunks = _full_packed_split(self._new_params) def _packed_split(p): def __packed_blockify(p): packed_block_size = self._num_chunks*self._shard_size return [p[block_id*packed_block_size:(block_id+1)*packed_block_size] for block_id in range(self._num_blocks)] def __packed_chunkify(p): # in the packed format, each chunk contains one shard, so packed_chunk_size == self._shard_size return [p[chunk_id*self._shard_size:(chunk_id+1)*self._shard_size] for chunk_id in range(self._num_chunks)] list_of_blocks = __packed_blockify(p) list_of_list_of_chunks = [__packed_chunkify(block) for block in list_of_blocks] return list_of_blocks, list_of_list_of_chunks self._fp32_p_blocks, self._fp32_p_chunks = _packed_split(self._fp32_p) self._fp32_m_blocks, self._fp32_m_chunks = _packed_split(self._fp32_m) self._fp32_v_blocks, self._fp32_v_chunks = _packed_split(self._fp32_v) self._fp32_u_blocks, self._fp32_u_chunks = _packed_split(self._fp32_u) self._fp16_p_blocks, self._fp16_p_chunks = _packed_split(self._fp16_p) self._fp16_g_blocks, self._fp16_g_chunks = _packed_split(self._fp16_g) self._lazy_init_stage1_done = True def _lazy_init_stage2(self): if self._lazy_init_stage2_done: return self._param_order.order.reverse() # re-order model_params, grad_accs, group_properties lists self._model_params = [self._model_params[i] for i in self._param_order.order] self._grad_accs = [self._grad_accs[i] for i in self._param_order.order] self._group_properties = [self._group_properties[i] for i in self._param_order.order] # re-collect grads info (size, offset) after ordering prev = None p_offset = 0 self._grads_info = [] self._individual_flat_grads = [] for i, p in enumerate(self._model_params): p_grads_size = p.numel() self._grads_info.append({"param_grads_size":p_grads_size, "param_offset":p_offset}) self._individual_flat_grads.append(self._flat_grads[p_offset:p_offset+p_grads_size].view_as(p)) # for the first iteration self._do_overlapped_reduction(i, p) p_offset += p_grads_size # Only enforce 128b alignment (64 * fp16) for non-consecutive parameters # RNN is one example of consecutive parameters: # (weight_ih, weight_hh, bias_ih, bias_hh) if prev is not None and (prev.data_ptr() + prev.numel() * prev.element_size() != p.data_ptr()): p_offset = ((p_offset + 63) // 64) * 64 prev = p self._low_param_i = [0]*self._num_blocks for block_id in range(self._num_blocks-1,-1,-1): p_i = len(self._grads_info)-1 while p_i > 0 and self._grads_info[p_i]["param_offset"] > block_id*self._block_size: p_i -= 1 self._low_param_i[block_id] = p_i #print("self._low_param_i", self._low_param_i) # This paragraph does two things: # 1) Copy model parameters into master buffer # 2) Create tensor lists for unpacking new parameter tensor after all-gather self._packed_flat_to_model_params_fp16 = [] self._packed_flat_to_model_params_fp32 = [] self._model_params_num = len(self._model_params) self._contrib_tensor_list = [] self._contrib_min_param_i, self._contrib_max_param_i = -1, -1 self._contrib_update_frag_for_norm = [] self._contrib_model_param_for_norm_fp16 = [] self._contrib_model_param_for_norm_fp32 = [] self._contrib_model_param_for_norm_is_fp16 = [] self._model_param_is_contrib = [] self._contrib_group_properties = [] for shard_id in range(self._group_size): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): flat_shard_start = (((block_id * self._num_chunks + chunk_id) * self._group_size) + shard_id) * self._shard_size flat_shard_end = flat_shard_start + self._shard_size for param_i, (p, grads_info, group_props) in enumerate(zip(self._model_params, self._grads_info, self._group_properties)): flat_grad_start = grads_info["param_offset"] flat_grad_end = flat_grad_start + grads_info["param_grads_size"] clipped_start = (lambda a,b: a if a > b else b)(flat_grad_start, flat_shard_start) clipped_end = (lambda a,b: a if a < b else b)(flat_grad_end, flat_shard_end) if clipped_start < clipped_end: grad_offset = clipped_start - flat_grad_start grad_length = clipped_end - clipped_start shard_offset = clipped_start - flat_shard_start model_param_fragment = p.view(-1)[grad_offset:grad_offset+grad_length] new_param_packed_fragment = self._new_params_mega_chunks[shard_id][block_id][chunk_id][shard_offset:shard_offset+grad_length] if model_param_fragment.dtype == torch.float16: self._packed_flat_to_model_params_fp16.append( (new_param_packed_fragment, model_param_fragment) ) else: self._packed_flat_to_model_params_fp32.append( (new_param_packed_fragment, model_param_fragment) ) if shard_id == self._rank_in_group: self._model_param_is_contrib.append(param_i) # copy model parameters into master buffer master_param_fragment = self._fp32_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_m_fragment = self._fp32_m_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_v_fragment = self._fp32_v_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_u_fragment = self._fp32_u_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_g_fragment = self._fp16_g_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] opti_state_p_fragment = self._fp16_p_chunks[block_id][chunk_id][shard_offset:shard_offset+grad_length] #print("model_param_fragment.size()=%s, new_param_packed_fragment.size()=%s, master_param_fragment.size()=%s" % (str(model_param_fragment.size()), str(new_param_packed_fragment.size()), str(master_param_fragment.size()))) if not self._resume_from_checkpoint: master_param_fragment.copy_(model_param_fragment) self._contrib_group_properties.append(group_props) self._contrib_tensor_list.append((master_param_fragment, opti_state_m_fragment, opti_state_v_fragment, opti_state_u_fragment, opti_state_g_fragment, opti_state_p_fragment)) # p, m, v, u, g, p_copy self._contrib_update_frag_for_norm.append(opti_state_u_fragment) if p.dtype == torch.float16: self._contrib_model_param_for_norm_fp16.append(p) else: self._contrib_model_param_for_norm_fp32.append(p) self._contrib_model_param_for_norm_is_fp16.append(True if p.dtype == torch.float16 else False) if self._contrib_min_param_i < 0: self._contrib_min_param_i = param_i self._contrib_max_param_i = param_i self._contrib_model_param_for_norm_num = len(self._contrib_model_param_for_norm_is_fp16) if len(self._contrib_model_param_for_norm_fp16) == 0: self._contrib_model_param_for_norm_fp16 = None if len(self._contrib_model_param_for_norm_fp32) == 0: self._contrib_model_param_for_norm_fp32 = None self._contrib_model_param_for_norm_is_fp32 = torch.tensor([not is_fp16 for is_fp16 in self._contrib_model_param_for_norm_is_fp16], dtype=torch.bool, device='cuda') self._contrib_model_param_for_norm_is_fp16 = torch.tensor([is_fp16 for is_fp16 in self._contrib_model_param_for_norm_is_fp16], dtype=torch.bool, device='cuda') self._offsets = torch.tensor(self._model_param_is_contrib, dtype=torch.int64, device='cuda') p, m, v, u, g, p_copy = list(zip(*self._contrib_tensor_list)) self._contrib_compute_update_term_tensor_list = [g, p, m, v, u] self._contrib_update_weights_tensor_list = [u, p, p_copy] math_type = self._fp32_u.dtype decay, bias_correction, beta1, beta2, beta3, epsilon = list(zip(*self._contrib_group_properties)) self._contrib_beta1 = torch.tensor(beta1, dtype=math_type, device='cuda') self._contrib_beta2 = torch.tensor(beta2, dtype=math_type, device='cuda') self._contrib_beta3 = torch.tensor(beta3, dtype=math_type, device='cuda') self._contrib_bias_correction = torch.tensor(bias_correction, dtype=torch.int, device='cuda') self._contrib_epsilon = torch.tensor(epsilon, dtype=math_type, device='cuda') self._contrib_weight_decay = torch.tensor(decay, dtype=math_type, device='cuda') self._packed_flat_to_model_params_fp16 = list(zip(*self._packed_flat_to_model_params_fp16)) if len(self._packed_flat_to_model_params_fp16) > 0 else None self._packed_flat_to_model_params_fp32 = list(zip(*self._packed_flat_to_model_params_fp32)) if len(self._packed_flat_to_model_params_fp32) > 0 else None self._lazy_init_stage2_done = True self.complete_reductions() self._first_step = False def set_is_accumulation_step(self, is_accumulation_step): self._is_accumulation_step = is_accumulation_step def set_last_step(self, last_step): self._last_step = last_step def _get_flush_block(self): flush_block = [] if self._current_block > 0 and self._grads_generated[self._low_param_i[self._current_block-1]]: num_grads = len(self._grads_generated) contiguous_idx = num_grads while contiguous_idx > 0 and self._grads_generated[contiguous_idx-1]: contiguous_idx -= 1 if contiguous_idx < num_grads and self._grads_info[contiguous_idx]["param_offset"] <= (self._current_block-1)*self._block_size: self._current_block -= 1 start = self._current_block * self._block_size end = (self._current_block+1) * self._block_size flush_block = [start, end] return flush_block def _pipeline_block_reductions(self, block_id): if self._clip_after_ar: self._flatten_grad_mt(1.0/self._world_size) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works # Compute L2 grad norm if block_id == 0: with torch.cuda.stream(self._l2_grad_norm_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() # Since the packed format is contiguous after reductions, only one norm is needed l2_grad_norm_sq = torch.empty([1], device='cuda') l2_grad_norm_sq = self._fp16_g.norm(dtype=torch.float32, p=2)**2 torch.distributed.all_reduce(l2_grad_norm_sq, group=self._l2_grad_norm_pg) self._L2_grad_norm = l2_grad_norm_sq.sqrt() else: # Copy model grads to flat grads buffer self._flatten_grad_mt(1.0) # Compute L2 grad norm self._l2_grad_norm_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._l2_grad_norm_st): self._L2_grad_norm = self._flat_grads.norm(dtype=torch.float16, p=2).float() torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) # Apply clipping & pre-reduction scaling on grads loss_scale = self.global_scale max_grad_norm = loss_scale*self.defaults['max_grad_norm'] coeff = max_grad_norm /(1e-6+self.L2_grad_norm) coeff = (coeff>1) * self._one + (coeff<=1) * coeff tmp = torch.cat(((self._one), (coeff))) index = (coeff+1>coeff).int() scale = tmp.index_select(0, index).half()/self._world_size self._flat_grads.mul_(scale) # Reduction within each node # Changes gradient format from [block * chunk * shard] to [shard * block * chunk] # The output format is the same as the fp32 master parameters works = [None]*self._num_chunks for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id rs_stream = self._rs_st[glob_chunk_id%self._num_rs_pg] rs_stream.wait_stream(torch.cuda.current_stream()) rs_stream.wait_stream(self._l2_grad_norm_st) with torch.cuda.stream(rs_stream): works[chunk_id] = torch.distributed.reduce_scatter(self._fp16_g_chunks[block_id][chunk_id],self._flat_grads_shards[block_id][chunk_id],group=self._rs_pg[glob_chunk_id%self._num_rs_pg],async_op=True,no_copy=True) # Reduction across nodes for each rank if self._num_groups > 1: for chunk_id in range(self._num_chunks): glob_chunk_id = block_id * self._num_chunks + chunk_id ar_stream = self._ar_st[glob_chunk_id%self._num_ar_pg] with torch.cuda.stream(ar_stream): works[chunk_id].wait() works[chunk_id] = torch.distributed.all_reduce(self._fp16_g_chunks[block_id][chunk_id],group=self._ar_pg[glob_chunk_id%self._num_ar_pg],async_op=True) self._reductions_works[block_id] = works if block_id == 0: for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() def __compute_contrib_param_norm(self): if self._contrib_model_param_for_norm_fp16 is not None and self._contrib_model_param_for_norm_fp32 is not None: gnorm_fp16 = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp16], True)[1] gnorm_fp32 = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp32], True)[1] gnorm = torch.empty(size=[self._contrib_model_param_for_norm_num], dtype=torch.bool, device='cuda') gnorm.masked_scatter_(self._contrib_model_param_for_norm_is_fp16, gnorm_fp16) gnorm.masked_scatter_(self._contrib_model_param_for_norm_is_fp32, gnorm_fp32) elif self._contrib_model_param_for_norm_fp16 is not None: gnorm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp16], True)[1] elif self._contrib_model_param_for_norm_fp32 is not None: gnorm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_model_param_for_norm_fp32], True)[1] return gnorm def __compute_contrib_update_norm(self): l2_norm = torch.zeros(size=[self._model_params_num], dtype=torch.float32, device='cuda') local_contrib_l2_norm = multi_tensor_applier(self.multi_tensor_l2norm, self._overflow_buf, [self._contrib_update_frag_for_norm], True)[1] ** 2 l2_norm.scatter_(dim=0, index=self._offsets, src=local_contrib_l2_norm) torch.distributed.all_reduce(l2_norm, group=self._ag_pg[0]) l2_norm = torch.sqrt(l2_norm) return l2_norm def _pipeline_step(self): global_scale = self.global_scale # if clip before ar, set max_grad_norm to 0 max_grad_norm = self.defaults['max_grad_norm'] * self._clip_after_ar self._completion_st.wait_stream(self._l2_grad_norm_st) global_grad_norm = self.L2_grad_norm # check global_grad_norm and fill overflow_buf is_finite = (global_grad_norm + 1 > global_grad_norm).int() self._overflow_buf = self._one * (is_finite ^ self._one) # toggle between 0 and 1 torch.distributed.all_reduce(is_finite, op=torch.distributed.ReduceOp.MIN, group=self._current_process_group) torch.distributed.all_reduce(self._overflow_buf, op=torch.distributed.ReduceOp.MAX, group=self._current_process_group) # increment step counter if no overflow self._step += is_finite self._completion_st.wait_stream(torch.cuda.current_stream()) self._completion_st.wait_stream(self._l2_grad_norm_st) # Call step kernel once per step # Call all-gather once per step with torch.cuda.stream(self._completion_st): for block_id in range(self._num_blocks): for chunk_id in range(self._num_chunks): self._reductions_works[block_id][chunk_id].wait() param_norm = self.__compute_contrib_param_norm() multi_tensor_applier(self.multi_tensor_lamb_compute_update_term, self._overflow_buf, self._contrib_compute_update_term_tensor_list, # g, p, m, v, u self._contrib_beta1, self._contrib_beta2, self._contrib_beta3, self._contrib_bias_correction, self._step, self._contrib_epsilon, self._adam_w_mode, self._contrib_weight_decay, global_scale, global_grad_norm, max_grad_norm) upd_norm = self.__compute_contrib_update_norm() multi_tensor_applier(self.multi_tensor_lamb_update_weights, self._overflow_buf, self._contrib_update_weights_tensor_list, # u, p, p_copy param_norm, upd_norm, self._offsets, self._lr, self._contrib_weight_decay, global_grad_norm, self._use_nvlamb) torch.distributed.all_gather(self._new_params_mega_shards, self._fp16_p, group=self._ag_pg[0], no_copy=True) def _flatten_grad_mt(self, scale): if len(self._grads_fp16) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads_fp16)), scale) self._grads_fp16 = [] if len(self._grads_fp32) > 0: self._overflow_buf.zero_() multi_tensor_applier( amp_C.multi_tensor_scale, self._overflow_buf, list(zip(*self._grads_fp32)), scale) self._grads_fp32 = [] def _do_overlapped_reduction(self, param_i, param): if not self._is_accumulation_step: # handle overlapped reductions if param.dtype == torch.float16: self._grads_fp16.append( (param.grad, self._individual_flat_grads[param_i]) ) else: self._grads_fp32.append( (param.grad, self._individual_flat_grads[param_i]) ) self._grads_generated[param_i]=True if not self._first_step and not self._last_step: if self._overlap_reductions: flush_block = self._get_flush_block() while flush_block: block_id = flush_block[0] // self._block_size self._pipeline_block_reductions(block_id) flush_block = self._get_flush_block() def set_global_scale(self, global_scale): """Set global scale. """ self._global_scale = global_scale @property def global_scale(self): return self._global_scale @property def L2_grad_norm(self): torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) return self._L2_grad_norm def complete_reductions(self): """Complete reductions if full pipeline is not selected or overlap is not allowed. """ if self._last_step: # zero out gradients that have not been completed yet for param_i, grad_generated in enumerate(self._grads_generated): if not grad_generated: grad_info = self._grads_info[param_i] param_offset = grad_info["param_offset"] param_size = grad_info["param_grads_size"] self._flat_grads[param_offset:param_offset+param_size].zero_() self._grads_generated[param_i] = True if self._first_step or self._last_step or not self._overlap_reductions: # nothing done so far, run full pipeline after reductions for block_id in range(self._num_blocks-1,-1,-1): self._pipeline_block_reductions(block_id) torch.cuda.current_stream().wait_stream(self._l2_grad_norm_st) self._current_block = self._num_blocks self._grads_generated = [False]*len(self._grads_info) def step(self, closure=None, grad_scaler=None): loss = None if closure is not None: loss = closure() self._pipeline_step() if grad_scaler is not None: found_inf = self._overflow_buf.float() optimizer_state = grad_scaler._per_optimizer_states[id(self)] current_device = torch.device('cuda', torch.cuda.current_device()) optimizer_state["found_inf_per_device"][current_device] = found_inf self._completion_st.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(self._completion_st): # Copy self._new_params to model params with torch.no_grad(): if self._packed_flat_to_model_params_fp16 is not None: multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params_fp16) if self._packed_flat_to_model_params_fp32 is not None: multi_tensor_applier( fused_adam_cuda.maybe_cast_mt, self._overflow_buf, self._packed_flat_to_model_params_fp32) torch.cuda.current_stream().wait_stream(self._completion_st) self._reductions_works = [None]*self._num_blocks self._allgather_works = [None]*self._num_blocks return loss def state_dict(self): """ Returns a dict containing the current state of this :class:`DistributedFusedAdam` instance. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ # save step, master weights and first/second moments state_dict = {} state_dict['step'] = self._step state_dict['fp32_p'] = self._fp32_p state_dict['fp32_m'] = self._fp32_m state_dict['fp32_v'] = self._fp32_v return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If an DistributedFusedAdam instance was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``optimizer.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # restore step, master weights and first/second moments self._step = state_dict['step'] self._fp32_p = state_dict['fp32_p'].to(device="cuda") self._fp32_m = state_dict['fp32_m'].to(device="cuda") self._fp32_v = state_dict['fp32_v'].to(device="cuda") self._resume_from_checkpoint = True ================================================ FILE: KoSimCSE/apex/contrib/optimizers/fp16_optimizer.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FP16_Optimizer(object): """ :class:`FP16_Optimizer` A cutdown version of apex.fp16_utils.FP16_Optimizer. Designed only to wrap apex.contrib.optimizers.FusedAdam, FusedSGD. Refer to apex.fp16_utils documents for more information. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = apex.contrib.optimizers.FusedSGD(model.parameters()) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... # loss.backward() becomes: optimizer.backward(loss) ... Example with dynamic loss scaling:: ... optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True) # optional arg to control dynamic loss scaling behavior # dynamic_loss_args={'scale_window' : 500}) # Usually, dynamic_loss_args is not necessary. """ def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=True): print("\nThis fp16_optimizer is designed to only work with apex.contrib.optimizers.*") print("To update, use updated optimizers with AMP.") # The fused optimizer does all the work. We need this layer for two reason: # 1. maintain same user API from apex.fp16_utils # 2. keep common stuff here in case we need to add new fused optimizer later if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.optimizer = init_optimizer self.fp16_groups = [] # model params self.fp32_groups = [] # master weights # iterate over param_groups for param_group in self.optimizer.param_groups: fp16_group = [] fp32_group = [] for p in param_group['params']: fp16_group.append(p) fp32_group.append(p.clone().float().detach()) self.fp16_groups.append(fp16_group) self.fp32_groups.append(fp32_group) param_group['params'] = fp32_group if multi_tensor_applier.available: import amp_C self.overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm else: raise RuntimeError('FP16_Optimizer requires cuda extensions') # we may have a way of fusing dynamic scale. Do not support for now if dynamic_loss_scale: if dynamic_loss_args is not None: raise SystemError("Do not support dynamic loss scale args for now.") self.dynamic_loss_scale = True self.cur_scale = 2**16 self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = 2 self.scale_window = 1000 else: self.dynamic_loss_scale = False self.cur_iter = 0 self.cur_scale = static_loss_scale self.verbose = verbose def zero_grad(self, set_grads_to_None=True): """ Zero FP16 parameter grads. """ # FP32 grad should never exist. # For speed, set model fp16 grad to None by default for group in self.fp16_groups: for p in group: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() def step(self, closure=None): """ Not supporting closure. """ fp16_grads = [] norm_groups = [] skip = False for group in self.fp16_groups: fp16_grad = [] for i, p in enumerate(group): fp16_grad.append(p.grad) fp16_grads.append(fp16_grad) # nan check self.overflow_buf.zero_() for fp16_grad in fp16_grads: if len(fp16_grad) > 0: norm, norm_per_tensor = multi_tensor_applier(self.multi_tensor_l2norm, self.overflow_buf, [fp16_grad], True) norm_groups.append(norm) if self.overflow_buf.item() != 0: skip = True if skip: self._update_scale(skip) return # norm is in fact norm*cur_scale self.optimizer.step(grads=fp16_grads, output_params=self.fp16_groups, scale=self.cur_scale, grad_norms=norm_groups) self._update_scale(False) return def backward(self, loss): """ :attr:`backward` performs the following steps: 1. fp32_loss = loss.float() 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's fp16 leaves """ scaled_loss = (loss.float()) * self.cur_scale scaled_loss.backward() def _update_scale(self, skip): if self.dynamic_loss_scale: if skip: if self.verbose: print("\nGrad overflow on iteration", self.cur_iter) print("Using dynamic loss scale of", self.cur_scale) self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor else: if skip: print("\nGrad overflow on iteration", self.cur_iter) print("Using static loss scale of", self.cur_scale) self.cur_iter +=1 return # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups) def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['cur_scale'] = self.cur_scale state_dict['cur_iter'] = self.cur_iter if state_dict['dynamic_loss_scale']: state_dict['last_overflow_iter'] = self.last_overflow_iter state_dict['scale_factor'] = self.scale_factor state_dict['scale_window'] = self.scale_window state_dict['optimizer_state_dict'] = self.optimizer.state_dict() state_dict['fp32_groups'] = self.fp32_groups return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.cur_scale = state_dict['cur_scale'] self.cur_iter = state_dict['cur_iter'] if state_dict['dynamic_loss_scale']: self.last_overflow_iter = state_dict['last_overflow_iter'] self.scale_factor = state_dict['scale_factor'] self.scale_window = state_dict['scale_window'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) # At this point, the optimizer's references to the model's fp32 parameters are up to date. # The optimizer's hyperparameters and internal buffers are also up to date. # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still # out of date. There are two options. # 1: Refresh the master params from the model's fp16 params. # This requires less storage but incurs precision loss. # 2: Save and restore the fp32 master copies separately. # We choose option 2. # # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device # of their associated parameters, because it's possible those buffers might not exist yet in # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been # constructed in the same way as the one whose state_dict we are loading, the same master params # are guaranteed to exist, so we can just copy_() from the saved master params. for current, saved in zip(self.fp32_groups, state_dict['fp32_groups']): for _current, _saved in zip(current, saved): _current.data.copy_(_saved.data) ================================================ FILE: KoSimCSE/apex/contrib/optimizers/fused_adam.py ================================================ import types import torch import importlib from apex.multi_tensor_apply import multi_tensor_applier class FusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``python setup.py install --cuda_ext --cpp_ext``. It has been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! eps_inside_sqrt (boolean, optional): in the 'update parameters' step, adds eps to the bias-corrected second moment estimate before evaluating square root instead of adding it to the square root of second moment estimate as in the original paper. (default: False) use_mt (boolean, optional): use multi tensor apply for lower launch latency. (default: False) .. _Adam - A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction = True, betas=(0.9, 0.999), eps=1e-8, eps_inside_sqrt = False, weight_decay=0., max_grad_norm=0., amsgrad=False, use_mt=False, amp_scale_adjustment=1.0): global fused_adam_cuda fused_adam_cuda = importlib.import_module("fused_adam_cuda") self._use_multi_tensor = False if use_mt: if not multi_tensor_applier.available: print("Warning: multi_tensor_applier is unavailable") else: self._use_multi_tensor = True self._overflow_buf = torch.cuda.IntTensor([0]) self._amp_scale_adjustment = amp_scale_adjustment if amsgrad: raise RuntimeError('FusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(FusedAdam, self).__init__(params, defaults) self.eps_mode = 0 if eps_inside_sqrt else 1 def step(self, closure=None, grads=None, output_params=None, scale=1., grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use for the optimizer update. If gradients have type torch.half, parameters are expected to be in type torch.float. (default: None) output params (list of tensors, optional): A reduced precision copy of the updated weights written out in addition to the regular updated weights. Have to be of same type as gradients. (default: None) scale (float, optional): factor to divide gradient tensor values by before applying to weights. (default: 1) """ loss = None if closure is not None: loss = closure() if hasattr(self, "_amp_stash"): grads = self._amp_stash.grads output_params = self._amp_stash.output_params scale = self._amp_stash.scale*self._amp_scale_adjustment grad_norms = self._amp_stash.grad_norms if grads is None: grads_group = [None]*len(self.param_groups) # backward compatibility # assuming a list/generator of parameter means single group elif isinstance(grads, types.GeneratorType): grads_group = [grads] elif type(grads[0])!=list: grads_group = [grads] else: grads_group = grads if output_params is None: output_params_group = [None]*len(self.param_groups) elif isinstance(output_params, types.GeneratorType): output_params_group = [output_params] elif type(output_params[0])!=list: output_params_group = [output_params] else: output_params_group = output_params if grad_norms is None: grad_norms = [None]*len(self.param_groups) for group, grads_this_group, output_params_this_group, grad_norm in zip(self.param_groups, grads_group, output_params_group, grad_norms): if grads_this_group is None: grads_this_group = [None]*len(group['params']) if output_params_this_group is None: output_params_this_group = [None]*len(group['params']) # compute combined scale factor for this group combined_scale = scale if group['max_grad_norm'] > 0: # norm is in fact norm*scale clip = ((grad_norm / scale) + 1e-6) / group['max_grad_norm'] if clip > 1: combined_scale = clip * scale bias_correction = 1 if group['bias_correction'] else 0 if self._use_multi_tensor: if output_params: tensorlists = [[],[],[],[],[]] else: tensorlists = [[],[],[],[]] tensordevice = None for p, grad, output_param in zip(group['params'], grads_this_group, output_params_this_group): #note: p.grad should not ever be set for correct operation of mixed precision optimizer that sometimes sends None gradients if p.grad is None and grad is None: continue if grad is None: grad = p.grad.data if grad.is_sparse: raise RuntimeError('FusedAdam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] beta1, beta2 = group['betas'] state['step'] += 1 out_p = torch.tensor([], dtype = torch.float) if output_param is None else output_param if self._use_multi_tensor: pl = [p.data, exp_avg, exp_avg_sq, grad] if output_param is not None: pl.append(out_p) for tl, t in zip(tensorlists, pl): tl.append(t) if tensordevice is None: tensordevice = p.device elif tensordevice != p.device: raise RuntimeError('FusedAdam does not support use_mt with tensors on multiple device') else: with torch.cuda.device(p.device): fused_adam_cuda.adam(p.data, out_p, exp_avg, exp_avg_sq, grad, group['lr'], beta1, beta2, group['eps'], combined_scale, state['step'], self.eps_mode, bias_correction, group['weight_decay']) if self._use_multi_tensor: with torch.cuda.device(tensordevice): multi_tensor_applier( fused_adam_cuda.adam_mt, self._overflow_buf, tensorlists, group['lr'], beta1, beta2, group['eps'], combined_scale, state['step'], self.eps_mode, bias_correction, group['weight_decay']) return loss ================================================ FILE: KoSimCSE/apex/contrib/optimizers/fused_lamb.py ================================================ import torch import importlib import math from apex.multi_tensor_apply import multi_tensor_applier class FusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" --global-option="--deprecated_fused_lamb" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.contrib.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.contrib.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01, amsgrad=False, adam_w_mode=True, grad_averaging=True, set_grad_none=True, max_grad_norm=1.0): if amsgrad: raise RuntimeError('FusedLAMB does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(FusedLAMB, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm self._dummy_overflow_buf = torch.cuda.IntTensor([0]) fused_lamb_cuda = importlib.import_module("fused_lamb_cuda") self.multi_tensor_lamb = fused_lamb_cuda.lamb else: raise RuntimeError('apex.contrib.optimizers.FusedLAMB requires cuda extensions') self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedLAMB, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() # create separate grad lists for fp32 and fp16 params g_all_32, g_all_16 = [], [] for group in self.param_groups: for p in group['params']: if p.grad is None: continue if p.dtype == torch.float32: g_all_32.append(p.grad.data) elif p.dytpe == torch.float16: g_all_16.append(p.grad.data) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') g_norm_32, g_norm_16 = 0.0, 0.0 # compute grad norm for two lists if len(g_all_32) > 0: g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_32], False)[0].item() if len(g_all_16) > 0: g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_16], False)[0].item() # blend two grad norms to get global grad norm global_grad_norm = math.sqrt(g_norm_32 * g_norm_32 + g_norm_16 * g_norm_16) max_grad_norm = self.defaults['max_grad_norm'] for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedLAMB does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm) return loss ================================================ FILE: KoSimCSE/apex/contrib/optimizers/fused_sgd.py ================================================ import types import torch from torch.optim.optimizer import Optimizer, required from apex.multi_tensor_apply import multi_tensor_applier class FusedSGD(Optimizer): r"""Implements stochastic gradient descent (optionally with momentum). This version of fused SGD implements 2 fusions. * Fusion of the SGD update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.contrib.optimizers.FusedSGD` should be used without AMP. :class:`apex.contrib.optimizers.FusedSGD` only works in the case where all parameters require grad. Nesterov momentum is based on the formula from `On the importance of initialization and momentum in deep learning`__. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float): learning rate momentum (float, optional): momentum factor (default: 0) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) dampening (float, optional): dampening for momentum (default: 0) nesterov (bool, optional): enables Nesterov momentum (default: False) Example: model = ... model.half() optimizer = apex.contrib.optimizers.FusedSGD(model.parameters()) # wrap with FP16_Optimizer optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True) optimizer.zero_grad() ... optimizer.backward(loss) optmizer.step() __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf .. note:: The implementation of SGD with Momentum/Nesterov subtly differs from Sutskever et. al. and implementations in some other frameworks. Considering the specific case of Momentum, the update can be written as .. math:: v = \rho * v + g \\ p = p - lr * v where p, g, v and :math:`\rho` denote the parameters, gradient, velocity, and momentum respectively. This is in contrast to Sutskever et. al. and other frameworks which employ an update of the form .. math:: v = \rho * v + lr * g \\ p = p - v The Nesterov version is analogously modified. """ def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, wd_after_momentum=False, materialize_master_grads=True): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super(FusedSGD, self).__init__(params, defaults) self.wd_after_momentum = wd_after_momentum if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_sgd = amp_C.multi_tensor_sgd else: raise RuntimeError('apex.contrib.optimizers.FusedSGD requires cuda extensions') def __setstate__(self, state): super(FusedSGD, self).__setstate__(state) for group in self.param_groups: group.setdefault('nesterov', False) def get_momentums(self, params): momentums = [] first_run = True for p in params: param_state = self.state[p] # torch.optim.SGD initializes momentum in the main loop, we have # to do it here, and track whether or not we've done so, so that # momentum application can be skipped in the main kernel. if 'momentum_buffer' not in param_state: first_run = True buf = param_state['momentum_buffer'] = torch.zeros_like(p.data) momentums.append(buf) else: first_run = False momentums.append(param_state['momentum_buffer']) return momentums, first_run def step(self, closure=None, grads=None, output_params=None, scale=1., grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use for the optimizer update. If gradients have type torch.half, parameters are expected to be in type torch.float. (default: None) output_params (list of tensors, optional): A reduced precision copy of the updated weights written out in addition to the regular updated weights. Have to be of same type as gradients. (default: None) scale (float, optional): factor to divide gradient tensor values by before applying to weights. (default: 1) """ if hasattr(self, "_amp_stash"): raise RuntimeError('apex.contrib.optimizers.FusedSGD should not be used with AMP.') loss = None if closure is not None: loss = closure() if grads is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD must be wrapped \ with apex.contrib.optimizers.FP16_Optimizer \ which provides grads.') # backward compatibility # assuming a list/generator of parameter means single group elif isinstance(grads, types.GeneratorType): grads_group = [grads] elif type(grads[0])!=list: grads_group = [grads] else: grads_group = grads if output_params is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD must be wrapped \ with apex.contrib.optimizers.FP16_Optimizer \ which provides output_params.') elif isinstance(output_params, types.GeneratorType): output_params_group = [output_params] elif type(output_params[0])!=list: output_params_group = [output_params] else: output_params_group = output_params for group, grads_this_group, output_params_this_group in zip(self.param_groups, grads_group, output_params_group): if grads_this_group is None or output_params_this_group is None: raise RuntimeError('apex.contrib.optimizers.FusedSGD only works \ when all parameters require grad.') weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] lr = group['lr'] first_runs = [True, True] # output_params_this_group: original weights (either fp16 or fp32) # group['params']: master weights (fp32) # grad_type, param_to_update_type, momentum_type, requires_fp16_model_copy # fp32, fp32, fp32, No fp32_grads = [g for (p, g) in zip(output_params_this_group, grads_this_group) if p.dtype == torch.float32] fp32_params = [p2 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float32] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) fp32_set = [fp32_grads, fp32_params, fp32_momentums] # fp16, fp32, fp32, Yes fp16_grads = [g for (p, g) in zip(output_params_this_group, grads_this_group) if p.dtype == torch.float16] fp32_from_fp16_params = [p2 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float16] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_params = [p1 for (p1, p2) in zip(output_params_this_group, group['params']) if p1.dtype == torch.float16] fp16_set = [fp16_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_params] launch_sets = [fp16_set, fp32_set] for launch_set, first_run in zip(launch_sets, first_runs): assert len(launch_set[0]) == len(launch_set[1]) assert len(launch_set[0]) == len(launch_set[2]) if len(launch_set[0]) > 0: multi_tensor_applier( self.multi_tensor_sgd, self._dummy_overflow_buf, launch_set, weight_decay, momentum, dampening, lr, nesterov, first_run, self.wd_after_momentum, 1.0/scale) return loss ================================================ FILE: KoSimCSE/apex/contrib/sparsity/README.md ================================================ # Introduction to ASP This serves as a quick-start for ASP (Automatic SParsity), a tool that enables sparse training and inference for PyTorch models by adding 2 lines of Python. ## Importing ASP ``` from apex.contrib.sparsity import ASP ``` ## Initializing ASP Apart from the import statement, it is sufficient to add just the following line of code before the training phase to augment the model and the optimizer for sparse training/inference: ``` ASP.prune_trained_model(model, optimizer) ``` In the context of a typical PyTorch training loop, it might look like this: ``` ASP.prune_trained_model(model, optimizer) x, y = DataLoader(args) for epoch in range(epochs): y_pred = model(x) loss = loss_function(y_pred, y) loss.backward() optimizer.step() torch.save(...) ``` The `prune_trained_model` step calculates the sparse mask and applies it to the weights. This is done once, i.e., sparse locations in the weights matrix remain fixed after this step. ## Generate a Sparse Network The following approach serves as a guiding example on how to generate a pruned model that can use Sparse Tensor Cores in the NVIDIA Ampere Architecture. This approach generates a model for deployment, i.e. inference mode. ``` (1) Given a fully trained (dense) network, prune parameter values in a 2:4 sparse pattern. (2) Fine-tune the pruned model with optimization method and hyper-parameters (learning-rate, schedule, number of epochs, etc.) exactly as those used to obtain the trained model. (3) (If required) Quantize the model. ``` In code, below is a sketch on how to use ASP for this approach (steps 1 and 2 above). ``` model = define_model(..., pretrained=True) # define model architecture and load parameter tensors with trained values (by reading a trained checkpoint) criterion = ... # compare ground truth with model predition; use the same criterion as used to generate the dense trained model optimizer = ... # optimize model parameters; use the same optimizer as used to generate the dense trained model lr_scheduler = ... # learning rate scheduler; use the same schedule as used to generate the dense trained model from apex.contrib.sparsity import ASP ASP.prune_trained_model(model, optimizer) #pruned a trained model x, y = DataLoader(args) for epoch in range(epochs): # train the pruned model for the same number of epochs as used to generate the dense trained model y_pred = model(x) loss = criterion(y_pred, y) lr_scheduler.step() loss.backward() optimizer.step() torch.save(...) # saves the pruned checkpoint with sparsity masks ``` ## Non-Standard Usage If your goal is to easily perpare a network for accelerated inference, please follow the recipe above. However, ASP can also be used to perform experiments in advanced techniques like training with sparsity from initialization. For example, in order to recompute the sparse mask in between training steps, use the following method: ``` ASP.compute_sparse_masks() ``` A more thorough example can be found in `./test/toy_problem.py`. ================================================ FILE: KoSimCSE/apex/contrib/sparsity/__init__.py ================================================ from .sparse_masklib import create_mask from .asp import ASP ================================================ FILE: KoSimCSE/apex/contrib/sparsity/asp.py ================================================ import types import torch from .sparse_masklib import create_mask torchvision_imported=True try: import torchvision except ImportError: print("[ASP][Warning] torchvision cannot be imported.") torchvision_imported=False def eligible_modules(model, whitelist_layer_types, allowed_layer_names, disallowed_layer_names): eligible_modules_list = [] for name, mod in model.named_modules(): if isinstance(mod, whitelist_layer_types) and name not in disallowed_layer_names: if allowed_layer_names is not None and name not in allowed_layer_names: continue eligible_modules_list.append((name, mod)) return eligible_modules_list class ASP: __model = None __verbosity = 0 __optimizer = None __sparse_parameters = [] __calculate_mask = None @classmethod def init_model_for_pruning(cls, model, mask_calculator="m4n2_1d", verbosity=3, whitelist=[torch.nn.Linear, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d], allowed_layer_names=None, disallowed_layer_names=[], allow_recompute_mask=False, custom_layer_dict={}): """Call this method to modify your model to take advantage of sparse matrix multiplication. Note that this call alone only augments the model with additional buffers needed for sparse MMA, it does not enable use of sparse MMA. If you are starting with a fresh model: model = ... ASP.init_model_for_pruning(model, mask_calculator, ...) if (training) ASP.init_optimizer_for_pruning(optimizer) ASP.compute_sparse_masks() // sparsity is off by default, call when youy want to enable it. If you are starting from a checkpoint: model = ... ASP.init_model_for_pruning(model, mask_calculator, ...) torch.load(...) if (training) ASP.init_optimizer_for_pruning(optimizer) Arguments: model The model mask_calculator Either callable that computes mask given a tensor OR pattern string for sparse mask lib. verbosity Integer controling verbosity level. 0 -> Only errors. 1 -> Errors and warnings. 2 -> Errors, warnings and info. 3 -> Errors, warnings, info and debug. whitelist Module types approved for sparsity. allowed_layer_names If not None, only layer names that appear in this list are considered for sparsity. disallowed_layer_names If not [], only layer names that do not appear in this list are considered for sparsity. allow_recompute_mask If True, stores pruned values so that dense weights can be restored. Pruned weights are stored in CPU memory, hence this option does not increase GPU memory usage. custom_layer_dict Dictionary of additional layer paremeters to sparsify. e.g. {CustomLinear: ['weight']} [Future] Support for allow_recompute_mask can be removed, it is not part of sparse inference recipe -- AKM. """ assert (cls.__model is None), "ASP has been initialized already." cls.__model = model cls.__verbosity = verbosity if isinstance(mask_calculator, str): def create_mask_from_pattern(param): return create_mask(param, mask_calculator).bool() cls.__calculate_mask = create_mask_from_pattern else: cls.__calculate_mask = mask_calculator #user defined function # function to extract variables that will be sparsified. # idea is that you will add one of these functions for each module type that can be sparsified. if torchvision_imported: print("[ASP] torchvision is imported, can work with the MaskRCNN/KeypointRCNN from torchvision.") sparse_parameter_list = {torch.nn.Linear: ['weight'], torch.nn.Conv1d: ['weight'], torch.nn.Conv2d: ['weight'], torch.nn.Conv3d: ['weight'], torchvision.ops.misc.Conv2d: ['weight']} else: sparse_parameter_list = {torch.nn.Linear: ['weight'], torch.nn.Conv1d: ['weight'], torch.nn.Conv2d: ['weight'], torch.nn.Conv3d: ['weight']} if custom_layer_dict: # Update default list to include user supplied custom (layer type : parameter tensor), make sure this tensor type is something ASP knows how to prune sparse_parameter_list.update(custom_layer_dict) whitelist += list(custom_layer_dict.keys()) for module_type in whitelist: assert (module_type in sparse_parameter_list), "Module %s :: Don't know how to sparsify module." % module.dtype() # find all sparse modules, extract sparse parameters and decorate def add_sparse_attributes(module_name, module): sparse_parameters = sparse_parameter_list[type(module)] for p_name, p in module.named_parameters(): if p_name in sparse_parameters and p.requires_grad: # check for NVIDIA's TC compatibility: we check along the horizontal direction if p.dtype == torch.float32 and ((p.size()[0] % 8) != 0 or (p.size()[1] % 16) != 0): #User defines FP32 and APEX internally uses FP16 math print("[ASP] Auto skipping pruning %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) continue if p.dtype == torch.float16 and ((p.size()[0] % 8) != 0 or (p.size()[1] % 16) != 0): #For Conv2d dim= K x CRS; we prune along C print("[ASP] Auto skipping pruning %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) continue if cls.__verbosity >= 3: print("[ASP] Sparsifying %s::%s of size=%s and type=%s for sparsity" % (module_name, p_name, str(p.size()), str(p.dtype))) mask = torch.ones_like(p).bool() buffname = p_name.split(".")[-1] # buffer names cannot contain "." module.register_buffer('__%s_mma_mask' % buffname, mask) if allow_recompute_mask: pruned = torch.zeros_like(p).cpu() module.register_buffer('__%s_mma_pruned_p' % buffname, pruned) else: pruned = None cls.__sparse_parameters.append((module_name, module, p_name, p, mask, pruned)) else: if cls.__verbosity >= 3: print("[ASP] Not sparsifying %s::%s of size=%s and type=%s" % (module_name, p_name, str(p.size()), str(p.dtype))) for name, sparse_module in eligible_modules(model, tuple(whitelist), allowed_layer_names, disallowed_layer_names): add_sparse_attributes(name, sparse_module) @classmethod def init_optimizer_for_pruning(cls, optimizer): """Call this method to monkey patch optimizer step function so that masks can be applied to gradients and weights during training. You must call init_model_for_pruning(...) before calling init_optimizer_for_pruning(...) """ assert (cls.__optimizer is None), "ASP has initialized optimizer already." assert (cls.__calculate_mask is not None), "Called ASP.init_optimizer_for_pruning before ASP.init_model_for_pruning." # store pointer to original optimizer step method cls.__optimizer = optimizer cls.__optimizer.__step = optimizer.step def __step(opt_self, *args, **kwargs): # prune gradients before step method with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if p.grad is not None: #thx pjudd p.grad.mul_(mask) # call original optimizer step method rval = opt_self.__step(*args, **kwargs) # prune parameters after step method with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: p.mul_(mask) return rval cls.__optimizer.step = types.MethodType(__step, cls.__optimizer) @classmethod def compute_sparse_masks(cls): """Call this method to enable sparsity. If init(...) was called with allow_recompute_mask=False AND sparsity is disabled, pruned field can be None. """ with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if mask.sum() < mask.numel(): # when recalculating masks # restore dense parameter if allow_recompute_mask is enabled assert (pruned is not None), "Unable to restore dense parameter because allow_recompute_mask == False" p.add_(pruned.cuda()) mask.set_(cls.__calculate_mask(p)) if pruned is not None: # stow away pruned weights to cpu pruned.set_((p * (~mask)).cpu()) p.mul_(mask) # in-place multiplication, so pruned weights are 0-values, hence checkpoint will have 0s for pruned weights if cls.__verbosity >= 2: print("[ASP] Enabled %.2f%% sparsity for %s::%s of size=%s and type=%s" % (100.0*mask.sum()/mask.numel(), module_name, p_name, str(p.size()), str(p.dtype))) @classmethod def restore_pruned_weights(cls): """Call this method to disable sparsity and restore all weights. This will only work if init(...) was called with allow_recompute=True. """ with torch.no_grad(): for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: if mask.sum() < mask.numel(): assert (pruned is not None), "Unable to restore dense parameter because allow_recompute_mask == False" p.add_(pruned.cuda()) mask.fill_(1) pruned.zero_() if cls.__verbosity >= 2: print("[ASP] Disabled sparsity for %s::%s (dense weights restored)" % (module_name, p_name)) @classmethod def is_sparsity_enabled(cls): """Call this method to determine if sparsity is enabled in the model. The typical use case is right after checkpoint has been loaded. """ total,sp100,sp50 = 0,0,0 for module_name, module, p_name, p, mask, pruned in cls.__sparse_parameters: total += 1 mask_sum = mask.sum() mask_numel = mask.numel() if mask_sum == mask_numel: sp100 += 1 elif mask_sum*2 == mask_numel: sp50 += 1 assert (total == sp100 or total == sp50), "Inconsistent model sparsity" if total == sp100: return False elif total == sp50: return True @classmethod def prune_trained_model(cls, model, optimizer): # add mask buffers to model (init_model_for_pruning), augment optimizer (init_optimizer_for_pruning) and compute masks (compute_sparse_masks) cls.init_model_for_pruning(model, mask_calculator="m4n2_1d", verbosity=2, whitelist=[torch.nn.Linear, torch.nn.Conv2d], allow_recompute_mask=False) cls.init_optimizer_for_pruning(optimizer) cls.compute_sparse_masks() ================================================ FILE: KoSimCSE/apex/contrib/sparsity/sparse_masklib.py ================================================ import sys import torch import numpy as np import collections from itertools import permutations """ compute density (helper fn to compute % NNZs in a tensor) """ def fill(x): return float(x.nonzero().size(0))/torch.numel(x) """ reshape matrix into m-dimensional vectors: (h,w) -> (hw/m, m) """ def reshape_1d(matrix, m): # If not a nice multiple of m, fill with zeroes. if matrix.shape[1] % m > 0: mat = torch.cuda.FloatTensor(matrix.shape[0], matrix.shape[1] + (m-matrix.shape[1]%m)).fill_(0) mat[:, :matrix.shape[1]] = matrix shape = mat.shape return mat.view(-1,m),shape else: return matrix.view(-1,m), matrix.shape """ return all possible m:n patterns in a 1d vector """ valid_m4n2_1d_patterns = None def compute_valid_1d_patterns(m,n): # Early exit if patterns was already created. global valid_m4n2_1d_patterns if m==4 and n==2 and valid_m4n2_1d_patterns is not None: return valid_m4n2_1d_patterns patterns = torch.zeros(m) patterns[:n] = 1 valid_patterns = torch.Tensor(list(set(permutations(patterns.tolist())))) if m == 4 and n == 2: valid_m4n2_1d_patterns = valid_patterns return valid_patterns """ m:n 1d structured best """ def mn_1d_best(matrix, m, n): # Find all possible patterns. patterns = compute_valid_1d_patterns(m,n).cuda() # Find the best m:n pattern (sum of non-masked weights). mask = torch.cuda.IntTensor(matrix.shape).fill_(1).view(-1,m) mat,shape = reshape_1d(matrix,m) pmax = torch.argmax(torch.matmul(mat.abs(),patterns.t()), dim=1) mask[:] = patterns[pmax[:]] mask = mask.view(matrix.shape) return mask def m4n2_1d(mat, density): return mn_1d_best(mat, 4, 2) """ Below 2d-masking related code is targeted more for training (from scratch). 2d-pruning of a weight tensor is done to accelerate DGRAD step during backprop phase of training algorithm. Acceleration comes from using SpMMA instructions in Tensor Cores of NVIDIA Ampere GPU Architecture (note: this code does not do the acceleration, GPU kernels are required for this). 1d pruning of weight tensor helps speed up FPROP step by pruning in 2:4 pattern along the horizontal (logical) direction. During DGRAD step, weight tensor is transposed. 2d pruning functions below, mask weight tensor such that their transposed versions are also 2:4 sparse along the horizontal (logical) direction. Thus, with 2d pruning, weight tensors are 2:4 sparse along row and column directions. """ """ m:n 2d structured pruning: greedy method to select mask """ def mn_2d_greedy(matrix, m, n): # Convert to numpy mat = matrix.cpu().detach().numpy() mask = np.ones(mat.shape, dtype=int) rowCount = int(mat.shape[0]/m) * m colCount = int(mat.shape[1]/m) * m for rowStartIdx in range(0, rowCount, m): rowEndIdx = rowStartIdx + m for colStartIdx in range(0, colCount, m): colEndIdx = colStartIdx + m matrixSub = np.absolute(np.squeeze(mat[rowStartIdx:rowEndIdx, colStartIdx:colEndIdx])) maskSub = np.squeeze(mask[rowStartIdx:rowEndIdx, colStartIdx:colEndIdx]) maskSub.fill(0.0) matrixVecView = matrixSub.reshape(-1) maskVecView = maskSub.reshape(-1) linearIdx = np.argsort(matrixVecView) matrixIdx = [(int(x/m), x % m) for x in linearIdx] rowCounter = collections.Counter() colCounter = collections.Counter() for currIdx in range(len(linearIdx) - 1, -1, -1): currMatrixEntry = matrixIdx[currIdx] if (rowCounter[currMatrixEntry[0]] == n) or (colCounter[currMatrixEntry[1]] == n): continue #end if maskSub[currMatrixEntry[0], currMatrixEntry[1]] = 1.0 rowCounter[currMatrixEntry[0]] += 1 colCounter[currMatrixEntry[1]] += 1 return torch.tensor(mask.cuda()) def m4n2_2d_greedy(mat, density): return mn_2d_greedy(mat, 4, 2) """ return all possible m:n patterns in a mxn block. """ valid_m4n2_2d_patterns = None def compute_valid_2d_patterns(m,n): # Early exit if patterns was already created. global valid_m4n2_2d_patterns if valid_m4n2_2d_patterns is not None: return valid_m4n2_2d_patterns patterns = torch.zeros(m) patterns[:n] = 1 patterns = list(set(permutations(patterns.tolist()))) patterns = patterns + patterns patterns = torch.Tensor(list(set(permutations(patterns,m)))) valid = ((patterns.sum(dim=1) <= n).sum(dim=1) == m).nonzero().view(-1) valid_patterns = torch.Tensor(valid.shape[0],m,m) valid_patterns[:] = patterns[valid[:]] if m == 4 and n == 2: valid_m4n2_2d_patterns = valid_patterns return valid_patterns """ m:n 2d structured pruning: exhaustive method to select best mask """ def mn_2d_best(matrix, m, n): # Find all possible patterns. patterns = compute_valid_2d_patterns(m,n).cuda() # Find the best m:n pattern (sum of non-masked weights). mask = torch.cuda.IntTensor(matrix.shape).fill_(1) mat = reshape_2d(matrix,m,m).abs() pmax = torch.argmax(torch.matmul(mat,patterns.view(patterns.shape[0],m*m).t()), dim=2) # Copy best m:n patterns into mask. mat = mat.view(mat.shape[0]*mat.shape[1],-1) pmax = pmax.view(pmax.shape[0]*pmax.shape[1]).unsqueeze(1).expand(-1,mat.shape[1]) patterns = patterns.view(patterns.shape[0],patterns.shape[1]*patterns.shape[2]) mat = torch.gather(patterns,0,pmax) mat = reshape_2d_inv(mat.view(matrix.shape[0]//m,matrix.shape[1]//m,m,m)) mask.copy_(mat.type(mask.type())) return mask def m4n2_2d_best(mat, density): return mn_2d_best(mat, 4, 2) """ returns a sparse mask """ def create_mask(tensor, pattern="m4n2_1d", density=0.5): # Reshape tensor and mask. shape = tensor.shape ttype = tensor.type() t = tensor.float().contiguous() # 1d-tensor if len(shape) == 1: t = t.view(1, shape[0]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 2d-tensor (in, out) elif len(shape) == 2: t = t.view(shape[0], shape[1]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 3d-tensor (batch, in, out) elif len(shape) == 3: t = t.view(shape[0]*shape[1], shape[2]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) # 4d-tensor (in, out, h, w) elif len(shape) == 4: """ # transformers (bmm) t = t.view(shape[0]*shape[1]*shape[2], shape[3]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) return mask.view(shape).type(ttype) """ # convs t = t.permute(2,3,0,1).contiguous().view(shape[2]*shape[3]*shape[0], shape[1]) func = getattr(sys.modules[__name__], pattern, None) mask = func(t, density) mask = mask.view(shape[2], shape[3], shape[0], shape[1]).permute(2,3,0,1).contiguous() return mask.view(shape).type(ttype) ================================================ FILE: KoSimCSE/apex/contrib/sparsity/test/checkpointing_test_part1.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): # # PART1 # torch.manual_seed(args.seed) model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, verbosity=args.verbosity, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.enable_sparsity() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) torch.save({ 'step': step, 'verbosity': args.verbosity, 'seed2': args.seed2, 'pattern': args.pattern, 'whitelist': args.whitelist, 'allow_recompute_mask': args.allow_recompute_mask, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), }, args.checkpoint_path) if __name__ == '__main__': class Args: verbosity=3 seed = 4873 seed2 = 99875 pattern = "m4n2_2d_best" whitelist = [torch.nn.Linear] allow_recompute_mask = True batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(args) ================================================ FILE: KoSimCSE/apex/contrib/sparsity/test/checkpointing_test_part2.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(step, args, model_state_dict, optimizer_state_dict): # # PART2 # model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, verbosity=args.verbosity, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) torch.manual_seed(args.seed2) model.load_state_dict(model_state_dict) optimizer.load_state_dict(optimizer_state_dict) print("Model sparsity is %s" % ("enabled" if ASP.sparsity_is_enabled() else "disabled")) # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) if __name__ == '__main__': checkpoint = torch.load("part1.chkp") class Args: verbosity = checkpoint['verbosity'] seed = 4873 seed2 = checkpoint['seed2'] pattern = checkpoint['pattern'] whitelist = checkpoint['whitelist'] allow_recompute_mask = checkpoint['allow_recompute_mask'] batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(checkpoint['step'], args, checkpoint['model_state_dict'], checkpoint['optimizer_state_dict']) ================================================ FILE: KoSimCSE/apex/contrib/sparsity/test/checkpointing_test_reference.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP # # Reference run for checkpointing test (part1 + part2) # def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): # # PART1 # torch.manual_seed(args.seed) model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) ASP.init_model_for_pruning(model, args.pattern, whitelist=args.whitelist, allow_recompute_mask=args.allow_recompute_mask) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.enable_sparsity() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) # # PART 2 # torch.manual_seed(args.seed2) # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) if __name__ == '__main__': class Args: seed = 4873 seed2 = 99875 pattern = "m4n2_2d_best" whitelist = [torch.nn.Linear] allow_recompute_mask = True batch_size = 32 input_features = 8 output_features = 8 hidden_features = 32 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 checkpoint_path = "part1.chkp" args = Args() main(args) ================================================ FILE: KoSimCSE/apex/contrib/sparsity/test/toy_problem.py ================================================ from collections import OrderedDict import torch from apex.optimizers import FusedAdam from apex.contrib.sparsity import ASP def build_model(args): od = OrderedDict() for i in range(args.num_layers): if i == 0: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) elif i == args.num_layers-1: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.output_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.output_features]) else: od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.hidden_features, args.hidden_features) od['layer_norm_%d' % (i+1)] = torch.nn.LayerNorm([args.batch_size, args.hidden_features]) return torch.nn.Sequential(od) def train_step(args, model, optimizer, input_batch, target_batch, step): predicted_target = model(input_batch) loss = ((predicted_target-target_batch)**2).sum() loss.backward() optimizer.step() optimizer.zero_grad() step = step + 1 #print("Step %d :: loss=%e" % (step, loss.item())) return step def train_loop(args, model, optimizer, step, num_steps): for i in range(num_steps): input_batch = torch.randn([args.batch_size, args.input_features]).cuda() target_batch = torch.randn([args.batch_size, args.output_features]).cuda() step = train_step(args, model, optimizer, input_batch, target_batch, step) return step def main(args): model = build_model(args).cuda() one_ll = next(model.children()).weight optimizer = FusedAdam(model.parameters()) # only prune linear layers, even though we also support conv1d, conv2d and conv3d ASP.init_model_for_pruning(model, "m4n2_1d", whitelist=[torch.nn.Linear], allow_recompute_mask=True) ASP.init_optimizer_for_pruning(optimizer) step = 0 # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps) # simulate sparsity by inserting zeros into existing dense weights ASP.compute_sparse_masks() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps) # recompute sparse masks ASP.compute_sparse_masks() # train for a few steps with sparse weights print("SPARSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_sparse_steps_2) # turn off sparsity print("SPARSE :: ",one_ll) ASP.restore_pruned_weights() # train for a few steps with dense weights print("DENSE :: ",one_ll) step = train_loop(args, model, optimizer, step, args.num_dense_steps_2) if __name__ == '__main__': class Args: batch_size = 32 input_features = 16 output_features = 8 hidden_features = 40 num_layers = 4 num_dense_steps = 2000 num_sparse_steps = 3000 num_sparse_steps_2 = 1000 num_dense_steps_2 = 1500 args = Args() main(args) ================================================ FILE: KoSimCSE/apex/contrib/test/fmha/test_fmha.py ================================================ ############################################################################### # Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the NVIDIA CORPORATION nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ############################################################################### import sys import torch import numpy as np import unittest import math import fmhalib as mha def py_mha(qkv, amask, b, s, h, d): qkv = qkv.view(b, s, h, 3, d) q = qkv[:, :, :, 0, :].permute(0,2,1,3) k = qkv[:, :, :, 1, :].permute(0,2,1,3) v = qkv[:, :, :, 2, :].permute(0,2,1,3) p = torch.matmul(q.float(), k.permute(0,1,3,2).float()) p_masked = p / math.sqrt(d) + (1.0 - amask) * -10000.0 s = torch.softmax(p_masked, -1).to(qkv.dtype) ctx = torch.matmul(s, v) ctx = ctx.permute(0,2,1,3).contiguous() ctx.retain_grad() return ctx class TestFMHA(unittest.TestCase): def run_test(self, s, b): print(f'Test s={s} b={b}') torch.manual_seed(1234) torch.cuda.manual_seed(1234) dtype = torch.float16 device = torch.device('cuda') h = 16 d = 64 slens = [s] * b a = torch.tensor(np.array([0] + slens), dtype=torch.int32) amask = torch.ones(b,h,s,s, dtype=dtype, device=device) seqlens = torch.tensor(slens, dtype=torch.int32, device=device) cu_seqlens = torch.cumsum(a, 0).to(dtype=torch.int32, device=device) total = cu_seqlens[-1].item() qkv = torch.randn((b,s,h,3,d), device=device, dtype=dtype) qkv_vs = qkv.permute(0,1,3,2,4).contiguous().view(b*s, 3, h,d) qkv.requires_grad = True if b < 4: ctx, S_ = mha.fwd_nl(qkv_vs, cu_seqlens, 0.0, s, True, None) else: ctx, S_ = mha.fwd(qkv_vs, cu_seqlens, 0.0, s, True, None) ctx = ctx.view(b,s,h,d) ctx_ref = py_mha(qkv, amask, b,s,h,d) self.assertTrue(torch.allclose(ctx_ref.float(), ctx.float(), atol=1e-3)) labels = torch.randn_like(ctx_ref) diff = ctx_ref - labels l = (diff * diff).sum() / b l.backward() dw = ctx_ref.grad.permute(0,2,1,3) dw2 = dw.permute(0,2,1,3).clone().detach().contiguous() if b < 4: dqkv2, _, _ = mha.bwd_nl(dw2, qkv_vs, S_, cu_seqlens, 0.0, s) else: dqkv2, _ = mha.bwd(dw2, qkv_vs, S_, cu_seqlens, 0.0, s) dqkv2 = dqkv2.permute(0,2,1,3).view(b,s, h,3,d) self.assertTrue(torch.allclose(qkv.grad.float(), dqkv2.float(), atol=1e-3)) def test_128(self): self.run_test(128, 32) def test_256(self): self.run_test(256, 32) def test_384(self): self.run_test(384, 32) def test_512(self): self.run_test(512, 32) self.run_test(512, 2) self.run_test(512, 3) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/layer_norm/test_fast_layer_norm.py ================================================ import torch import unittest import numpy as np import torch.nn.functional as F from apex.contrib.layer_norm import FastLayerNorm import fast_layer_norm as fln class GPUTimer: def __init__(self, stream): self.start_ = torch.cuda.Event(enable_timing=True) self.stop_ = torch.cuda.Event(enable_timing=True) self.stream_ = stream def start(self): self.stream_.record_event(self.start_) def stop(self): self.stream_.record_event(self.stop_) def sync(self): self.stream_.synchronize() def millis(self): return self.start_.elapsed_time(self.stop_) def size_in_bytes(t): return torch.numel(t) * t.element_size() def abs_err(x, y): xf = x.float() yf = y.float() return ((xf-yf).abs().sum() / yf.abs().sum()).item() class TestFastLayerNorm(unittest.TestCase): def setUp(self, seed=1234): seed = 1234 torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def test_ln_fp32(self): self.run_test_layer_norm(torch.float32, atol=1e-5) def test_ln_fp16(self): self.run_test_layer_norm(torch.float16, atol=1e-2, rtol=1e-3) def run_test_layer_norm(self, dtype, atol, rtol=1e-5): device = torch.device('cuda') s = 512 b = 32 hidden_size = 1024 epsilon = 1e-5 x = torch.randn((s,b,hidden_size), dtype=dtype, device=device) beta = torch.randn(hidden_size, dtype=dtype, device=device) gamma = torch.randn(hidden_size, dtype=dtype, device=device) x.requires_grad = True beta.requires_grad = True gamma.requires_grad = True x2 = x.clone().detach() beta2 = beta.clone().detach() gamma2 = gamma.clone().detach() x2.requires_grad = True beta2.requires_grad = True gamma2.requires_grad = True dummy_label = torch.randn_like(x) y = F.layer_norm(x, [hidden_size], gamma, beta, epsilon) diff = y-dummy_label l = (diff * diff).sum() / b l.backward() fln = FastLayerNorm(hidden_size).cuda() fln.load_state_dict({'bias': beta2, 'weight':gamma2}) if dtype == torch.float16: fln = fln.half() y2 = fln(x2) diff2 = (y2 - dummy_label) l2 = (diff2 * diff2).sum() / b l2.backward() self.assertTrue(torch.allclose(y2, y, atol=atol, rtol=rtol)) self.assertTrue(torch.allclose(x2.grad, x.grad, atol=atol,rtol=rtol)) self.assertTrue(torch.allclose(fln.bias.grad, beta.grad, atol=atol, rtol=rtol)) self.assertTrue(torch.allclose(fln.weight.grad, gamma.grad, atol=atol, rtol=rtol)) def test_performance(self): print() runs = 1000 device = torch.device('cuda') dtype =torch.float16 s = 512 b = 32 hidden_size = 1024 epsilon = 1e-5 x = torch.randn((s*b,hidden_size), dtype=dtype, device=device) beta = torch.randn(hidden_size, dtype=dtype, device=device) gamma = torch.randn(hidden_size, dtype=dtype, device=device) dy = torch.randn_like(x) stream = torch.cuda.Stream() with torch.cuda.stream(stream): timer = GPUTimer(stream) #warmup for r in range(runs): y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5) timer.start() for r in range(runs): y, mu, rsigma = fln.ln_fwd(x, gamma, beta, 1e-5) timer.stop() timer.sync() total_bytes_fwd = (size_in_bytes(x) + size_in_bytes(y) + size_in_bytes(gamma) + size_in_bytes(beta) + size_in_bytes(mu) + size_in_bytes(rsigma) ) ms_fwd = timer.millis() / runs print('[FWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_fwd, total_bytes_fwd * 1e-6 / ms_fwd )) timer.start() for r in range(runs): dx, dgamma, dbeta = fln.ln_bwd(dy, x, mu, rsigma, gamma) timer.stop() timer.sync() total_bytes_bwd = (size_in_bytes(x) + size_in_bytes(dx) + size_in_bytes(dy) + size_in_bytes(gamma) + size_in_bytes(dgamma) + size_in_bytes(dbeta) + size_in_bytes(mu) + size_in_bytes(rsigma) ) ms_bwd = timer.millis() / runs print('[BWD] Time: {:.4f}ms Throughput: {:.4f} GB/sec'.format(ms_bwd, total_bytes_bwd * 1e-6 / ms_bwd )) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_encdec_multihead_attn.py ================================================ import torch import unittest from apex.contrib.multihead_attn import EncdecMultiheadAttn class EncdecMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.ref_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_encdec_multihead_attn(self) : grads = torch.randn_like(self.tst_inputs_q) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) def test_encdec_multihead_attn_time_mask(self) : grads = torch.randn_like(self.tst_inputs_q) time_mask_byte = torch.triu(torch.ones(self.tst_inputs_q.size(0), self.tst_inputs_k.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) time_mask_bool = time_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=time_mask_bool, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=time_mask_byte, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) def test_encdec_multihead_attn_pad_mask(self) : grads = torch.randn_like(self.tst_inputs_q) pad_mask_byte = torch.tril(torch.ones(self.tst_inputs_k.size(1), self.tst_inputs_k.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) pad_mask_bool = pad_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=pad_mask_bool, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=pad_mask_byte, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_encdec_multihead_attn_norm_add.py ================================================ import torch import unittest from apex.contrib.multihead_attn import EncdecMultiheadAttn class EncdecMultiheadAttnNormAddTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.ref_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = EncdecMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs_q = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs_k = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_encdec_multihead_attn_norm_add(self) : grads = torch.randn_like(self.tst_inputs_q) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs_q, self.ref_inputs_k, self.ref_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs_q, self.tst_inputs_k, self.tst_inputs_k, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs_q.backward(grads) self.tst_inputs_q.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs_q, self.tst_inputs_q, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.ref_inputs_k, self.tst_inputs_k, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs_q.grad, self.tst_inputs_q.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_fast_self_multihead_attn_bias.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=True, include_norm_add=False, separate_qkv_params=True, mask_additive=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=True, include_norm_add=False, separate_qkv_params=True, mask_additive=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn_additive_mask(self) : grads = torch.randn_like(self.tst_inputs) mask = ((torch.randn(self.sequences, self.seq_length) > 0) * -10000.0).half().cuda() ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=mask, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=mask, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_mha_fused_softmax.py ================================================ import torch import unittest import torch.nn.functional as F from apex.contrib.multihead_attn import fast_mask_softmax_dropout_func class FusedSoftmaxTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.mask = (torch.randn(self.sequences,self.seq_length)>0).cuda() self.mask = self.mask.half()*-10000 self.ref_inputs = torch.randn(self.heads * self.sequences, self.seq_length, self.seq_length, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) self.tst_inputs = self.ref_inputs.clone().detach().requires_grad_(True) def test_fused_softmax(self) : grads = torch.randn_like(self.tst_inputs) y_ref = self.ref_inputs.view(self.sequences, self.heads, self.seq_length, self.seq_length) y_ref = y_ref + self.mask.unsqueeze(1).unsqueeze(2) y_ref = y_ref.view(self.sequences*self.heads, self.seq_length, self.seq_length) y_ref = F.softmax(y_ref, dim=-1) y_ref = torch._fused_dropout(y_ref, 1.0) y_tst = fast_mask_softmax_dropout_func(True, self.heads, self.tst_inputs, self.mask, True, 0.0) y_ref[0].backward(grads) y_tst.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(y_ref[0], y_tst, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_self_multihead_attn.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=False, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn(self) : grads = torch.randn_like(self.tst_inputs) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) def test_self_multihead_attn_time_mask(self) : grads = torch.randn_like(self.tst_inputs) time_mask_byte= torch.triu(torch.ones(self.tst_inputs.size(0), self.tst_inputs.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) time_mask_bool= time_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=time_mask_bool, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=time_mask_byte, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) def test_self_multihead_attn_pad_mask(self) : grads = torch.randn_like(self.tst_inputs) pad_mask_byte = torch.tril(torch.ones(self.tst_inputs.size(1), self.tst_inputs.size(0), device=torch.device("cuda"), dtype=torch.uint8), 1) pad_mask_bool = pad_mask_byte.to(torch.bool) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=pad_mask_bool, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=pad_mask_byte, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/multihead_attn/test_self_multihead_attn_norm_add.py ================================================ import torch import unittest from apex.contrib.multihead_attn import SelfMultiheadAttn class SelfMultiheadAttnNormAddTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.seq_length = 80 self.sequences = 10 self.hidden_dim = 1024 self.heads = 16 self.dropout_prob = 0.0 self.ref_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='default') self.ref_layer.cuda().half() self.ref_layer.reset_parameters() self.ref_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) # Reset seed so parameters are identical torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) self.tst_layer = SelfMultiheadAttn(self.hidden_dim, self.heads, dropout=self.dropout_prob, bias=False, include_norm_add=True, impl='fast') self.tst_layer.cuda().half() self.tst_layer.reset_parameters() self.tst_inputs = torch.randn(self.seq_length, self.sequences, self.hidden_dim, dtype=torch.float16, device=torch.device("cuda")).requires_grad_(True) def test_self_multihead_attn_norm_add(self) : grads = torch.randn_like(self.tst_inputs) ref_outputs,_ = self.ref_layer.forward(self.ref_inputs, self.ref_inputs, self.ref_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) tst_outputs,_ = self.tst_layer.forward(self.tst_inputs, self.tst_inputs, self.tst_inputs, key_padding_mask=None, need_weights=False, attn_mask=None, is_training=True) self.ref_inputs.backward(grads) self.tst_inputs.backward(grads) self.assertTrue(torch.allclose(self.ref_inputs, self.tst_inputs, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_outputs, tst_outputs, atol=1e-3, rtol=1e-3)) self.assertTrue(torch.allclose(self.ref_inputs.grad, self.tst_inputs.grad, atol=1e-3, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/test_label_smoothing.py ================================================ import torch from apex.contrib import xentropy as label_smoothing import unittest import warnings import random import numpy as np import time def label_smoothing_raw(x, target, padding_idx, smoothing): logprobs = torch.nn.functional.log_softmax(x, dim=-1, dtype=torch.float32) non_pad_mask = (target != padding_idx) nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1)) nll_loss = nll_loss.squeeze(1)[non_pad_mask] smooth_loss = -logprobs.mean(dim=-1)[non_pad_mask] loss = (1.0 - smoothing) * nll_loss + smoothing * smooth_loss return loss def label_smoothing_opt_1(x, target, padding_idx, smoothing): logprobs = torch.nn.functional.log_softmax(x, dim=-1, dtype=torch.float32) pad_mask = (target == padding_idx) ll_loss = logprobs.gather(dim=-1, index=target.unsqueeze(1)).squeeze(1) smooth_loss = logprobs.mean(dim=-1) loss = (smoothing - 1.0) * ll_loss - smoothing * smooth_loss loss.masked_fill_(pad_mask, 0) return loss class LabelSmoothingTest(unittest.TestCase): def setUp(self, seed=1234): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Set pytorch print precision torch.set_printoptions(precision=10) def gen_test_inputs(self, N, T, H, smoothing, padding_idx): logits = torch.randn((N*T, H), dtype=torch.half, device='cuda', requires_grad=True) labels = torch.randint(0, H, [N*T], device='cuda') for i in random.sample(range(N*T), N*T//6): labels[i] = padding_idx half_to_float = (logits.dtype == torch.half) return logits, labels, half_to_float def print_max_diff_elem(self, ref, tst): ref, tst = ref.flatten(), tst.flatten() diff = (ref - tst).abs().max() idx = (ref - tst).abs().argmax() print("Max atol idx: {}, diff: {:.6f}, ref: {:.6f}, tst: {:.6f}".format( idx, diff, ref[idx], tst[idx])) def test_label_smoothing_function(self): # Set label smoothing configuration smoothing, padding_idx = 0.1, 0 N, T, H = 128, 74, 32320 iters = 10 loss_func = label_smoothing.SoftmaxCrossEntropyLoss.apply for i in range(iters): logits, labels, half_to_float = self.gen_test_inputs( N, T, H, smoothing, padding_idx) # Run original softmax cross entropy with label smoothing logits.grad = None losses = label_smoothing_raw(logits, labels, padding_idx, smoothing) loss = losses.sum() loss.backward() ref_loss = loss.clone().detach() ref_grad = logits.grad.clone().detach() # Run optimized softmax cross entropy with label smoothing logits.grad = None losses = loss_func(logits, labels, smoothing, padding_idx, half_to_float) loss = losses.sum() loss.backward() val_loss = loss.clone().detach() val_grad = logits.grad.clone().detach() # Validate self.print_max_diff_elem(ref_grad, val_grad) self.assertTrue(torch.allclose(ref_loss, val_loss, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(ref_grad, val_grad, atol=1e-5, rtol=1e-5)) def test_label_smoothing_perf(self): # Set label smoothing configuration smoothing, padding_idx = 0.1, 0 N, T, H = 128, 74, 32320 iters = 1000 loss_func = label_smoothing.SoftmaxCrossEntropyLoss.apply print() logits, labels, half_to_float = self.gen_test_inputs( N, T, H, smoothing, padding_idx) # Run original softmax cross entropy with label smoothing torch.cuda.synchronize() ts = time.time() for i in range(iters): logits.grad = None losses = label_smoothing_raw(logits, labels, padding_idx, smoothing) loss = losses.sum() / N loss.backward() torch.cuda.synchronize() print("Raw time {:.2f} s elapsed for {} iterations, norm {:.4f}".format( time.time() - ts, iters, logits.grad.norm())) # Run optimized softmax cross entropy with label smoothing torch.cuda.synchronize() ts = time.time() for i in range(iters): logits.grad = None losses = loss_func(logits, labels, smoothing, padding_idx, half_to_float) loss = losses.sum() / N loss.backward() torch.cuda.synchronize() print("Opt time {:.2f} s elapsed for {} iterations, norm {:.4f}".format( time.time() - ts, iters, logits.grad.norm())) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/transducer/test_transducer_joint.py ================================================ import torch import unittest from apex.contrib.transducer import TransducerJoint import transducer_ref class TransducerJointTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def gen_input(self, for_vector_kernel): self.B = 4 T_min = 51 T_max = 101 U_min = 12 U_max = 25 if for_vector_kernel: H = 512 else: H = 509 dtype = torch.float16 device = "cuda" self.f_tst = torch.randn((self.B, T_max, H), dtype=dtype, requires_grad=True, device=device) self.g_tst = torch.randn((self.B, U_max, H), dtype=dtype, requires_grad=True, device=device) self.h_grad = torch.randn(self.B, T_max, U_max, H, dtype=dtype, device=device) self.f_len = torch.randint(T_min, T_max+1, (self.B,), dtype=torch.int, device=device) self.g_len = torch.randint(U_min, U_max+1, (self.B,), dtype=torch.int, device=device) self.f_len[torch.randint(0, self.B, (1,)).item()] = T_max self.g_len[torch.randint(0, self.B, (1,)).item()] = U_max self.dropout_prob = 0.5 # Make sure gradients from out-of-bound locations are zero. This should be guaranteed by # the loss function for b in range(self.B): self.h_grad[b, self.f_len[b]:, :, :] = 0 self.h_grad[b, :, self.g_len[b]:, :] = 0 self.h_grad_packed = self._pack(self.h_grad, self.f_len, self.g_len) def _pack(self, x, f_len, g_len): B = x.size(0) list_x = [] for b in range(B): list_x_row = [x[b, t, :g_len[b]] for t in range(f_len[b])] x_row = torch.cat(list_x_row) list_x.append(x_row) x_packed = torch.cat(list_x).data.clone() x_packed.requires_grad = True batch_offset = torch.cumsum(f_len * g_len, dim=0) return x_packed def _unpack(self, x, f_len, g_len): batch_offset = torch.cumsum(f_len * g_len, dim=0) x_unpacked = torch.zeros_like(self.h_grad, dtype=torch.uint8) B = self.h_grad.size(0) H = self.h_grad.size(-1) for b in range(B): my_batch_offset = 0 if b == 0 else batch_offset[b-1] my_f_len = f_len[b] my_g_len = g_len[b] for t in range(my_f_len): x_unpacked[b, t, :my_g_len] = x[my_batch_offset + t*my_g_len : my_batch_offset + t*my_g_len + my_g_len] return x_unpacked def run_transducer_joint(self, for_vector_kernel, pack_output, relu, dropout): self.gen_input(for_vector_kernel=for_vector_kernel) # Generate reference f_ref = self.f_tst.data.clone() g_ref = self.g_tst.data.clone() f_ref.requires_grad = True g_ref.requires_grad = True my_joint = TransducerJoint(pack_output=pack_output, relu=relu, dropout=dropout, dropout_prob=self.dropout_prob, probe_mask=True) if not pack_output: h_tst = my_joint( f=self.f_tst, g=self.g_tst, f_len=self.f_len, g_len=self.g_len) h_tst.backward(self.h_grad) if dropout: mask = my_joint.mask_probe[0] else: batch_offset = torch.cumsum(self.f_len * self.g_len, dim=0) h_tst = my_joint( f=self.f_tst, g=self.g_tst, f_len=self.f_len, g_len=self.g_len, batch_offset=batch_offset, packed_batch=batch_offset[-1]) h_tst.backward(self.h_grad_packed) if dropout: mask_packed = my_joint.mask_probe[0] mask = self._unpack(mask_packed, self.f_len, self.g_len) # reference h_ref, f_grad_ref, g_grad_ref \ = transducer_ref.transducer_joint_reference(f=f_ref, g=g_ref, h_grad=self.h_grad, f_len=self.f_len, g_len=self.g_len, pack_output=pack_output, relu=relu, dropout=dropout, dropout_prob=self.dropout_prob, mask=mask if dropout else None) f_grad_tst = self.f_tst.grad g_grad_tst = self.g_tst.grad self.assertTrue(torch.allclose(h_ref, h_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(f_grad_ref, f_grad_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(g_grad_ref, g_grad_tst, atol=1e-4, rtol=1e-4)) def test_transducer_joint(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=False, dropout=False) def test_transducer_joint_vec(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=False, dropout=False) def test_transducer_joint_pack(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=False, dropout=False) def test_transducer_joint_vec_pack(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=False, dropout=False) def test_transducer_joint_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=False) def test_transducer_joint_vec_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=True, dropout=False) def test_transducer_joint_pack_relu(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=True, dropout=False) def test_transducer_joint_vec_pack_relu(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=False) def test_transducer_joint_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=True) def test_transducer_joint_vec_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=False, relu=True, dropout=True) def test_transducer_joint_pack_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=False, pack_output=True, relu=True, dropout=True) def test_transducer_joint_vec_pack_relu_dropout(self): self.run_transducer_joint(for_vector_kernel=True, pack_output=True, relu=True, dropout=True) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/transducer/test_transducer_loss.py ================================================ import torch import unittest from apex.contrib.transducer import TransducerLoss import transducer_ref class TransducerLossTest(unittest.TestCase): def setUp(self, seed=1234): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) def gen_input(self, scalar_t, for_vector_kernel): self.B = 5 T_min = 23 T_max = 51 U_min = 12 U_max = 25 V = 16 if for_vector_kernel else 14 self.blank_idx = V - 1 device = "cuda" self.x_tst = torch.randn((self.B, T_max, U_max, V), dtype=scalar_t, requires_grad=True, device=device) self.y = torch.randint(0, self.blank_idx, (self.B, U_max-1), dtype=torch.int, device=device) self.f_len = torch.randint(T_min, T_max+1, (self.B,), dtype=torch.int, device=device) self.y_len = torch.randint(U_min-1, U_max, (self.B,), dtype=torch.int, device=device) self.f_len[torch.randint(0, self.B, (1,)).item()] = T_max self.y_len[torch.randint(0, self.B, (1,)).item()] = U_max-1 self.x_tst_packed, self.batch_offset = self._pack(self.x_tst) # Generate reference x_ref = self.x_tst.data.clone() x_ref.requires_grad = True loss_grad = torch.ones(x_ref.size(0), dtype=x_ref.dtype, device=x_ref.device)/x_ref.size(0) _, _, self.grad_ref, self.loss_ref \ = transducer_ref.transducer_loss_reference( x=x_ref, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx, loss_grad=loss_grad) def _pack(self, x): list_x = [] for b in range(self.B): list_x_row = [x[b, t, : self.y_len[b]+1] for t in range(self.f_len[b])] x_row = torch.cat(list_x_row) list_x.append(x_row) x_packed = torch.cat(list_x).data.clone() x_packed.requires_grad = True batch_offset = torch.cumsum(self.f_len * (self.y_len+1), dim=0) return x_packed, batch_offset def _unpack(self, x): x_unpacked = torch.zeros(self.B, self.f_len.max(), self.y_len.max()+1, x.size(-1), dtype=x.dtype, device=x.device) for b in range(self.B): my_batch_offset = 0 if b == 0 else self.batch_offset[b-1] my_f_len = self.f_len[b] my_g_len = self.y_len[b] + 1 for t in range(my_f_len): for u in range(my_g_len): x_unpacked[b, t, u] = x[my_batch_offset + t*my_g_len + u] return x_unpacked def run_transducer_loss(self, scalar_t, fuse_softmax_backward, packed_input, for_vector_kernel): self.gen_input(scalar_t, for_vector_kernel) my_loss = TransducerLoss( fuse_softmax_backward=fuse_softmax_backward, packed_input=packed_input) if not packed_input: loss_tst = my_loss( x=self.x_tst, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx) loss_tst.mean().backward() grad_tst = self.x_tst.grad else: loss_tst = my_loss( x=self.x_tst_packed, label=self.y, f_len=self.f_len, y_len=self.y_len, blank_idx=self.blank_idx, batch_offset=self.batch_offset, max_f_len=max(self.f_len)) loss_tst.mean().backward() grad_tst_packed = self.x_tst_packed.grad grad_tst = self._unpack(grad_tst_packed) return loss_tst, grad_tst def test_transducer_loss_fp32(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float32, fuse_softmax_backward=False, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-5, rtol=1e-5)) def test_transducer_loss_fp16(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=False, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=False, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion_packed(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=True, for_vector_kernel=False) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) def test_transducer_loss_fp16_backward_fusion_packed_vec(self): loss_tst, grad_tst = self.run_transducer_loss( scalar_t=torch.float16, fuse_softmax_backward=True, packed_input=True, for_vector_kernel=True) self.assertTrue(torch.allclose(self.loss_ref, loss_tst, atol=1e-5, rtol=1e-5)) self.assertTrue(torch.allclose(self.grad_ref, grad_tst, atol=1e-4, rtol=1e-3)) if __name__ == '__main__': unittest.main() ================================================ FILE: KoSimCSE/apex/contrib/test/transducer/transducer_ref.py ================================================ import torch import numpy as np import pdb def transducer_loss_reference(x, label, f_len, y_len, blank_idx, loss_grad): def log_sum_exp(a, b): if (a >= b): return a + torch.log(1 + torch.exp(b-a)) else: return b + torch.log(1 + torch.exp(a-b)) def forward_alpha(x, label, f_len, y_len, blank_idx): B, T, U, V = x.size() acc_t = torch.float32 if x.dtype in [torch.float16, torch.float32] else x.dtype alpha = torch.zeros((B, T, U), dtype=acc_t, device=x.device) for b in range(B): alpha[b, 0, 0] = 0 for t in range(1, f_len[b]): alpha[b, t, 0] = alpha[b, t-1, 0] + x[b, t-1, 0, blank_idx] for u in range(1, y_len[b]+1): alpha[b, 0, u] = alpha[b, 0, u-1] + x[b, 0, u-1, label[b, u-1]] for t in range(1, f_len[b]): for u in range(1, y_len[b]+1): curr_ = alpha[b, t-1, u] + x[b, t-1, u, blank_idx] next_ = alpha[b, t, u-1] + x[b, t, u-1, label[b, u-1]] alpha[b, t, u] = log_sum_exp(curr_, next_) return alpha def forward_beta(x, label, f_len, y_len, blank_idx): B, T, U, V = x.shape acc_t = torch.float32 if x.dtype in [torch.float16, torch.float32] else x.dtype beta = torch.zeros((B, T, U), dtype=acc_t, device=x.device) for b in range(B): beta[b, f_len[b]-1, y_len[b]] = x[b, f_len[b]-1, y_len[b], blank_idx] for t in range(f_len[b]-2, -1, -1): beta[b, t, y_len[b]] = beta[b, t+1, y_len[b]] + x[b, t, y_len[b], blank_idx] for u in range(y_len[b]-1, -1, -1): beta[b, f_len[b]-1, u] = beta[b, f_len[b]-1, u+1] + x[b, f_len[b]-1, u, label[b, u]] for t in range(f_len[b]-2, -1, -1): for u in range(y_len[b]-1, -1, -1): curr_ = beta[b, t+1, u] + x[b, t, u, blank_idx] next_ = beta[b, t, u+1] + x[b, t, u, label[b, u]] beta[b, t, u] = log_sum_exp(curr_, next_) return beta def backward(x, label, f_len, y_len, alpha, beta, loss_grad, blank_idx): grad = torch.zeros_like(x) B, T, U, V = x.size() for b in range(B): common_factor = torch.log(loss_grad[b]) + alpha - beta[b, 0, 0] # next for u in range(y_len[b]): grad[b, :f_len[b], u, label[b, u]] = -torch.exp(common_factor[b, :f_len[b], u] + beta[b, :f_len[b], u+1] + x[b, :f_len[b], u, label[b, u]]) # current grad[b, :f_len[b]-1, :y_len[b]+1, blank_idx] \ = -torch.exp(common_factor[b, :f_len[b]-1, :y_len[b]+1] + beta[b, 1:f_len[b], :y_len[b]+1] + x[b, :f_len[b]-1, :y_len[b]+1, blank_idx]) grad[b, f_len[b]-1, y_len[b], blank_idx] = -torch.exp(common_factor[b, f_len[b]-1, y_len[b]] + x[b, f_len[b]-1, y_len[b], blank_idx]) return grad x_log = torch.nn.functional.log_softmax(x, dim=-1) alpha = forward_alpha(x_log, label, f_len, y_len, blank_idx) beta = forward_beta(x_log, label, f_len, y_len, blank_idx) grad = backward(x_log, label, f_len, y_len, alpha, beta, loss_grad, blank_idx) x_log.backward(grad) loss = -beta[:, 0, 0] loss = loss.to(x.dtype) return alpha, beta, x.grad, loss def transducer_joint_reference(f, g, h_grad, f_len, g_len, pack_output, relu, dropout, dropout_prob=0, mask=None): if dropout and mask == None: raise NotImplementedError("mask needs to supplied to test dropout.") B, T, H = f.size() U = g.size(1) f_expand = f.unsqueeze(dim=2) g_expand = g.unsqueeze(dim=1) h = f_expand + g_expand if relu: h = torch.nn.functional.relu(h) if dropout: h *= mask scale = 1/(1-dropout_prob) h *= scale h.backward(h_grad) if pack_output == False: # intentionally set don't-care region to -1 to test if transducer joint # write these regions to avoid NaN and inf for b in range(B): h[b, f_len[b]:] = -1 h[b, :, g_len[b]:] = -1 return h, f.grad, g.grad # packing list_to_pack = [] for b in range(B): list_to_pack.append(h[b, :f_len[b], :g_len[b], :].reshape(-1, H)) h_packed = torch.cat(list_to_pack) return h_packed, f.grad, g.grad ================================================ FILE: KoSimCSE/apex/contrib/transducer/__init__.py ================================================ from .transducer import TransducerJoint from .transducer import TransducerLoss ================================================ FILE: KoSimCSE/apex/contrib/transducer/transducer.py ================================================ import torch import transducer_loss_cuda import transducer_joint_cuda class TransducerJoint(torch.nn.Module): """Transducer joint Detail of this loss function can be found in: Sequence Transduction with Recurrent Neural Networks Arguments: pack_output (bool, optional): whether to pack the output in a compact form with don't-care data being removed. (default: False) relu (bool, optional): apply ReLU to the output of the joint operation. Requires opt=1 (default: False) dropout (bool, optional): apply dropout to the output of the joint operation. Requires opt=1 (default: False) opt (int, optional): pick the optimization level in [0, 1]. opt=1 picks a tiled algorithm. (default: 1) fwd_tile_size (int, optional): tile size used in forward operation. This argument will be ignored if opt != 1. (default: 4) dropout_prob (float, optional): dropout probability. (default: 0.0) probe_mask (bool, optional): a flag used to probe the mask generated by ReLU and/or dropout operation. When this argument is set to True, the mask can be accessed through self.mask_probe. (default: false) """ def __init__(self, pack_output=False, relu=False, dropout=False, opt=1, fwd_tile_size=4, dropout_prob=0, probe_mask=False): super(TransducerJoint, self).__init__() self.pack_output = pack_output self.relu = relu self.dropout = dropout self.dropout_prob = dropout_prob self.opt = opt self.fwd_tile_size = fwd_tile_size self.dummy_batch_offset = torch.empty(0) masked = self.relu or self.dropout self.mask_probe = [] if masked and probe_mask else None if masked and opt != 1: raise NotImplementedError("ReLU and dropout fusion is only supported with opt=1") def forward(self, f, g, f_len, g_len, batch_offset=None, packed_batch=0): """Forward operation of transducer joint Arguments: f (tensor): transcription vector from encode block of shape (B, T, H). g (tensor): prediction vector form predict block of shape (B, U, H). f_len (tensor): length of transcription vector for each batch. g_len (tensor): length of prediction vector minus 1 for each batch. batch_offset (tensor, optional): tensor containing the offset of each batch in the results. For example, batch offset can be obtained from: batch_offset = torch.cumsum(f_len*g_len, dim=0) This argument is required if pack_output == True, and is ignored if pack_output == False. (default: None) packed_batch (int, optional): the batch size after packing. This argument is ignored if pack_output == False. (default: 0) """ my_batch_offset = batch_offset if self.pack_output else self.dummy_batch_offset if self.pack_output and (batch_offset is None or packed_batch == 0): raise Exception("Please specify batch_offset and packed_batch when packing is enabled") dropout = self.dropout and self.training # only dropout for training return TransducerJointFunc.apply(f, g, f_len, g_len, self.pack_output, self.relu, dropout, my_batch_offset, packed_batch, self.opt, self.fwd_tile_size, self.dropout_prob, self.mask_probe) class TransducerLoss(torch.nn.Module): """Transducer loss Detail of this loss function can be found in: Sequence Transduction with Recurrent Neural Networks Arguments: fuse_softmax_backward (bool, optional) whether to fuse the backward of transducer loss with softmax. (default: True) opt (int, optional): pick the optimization level in [0, 1]. opt=1 picks a more optimized algorithm. In some cases, opt=1 might fall back to opt=0. (default: 1) packed_input (bool, optional): whether to pack the output in a compact form with don't-care data being removed. (default: False) """ def __init__(self, fuse_softmax_backward=True, opt=1, packed_input=False): super(TransducerLoss, self).__init__() self.fuse_softmax_backward = fuse_softmax_backward self.opt = opt self.packed_input = packed_input self.dummy_batch_offset = torch.empty(0) def forward(self, x, label, f_len, y_len, blank_idx, batch_offset=None, max_f_len=None, debug_list=None): """Forward operation of transducer joint Arguments: x (tensor): input tensor to the loss function with a shape of (B, T, U, H). label (tensor): labels for the input data. f_len (tensor): lengths of the inputs in the time dimension for each batch. y_len (tensor): lengths of the labels for each batch. blank_idx (int): index for the null symbol. batch_offset (tensor, optional): tensor containing the offset of each batch in the input. For example, batch offset can be obtained from: batch_offset = torch.cumsum(f_len*(y_len+1), dim=0) This argument is required if packed_input == True, and is ignored if packed_input == False. (default: None) max_f_len (int, optional): maximum length of the input in the time dimension. For example, it can be obtained as max_f_len = max(f_len) This argument is required if packed_input == True, and is ignored if packed_input == False. (default: None) (default: None) debug_list (list, optional): when an empty list is supplied, Alpha and Beta generated in the forward operation will be attached to this list for debug purpose. (default: None) """ if self.packed_input: if batch_offset is None or max_f_len is None: raise Exception("Please specify batch_offset and max_f_len when packing is \ enabled") my_batch_offset = batch_offset my_max_f_len = max_f_len else: my_batch_offset = self.dummy_batch_offset my_max_f_len = x.size(1) return TransducerLossFunc.apply(x, label, f_len, y_len, my_batch_offset, my_max_f_len, blank_idx, self.fuse_softmax_backward, debug_list, self.opt, self.packed_input) class TransducerLossFunc(torch.autograd.Function): @staticmethod def forward(ctx, x, label, f_len, y_len, batch_offset, max_f_len, blank_idx, fuse_softmax_backward, debug_list, opt, packed_input): if fuse_softmax_backward == False: with torch.enable_grad(): x = torch.nn.functional.log_softmax(x, dim=-1) else: x = torch.nn.functional.log_softmax(x, dim=-1) alpha, beta, loss = transducer_loss_cuda.forward( x, label, f_len, y_len, batch_offset, max_f_len, blank_idx, opt, packed_input) if debug_list == []: debug_list += [alpha, beta] ctx.save_for_backward(x, alpha, beta, f_len, y_len, label, batch_offset) ctx.blank_idx = blank_idx ctx.fuse_softmax_backward = fuse_softmax_backward ctx.opt = opt ctx.packed_input = packed_input ctx.max_f_len = max_f_len return loss @staticmethod def backward(ctx, loss_grad): x, alpha, beta, f_len, y_len, label, batch_offset = ctx.saved_tensors x_grad = transducer_loss_cuda.backward( x, loss_grad, alpha, beta, f_len, y_len, label, batch_offset, ctx.max_f_len, ctx.blank_idx, ctx.opt, ctx.fuse_softmax_backward, ctx.packed_input) if ctx.fuse_softmax_backward == False: x_grad = x.backward(x_grad) return x_grad, None, None, None, None, None, None, None, None, None, None class TransducerJointFunc(torch.autograd.Function): @staticmethod def forward(ctx, f, g, f_len, g_len, pack_output, relu, dropout, batch_offset, packed_batch, opt, fwd_tile_size, dropout_prob, mask_probe): h = transducer_joint_cuda.forward(f, g, f_len, g_len, batch_offset, packed_batch, opt, pack_output, relu, dropout, dropout_prob, fwd_tile_size) masked = relu or dropout if masked: ctx.save_for_backward(h[1], f_len, g_len, batch_offset) if mask_probe is not None: mask_probe.append(h[1]) else: ctx.save_for_backward(f_len, g_len, batch_offset) ctx.pack_output = pack_output ctx.masked = relu or dropout ctx.max_f_len = f.size(1) ctx.max_g_len = g.size(1) ctx.scale = 1 / (1-dropout_prob) if dropout and dropout_prob != 1 else 1 return h[0] @staticmethod def backward(ctx, loss_grad): if ctx.masked: mask, f_len, g_len, batch_offset = ctx.saved_tensors inp = [loss_grad, mask] else: f_len, g_len, batch_offset = ctx.saved_tensors inp = [loss_grad] f_grad, g_grad = transducer_joint_cuda.backward( inp, f_len, g_len, batch_offset, ctx.max_f_len, ctx.max_g_len, ctx.pack_output, ctx.scale) return f_grad, g_grad, None, None, None, None, None, None, None, None, None, None, None, \ None, None, None ================================================ FILE: KoSimCSE/apex/contrib/xentropy/__init__.py ================================================ try: import torch import xentropy_cuda from .softmax_xentropy import SoftmaxCrossEntropyLoss del torch del xentropy_cuda del softmax_xentropy except ImportError as err: print("apex was installed without --xentropy flag, contrib.xentropy is not available") ================================================ FILE: KoSimCSE/apex/contrib/xentropy/softmax_xentropy.py ================================================ import torch import xentropy_cuda class SoftmaxCrossEntropyLoss(torch.autograd.Function): @staticmethod def forward(ctx, logits, labels, smoothing=0.0, padding_idx=0, half_to_float=False): losses, max_log_sum_exp = xentropy_cuda.forward( logits, labels, smoothing, half_to_float) losses.masked_fill_(labels==padding_idx, 0) ctx.save_for_backward(logits, max_log_sum_exp, labels, torch.FloatTensor([smoothing]), torch.LongTensor([padding_idx])) return losses @staticmethod def backward(ctx, grad_loss): logits, max_log_sum_exp, labels, smoothing, padding_idx = ctx.saved_tensors if not grad_loss.is_contiguous(): grad_loss = grad_loss.contiguous() grad_loss.masked_fill_(labels==padding_idx.item(), 0) grad_logits = xentropy_cuda.backward( grad_loss.contiguous(), logits, max_log_sum_exp, labels, smoothing.item()) return grad_logits, None, None, None, None ================================================ FILE: KoSimCSE/apex/fp16_utils/README.md ================================================ fp16_optimizer.py contains `FP16_Optimizer`, a Python class designed to wrap an existing Pytorch optimizer and automatically enable master parameters and loss scaling in a manner transparent to the user. To use `FP16_Optimizer`, only two lines of one's Python model need to change. #### [FP16_Optimizer API documentation](https://nvidia.github.io/apex/fp16_utils.html#automatic-management-of-master-params-loss-scaling) #### [Simple examples with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/FP16_Optimizer_simple) #### [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) #### [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model) fp16_util.py contains a number of utilities to manually manage master parameters and loss scaling, if the user chooses. #### [Manual management documentation](https://nvidia.github.io/apex/fp16_utils.html#manual-master-parameter-management) The [Imagenet with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) and [word_language_model with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/word_language_model) directories also contain `main.py` files that demonstrate manual management of master parameters and static loss scaling. These examples illustrate what sort of operations `FP16_Optimizer` is performing automatically. ================================================ FILE: KoSimCSE/apex/fp16_utils/__init__.py ================================================ from .fp16util import ( BN_convert_float, network_to_half, prep_param_lists, model_grads_to_master_grads, master_params_to_model_params, tofp16, to_python_float, clip_grad_norm, convert_module, convert_network, FP16Model, ) from .fp16_optimizer import FP16_Optimizer from .loss_scaler import LossScaler, DynamicLossScaler ================================================ FILE: KoSimCSE/apex/fp16_utils/fp16_optimizer.py ================================================ import torch from torch import nn from torch.autograd import Variable from torch.nn.parameter import Parameter from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from ..amp._amp_state import _amp_state, maybe_print from ..amp.scaler import LossScaler from ..multi_tensor_apply import multi_tensor_applier from .fp16util import model_grads_to_master_grads, master_params_to_model_params, clip_grad_norm # TODO: Update overflow check + downscale to use Carl's fused kernel. class FP16_Optimizer(object): def __init__(self, init_optimizer, static_loss_scale=1.0, dynamic_loss_scale=False, dynamic_loss_args=None, verbose=True): print("Warning: FP16_Optimizer is deprecated and dangerous, and will be deleted soon. " "If it still works, you're probably getting lucky. " "For mixed precision, use the documented API https://nvidia.github.io/apex/amp.html, with opt_level=O1.") if not torch.cuda.is_available: raise SystemError("Cannot use fp16 without CUDA.") self.verbose = verbose self.optimizer = init_optimizer # init_state_dict sets up an alternative way to cast per-param state tensors. # Stashing here in case https://github.com/pytorch/pytorch/issues/7733 makes it necessary. # init_state_dict = init_optimizer.state_dict() self.fp16_groups = [] self.fp32_from_fp16_groups = [] self.fp32_from_fp32_groups = [] for i, param_group in enumerate(self.optimizer.param_groups): self.maybe_print("FP16_Optimizer processing param group {}:".format(i)) fp16_params_this_group = [] fp32_params_this_group = [] fp32_from_fp16_params_this_group = [] for i, param in enumerate(param_group['params']): if param.requires_grad: if param.type() == 'torch.cuda.HalfTensor': self.maybe_print("FP16_Optimizer received torch.cuda.HalfTensor with {}" .format(param.size())) fp16_params_this_group.append(param) master_param = param.detach().clone().float() master_param.requires_grad = True param_group['params'][i] = master_param fp32_from_fp16_params_this_group.append(master_param) # Reset existing state dict key to the new master param. # We still need to recast per-param state tensors, if any, to FP32. if param in self.optimizer.state: self.optimizer.state[master_param] = self.optimizer.state.pop(param) elif param.type() == 'torch.cuda.FloatTensor': self.maybe_print("FP16_Optimizer received torch.cuda.FloatTensor with {}" .format(param.size())) fp32_params_this_group.append(param) param_group['params'][i] = param else: raise TypeError("Wrapped parameters must be either " "torch.cuda.FloatTensor or torch.cuda.HalfTensor. " "Received {}".format(param.type())) self.fp16_groups.append(fp16_params_this_group) self.fp32_from_fp16_groups.append(fp32_from_fp16_params_this_group) self.fp32_from_fp32_groups.append(fp32_params_this_group) self.all_fp16_params = [] for group in self.fp16_groups: self.all_fp16_params += group self.all_fp32_from_fp16_params = [] for group in self.fp32_from_fp16_groups: self.all_fp32_from_fp16_params += group self.all_fp32_from_fp32_params = [] for group in self.fp32_from_fp32_groups: self.all_fp32_from_fp32_params += group # Leverage state_dict() and load_state_dict() to recast preexisting per-param state tensors self.optimizer.load_state_dict(self.optimizer.state_dict()) # alternative way to cast per-param state tensors: # self.optimizer.load_state_dict(init_state_dict) if dynamic_loss_scale: self.dynamic_loss_scale = True if dynamic_loss_args is not None: self.loss_scaler = LossScaler("dynamic", **dynamic_loss_args) else: self.loss_scaler = LossScaler("dynamic") else: self.dynamic_loss_scale = False self.loss_scaler = LossScaler(static_loss_scale) self.overflow = False self.first_closure_call_this_step = True self.clip_grad_norm = clip_grad_norm # TODO: Centralize exposure and import error checking for the C backend. if multi_tensor_applier.available: import amp_C self.multi_tensor_scale = amp_C.multi_tensor_scale self._dummy_overflow_buf = torch.cuda.IntTensor([0]); # Having self.maybe_print distinct from _amp_state.maybe_print is another artifact # of having to support FP16_Optimizer separately, for the time being. def maybe_print(self, msg): if self.verbose: print(msg) def __getstate__(self): raise RuntimeError("FP16_Optimizer should be serialized using state_dict().") def __setstate__(self, state): raise RuntimeError("FP16_Optimizer should be deserialized using load_state_dict().") def zero_grad(self, set_grads_to_None=False): """ Zero fp32 and fp16 parameter grads. """ # In principle, only the .grad attributes of the model params need to be zeroed, # because gradients are copied into the FP32 master params. However, we zero # all gradients owned by the optimizer, just to be safe: for group in self.optimizer.param_groups: for p in group['params']: if set_grads_to_None: p.grad = None else: if p.grad is not None: p.grad.detach_() p.grad.zero_() # Zero fp16 gradients owned by the model: for fp16_group in self.fp16_groups: for param in fp16_group: if set_grads_to_None: param.grad = None else: if param.grad is not None: param.grad.detach_() # as in torch.optim.optimizer.zero_grad() param.grad.zero_() # Should not be used anymore. # def _check_overflow(self): # params = [] # for group in self.fp16_groups: # for param in group: # params.append(param) # for group in self.fp32_from_fp32_groups: # for param in group: # params.append(param) # self.overflow = self.loss_scaler.has_overflow(params) # def _update_scale(self, has_overflow=False): # self.loss_scaler.update_scale(has_overflow) def _master_params_to_model_params(self): if multi_tensor_applier.available: if len(self.all_fp16_params) > 0: multi_tensor_applier( self.multi_tensor_scale, self._dummy_overflow_buf, [self.all_fp32_from_fp16_params, self.all_fp16_params], 1.0) else: for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): master_params_to_model_params(fp16_group, fp32_from_fp16_group) # To consider: Integrate distributed with this wrapper by registering a hook on each variable # that does the overflow check, gradient copy + downscale, and fp32 allreduce in a different stream. # def _model_grads_to_master_grads(self): # for fp16_group, fp32_from_fp16_group in zip(self.fp16_groups, self.fp32_from_fp16_groups): # model_grads_to_master_grads(fp16_group, fp32_from_fp16_group) # def _downscale_master(self): # if self.loss_scale != 1.0: # for group in self.optimizer.param_groups: # for param in group['params']: # if param.grad is not None: # param.grad.data.mul_(1./self.loss_scale) def clip_master_grads(self, max_norm, norm_type=2): """ Clips fp32 master gradients via ``torch.nn.utils.clip_grad_norm``. Args: max_norm (float or int): max norm of the gradients norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for infinity norm. Returns: Total norm of the current fp32 gradients (viewed as a single vector). .. warning:: Returns -1 if the most recently computed fp16 gradients overflowed (that is, if ``self.overflow`` is ``True``). """ if not self.overflow: fp32_params = [] for param_group in self.optimizer.param_groups: for param in param_group['params']: fp32_params.append(param) return self.clip_grad_norm(fp32_params, max_norm, norm_type) else: return -1 def state_dict(self): """ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance. This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict of the contained Pytorch optimizer. Example:: checkpoint = {} checkpoint['model'] = model.state_dict() checkpoint['optimizer'] = optimizer.state_dict() torch.save(checkpoint, "saved.pth") """ state_dict = {} state_dict['loss_scaler'] = self.loss_scaler state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale state_dict['overflow'] = self.overflow state_dict['first_closure_call_this_step'] = self.first_closure_call_this_step state_dict['optimizer_state_dict'] = self.optimizer.state_dict() state_dict['fp32_from_fp16'] = self.fp32_from_fp16_groups return state_dict def load_state_dict(self, state_dict): """ Loads a state_dict created by an earlier call to state_dict(). If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``, whose parameters in turn came from ``model``, it is expected that the user will call ``model.load_state_dict()`` before ``fp16_optimizer_instance.load_state_dict()`` is called. Example:: model = torch.nn.Linear(D_in, D_out).cuda().half() optimizer = torch.optim.SGD(model.parameters(), lr=1e-3) optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0) ... checkpoint = torch.load("saved.pth") model.load_state_dict(checkpoint['model']) optimizer.load_state_dict(checkpoint['optimizer']) """ # I think it should actually be ok to reload the optimizer before the model. self.loss_scaler = state_dict['loss_scaler'] self.dynamic_loss_scale = state_dict['dynamic_loss_scale'] self.overflow = state_dict['overflow'] self.first_closure_call_this_step = state_dict['first_closure_call_this_step'] self.optimizer.load_state_dict(state_dict['optimizer_state_dict']) # At this point, the optimizer's references to the model's fp32 parameters are up to date. # The optimizer's hyperparameters and internal buffers are also up to date. # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still # out of date. There are two options. # 1: Refresh the master params from the model's fp16 params. # This requires less storage but incurs precision loss. # 2: Save and restore the fp32 master copies separately. # We choose option 2. # # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device # of their associated parameters, because it's possible those buffers might not exist yet in # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been # constructed in the same way as the one whose state_dict we are loading, the same master params # are guaranteed to exist, so we can just copy_() from the saved master params. for current_group, saved_group in zip(self.fp32_from_fp16_groups, state_dict['fp32_from_fp16']): for current, saved in zip(current_group, saved_group): current.data.copy_(saved.data) def step(self, closure=None): # could add clip option. """ If no closure is supplied, :attr:`step` should be called after ``fp16_optimizer_obj.backward(loss)``. :attr:`step` updates the fp32 master copy of parameters using the optimizer supplied to :class:`FP16_Optimizer`'s constructor, then copies the updated fp32 params into the fp16 params originally referenced by :class:`FP16_Optimizer`'s constructor, so the user may immediately run another forward pass using their model. If a closure is supplied, :attr:`step` may be called without a prior call to :attr:`backward(loss)`. This control flow is identical to `ordinary Pytorch optimizer use`_ with closures. However, the user should take care that any ``loss.backward()`` call within the closure has been replaced by ``fp16_optimizer_obj.backward(loss)``. Args: closure (optional): Closure that will be supplied to the underlying optimizer originally passed to :class:`FP16_Optimizer`'s constructor. closure should call :attr:`zero_grad()` on the :class:`FP16_Optimizer` object, compute the loss, call :attr:`backward(loss)`, and return the loss. Example with closure:: # optimizer is assumed to be an FP16_Optimizer object, previously constructed from an # existing pytorch optimizer. for input, target in dataset: def closure(): optimizer.zero_grad() output = model(input) loss = loss_fn(output, target) # loss.backward() becomes: optimizer.backward(loss) return loss optimizer.step(closure) .. warning:: Currently, calling :attr:`step` with a closure is not compatible with dynamic loss scaling. .. _`ordinary Pytorch optimizer use`: http://pytorch.org/docs/master/optim.html#optimizer-step-closure """ scale = self.loss_scaler.loss_scale() # To consider: Should this be in step(), or update_master_grads? It works either way, # but I should make it consistent with the Amp control flow, which updates the scale # during backward context manager exit. # self._update_scale(self.overflow) if self.overflow: # Using _amp_state.maybe_print instead of self.print here is intentional. maybe_print("Gradient overflow. Skipping step, reducing " + "loss scale to {}".format(self.loss_scaler.loss_scale())) return if closure is not None: retval = self._step_with_closure(closure) else: # torch.cuda.nvtx.range_push("pytorch optimizer step") retval = self.optimizer.step() # torch.cuda.nvtx.range_pop() self._master_params_to_model_params() return retval def _step_with_closure(self, closure): def wrapped_closure(): # helpful for debugging # print("Calling wrapped_closure, first_closure_call_this_step = {}" # .format(self.first_closure_call_this_step)) if self.first_closure_call_this_step: # We expect that the fp16 params are initially fresh on entering self.step(), # so _master_params_to_model_params() is unnecessary the first time wrapped_closure() # is called within self.optimizer.step(). self.first_closure_call_this_step = False else: # If self.optimizer.step() internally calls wrapped_closure more than once, # it may update the fp32 params after each call. However, self.optimizer # doesn't know about the fp16 params at all. If the fp32 params get updated, # we can't rely on self.optimizer to refresh the fp16 params. We need # to handle that manually: self._master_params_to_model_params() # Our API expects the user to give us ownership of the backward() call by # replacing all calls to loss.backward() with optimizer.backward(loss). # This requirement holds whether or not the call to backward() is made within a closure. # If the user is properly calling optimizer.backward(loss) within "closure," # calling closure() here will give the fp32 master params fresh gradients # for the optimizer to play with, so all wrapped_closure needs to do is call # closure() and return the loss. temp_loss = closure() while(self.overflow): scale = self.loss_scaler.loss_scale() # self._update_scale(self.overflow) # now done at the end of backward print("OVERFLOW within closure! Skipping step, reducing loss scale to {}".format( self.loss_scaler.loss_scale())) temp_loss = closure() return temp_loss retval = self.optimizer.step(wrapped_closure) self.first_closure_call_this_step = True return retval def backward(self, loss, update_master_grads=True, retain_graph=False): """ :attr:`backward` performs the following conceptual steps: 1. fp32_loss = loss.float() (see first Note below) 2. scaled_loss = fp32_loss*loss_scale 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's leaves (which may be fp16, fp32, or a mixture, depending how your model was defined). 4. fp16 grads are then copied to the master params' ``.grad`` attributes (see second Note), which are guaranteed to be fp32. 5. Finally, master grads are divided by loss_scale. In this way, after :attr:`backward`, the master params have fresh gradients, and :attr:`step` may be called. .. note:: :attr:`backward` internally converts the loss to fp32 before applying the loss scale. This provides some additional safety against overflow if the user has supplied an fp16 loss value. However, for maximum overflow safety, the user should compute the loss criterion (MSE, cross entropy, etc) in fp32 before supplying it to :attr:`backward`. .. warning:: The gradients found in a model's leaves after the call to :attr:`backward` should not be regarded as valid in general, because it's possible they have been scaled (and in the case of dynamic loss scaling, the scale factor may change over time). If the user wants to inspect gradients after a call to :attr:`backward`, only the master gradients should be regarded as valid. These can be retrieved via :attr:`inspect_master_grad_data()`. Args: loss: The loss output by the user's model. loss may be either float or half (but see first Note above). update_master_grads (bool, optional, default=True): Option to copy fp16 grads to fp32 grads on this call. By setting this to False, the user can delay the copy, which is useful to eliminate redundant fp16->fp32 grad copies if :attr:`backward` is being called on multiple losses in one iteration. If set to False, the user becomes responsible for calling :attr:`update_master_grads` before calling :attr:`step`. retain_graph (bool, optional, default=False): Forwards the usual ``retain_graph=True`` option to the internal call to ``loss.backward``. If ``retain_graph`` is being used to accumulate gradient values from multiple backward passes before calling ``optimizer.step``, passing ``update_master_grads=False`` is also recommended (see Example below). Example:: # Ordinary operation: optimizer.backward(loss) # Naive operation with multiple losses (technically valid, but less efficient): # fp32 grads will be correct after the second call, but # the first call incurs an unnecessary fp16->fp32 grad copy. optimizer.backward(loss1) optimizer.backward(loss2) # More efficient way to handle multiple losses: # The fp16->fp32 grad copy is delayed until fp16 grads from all # losses have been accumulated. optimizer.backward(loss1, update_master_grads=False) optimizer.backward(loss2, update_master_grads=False) optimizer.update_master_grads() """ # To consider: try multiple backward passes using retain_grad=True to find # a loss scale that works. After you find a loss scale that works, do a final dummy # backward pass with retain_graph=False to tear down the graph. Doing this would avoid # discarding the iteration, but probably wouldn't improve overall efficiency. scaled_loss = loss.float()*self.loss_scaler.loss_scale() scaled_loss.backward(retain_graph=retain_graph) if update_master_grads: self.update_master_grads() def update_master_grads(self): # torch.cuda.nvtx.range_push("update_master_grads") """ Copy the ``.grad`` attribute from stored references to fp16 parameters to the ``.grad`` attribute of the fp32 master parameters that are directly updated by the optimizer. :attr:`update_master_grads` only needs to be called if ``fp16_optimizer_obj.backward`` was called with ``update_master_grads=False``. """ # if self.dynamic_loss_scale: # self._check_overflow() # if self.overflow: return # self._model_grads_to_master_grads() # self._downscale_master() # Use the one-shot multi-tensor apply kernel self.loss_scaler.clear_overflow_state() if len(self.all_fp16_params) > 0: # print("Model grads before") # print([param.grad.data for param in self.all_fp16_params]) # I'm ONLY writing this as an incremental way to make some tests pass until # I can refactor the tests as well. # FP16_Optimizer should not be used by anyone. model_grads = [] master_grads = [] for model_param, master_param in zip(self.all_fp16_params, self.all_fp32_from_fp16_params): if model_param.grad is not None: model_grads.append(model_param.grad) if master_param.grad is None: master_param.grad = torch.empty_like(master_param) master_grads.append(master_param.grad) self.loss_scaler.unscale( model_grads, master_grads, self.loss_scaler.loss_scale()) # print("Master grads after") # print([param.grad.data for param in self.all_fp32_from_fp16_params]) if len(self.all_fp32_from_fp32_params) > 0: model_grads = [] master_grads = [] for model_param, master_param in zip(self.all_fp32_from_fp32_params, self.all_fp32_from_fp32_params): if model_param.grad is not None: model_grads.append(model_param.grad) master_grads.append(master_param.grad) # print("Model grads before") # print([param.grad.data for param in self.all_fp32_from_fp32_params]) self.loss_scaler.unscale( model_grads, master_grads, self.loss_scaler.loss_scale()) # print("Master grads after") # print([param.grad.data for param in self.all_fp32_from_fp32_params]) # quit() self.overflow = self.loss_scaler.update_scale() # torch.cuda.nvtx.range_pop() def inspect_master_grad_data(self): """ When running with :class:`FP16_Optimizer`, ``.grad`` attributes of a model's fp16 leaves should not be regarded as truthful, because they might be scaled. After a call to :attr:`fp16_optimizer_obj.backward(loss)`, if no overflow was encountered, the fp32 master params' ``.grad`` attributes will contain valid gradients properly divided by the loss scale. However, because :class:`FP16_Optimizer` flattens some parameters, accessing them may be nonintuitive. :attr:`inspect_master_grad_data` allows those gradients to be viewed with shapes corresponding to their associated model leaves. Returns: List of lists (one list for each parameter group). The list for each parameter group is a list of the ``.grad.data`` attributes of the fp32 master params belonging to that group. """ if self.overflow: print("Warning: calling FP16_Optimizer.inspect_master_grad_data while in an overflow state. " "Gradients are currently invalid (may be inf, nan, or stale). Returning None.") return None else: # The optimizer owns only references to master params. master_grads_data = [] for param_group in self.optimizer.param_groups: master_grads_this_group = [] for param in param_group['params']: if param.grad is not None: master_grads_this_group.append(param.grad.data) else: master_grads_this_group.append(None) master_grads_data.append(master_grads_this_group) return master_grads_data # Promote loss scale so it can be retrieved or set via "fp16_optimizer_instance.loss_scale" def _get_loss_scale(self): return self.loss_scaler.loss_scale() def _set_loss_scale(self, value): self.loss_scaler._loss_scale = value loss_scale = property(_get_loss_scale, _set_loss_scale) # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state" def _get_state(self): return self.optimizer.state def _set_state(self, value): self.optimizer.state = value state = property(_get_state, _set_state) # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups" # (for example, to adjust the learning rate) def _get_param_groups(self): return self.optimizer.param_groups def _set_param_groups(self, value): self.optimizer.param_groups = value param_groups = property(_get_param_groups, _set_param_groups) ================================================ FILE: KoSimCSE/apex/fp16_utils/fp16util.py ================================================ import torch import torch.nn as nn from torch.autograd import Variable from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors class tofp16(nn.Module): """ Utility module that implements:: def forward(self, input): return input.half() """ def __init__(self): super(tofp16, self).__init__() def forward(self, input): return input.half() def BN_convert_float(module): """ Utility function for network_to_half(). Retained for legacy purposes. """ if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: module.float() for child in module.children(): BN_convert_float(child) return module def network_to_half(network): """ Convert model to half precision in a batchnorm-safe way. Retained for legacy purposes. It is recommended to use FP16Model. """ return nn.Sequential(tofp16(), BN_convert_float(network.half())) def convert_module(module, dtype): """ Converts a module's immediate parameters and buffers to dtype. """ for param in module.parameters(recurse=False): if param is not None: if param.data.dtype.is_floating_point: param.data = param.data.to(dtype=dtype) if param._grad is not None and param._grad.data.dtype.is_floating_point: param._grad.data = param._grad.data.to(dtype=dtype) for buf in module.buffers(recurse=False): if buf is not None and buf.data.dtype.is_floating_point: buf.data = buf.data.to(dtype=dtype) def convert_network(network, dtype): """ Converts a network's parameters and buffers to dtype. """ for module in network.modules(): if isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and module.affine is True: continue convert_module(module, dtype) if isinstance(module, torch.nn.RNNBase) or isinstance(module, torch.nn.modules.rnn.RNNBase): module.flatten_parameters() return network class FP16Model(nn.Module): """ Convert model to half precision in a batchnorm-safe way. """ def __init__(self, network): super(FP16Model, self).__init__() self.network = convert_network(network, dtype=torch.half) def forward(self, *inputs): inputs = tuple(t.half() for t in inputs) return self.network(*inputs) def backwards_debug_hook(grad): raise RuntimeError("master_params recieved a gradient in the backward pass!") def prep_param_lists(model, flat_master=False): """ Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a performance optimization. Returns: A tuple (``model_params``, ``master_params``). ``model_params`` is a list of the model's parameters for later use with :func:`model_grads_to_master_grads` and :func:`master_params_to_model_params`. ``master_params`` is a list of FP32 master gradients. If ``flat_master=True``, ``master_params`` will be a list with one element. Example:: model_params, master_params = prep_param_lists(model) .. warning:: Currently, if ``flat_master=True``, all the model's parameters must be the same type. If the model has parameters of different types, use ``flat_master=False``, or use :class:`FP16_Optimizer`. .. _`Training Neural Networks with Mixed Precision: Real Examples`: http://on-demand.gputechconf.com/gtc/2018/video/S81012/ """ model_params = [param for param in model.parameters() if param.requires_grad] if flat_master: # Give the user some more useful error messages try: # flatten_dense_tensors returns a contiguous flat array. # http://pytorch.org/docs/master/_modules/torch/_utils.html master_params = _flatten_dense_tensors([param.data for param in model_params]).float() except: print("Error in prep_param_lists: model may contain a mixture of parameters " "of different types. Use flat_master=False, or use F16_Optimizer.") raise master_params = torch.nn.Parameter(master_params) master_params.requires_grad = True # master_params.register_hook(backwards_debug_hook) if master_params.grad is None: master_params.grad = master_params.new(*master_params.size()) return model_params, [master_params] else: master_params = [param.clone().float().detach() for param in model_params] for param in master_params: param.requires_grad = True return model_params, master_params def model_grads_to_master_grads(model_params, master_params, flat_master=False): """ Copy model gradients to master gradients. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`model_grads_to_master_grads`. """ if flat_master: # The flattening may incur one more deep copy than is necessary. master_params[0].grad.data.copy_( _flatten_dense_tensors([p.grad.data for p in model_params])) else: for model, master in zip(model_params, master_params): if model.grad is not None: if master.grad is None: master.grad = Variable(master.data.new(*master.data.size())) master.grad.data.copy_(model.grad.data) else: master.grad = None def master_params_to_model_params(model_params, master_params, flat_master=False): """ Copy master parameters to model parameters. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`master_params_to_model_params`. """ if flat_master: for model, master in zip(model_params, _unflatten_dense_tensors(master_params[0].data, model_params)): model.data.copy_(master) else: for model, master in zip(model_params, master_params): model.data.copy_(master.data) # Backward compatibility fixes def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 0 and TORCH_MINOR <= 4: clip_grad_norm = torch.nn.utils.clip_grad_norm else: clip_grad_norm = torch.nn.utils.clip_grad_norm_ ================================================ FILE: KoSimCSE/apex/fp16_utils/loss_scaler.py ================================================ import torch # item() is a recent addition, so this helps with backward compatibility. def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] class LossScaler: """ Class that manages a static loss scale. This class is intended to interact with :class:`FP16_Optimizer`, and should not be directly manipulated by the user. Use of :class:`LossScaler` is enabled via the ``static_loss_scale`` argument to :class:`FP16_Optimizer`'s constructor. Args: scale (float, optional, default=1.0): The loss scale. """ def __init__(self, scale=1): self.cur_scale = scale # `params` is a list / generator of torch.Variable def has_overflow(self, params): return False # `x` is a torch.Tensor def _has_inf_or_nan(x): return False def update_scale(self, overflow): pass @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) class DynamicLossScaler: """ Class that manages dynamic loss scaling. It is recommended to use :class:`DynamicLossScaler` indirectly, by supplying ``dynamic_loss_scale=True`` to the constructor of :class:`FP16_Optimizer`. However, it's important to understand how :class:`DynamicLossScaler` operates, because the default options can be changed using the the ``dynamic_loss_args`` argument to :class:`FP16_Optimizer`'s constructor. Loss scaling is designed to combat the problem of underflowing gradients encountered at long times when training fp16 networks. Dynamic loss scaling begins by attempting a very high loss scale. Ironically, this may result in OVERflowing gradients. If overflowing gradients are encountered, :class:`DynamicLossScaler` informs :class:`FP16_Optimizer` that an overflow has occurred. :class:`FP16_Optimizer` then skips the update step for this particular iteration/minibatch, and :class:`DynamicLossScaler` adjusts the loss scale to a lower value. If a certain number of iterations occur without overflowing gradients detected, :class:`DynamicLossScaler` increases the loss scale once more. In this way :class:`DynamicLossScaler` attempts to "ride the edge" of always using the highest loss scale possible without incurring overflow. Args: init_scale (float, optional, default=2**32): Initial loss scale attempted by :class:`DynamicLossScaler.` scale_factor (float, optional, default=2.0): Factor used when adjusting the loss scale. If an overflow is encountered, the loss scale is readjusted to loss scale/``scale_factor``. If ``scale_window`` consecutive iterations take place without an overflow, the loss scale is readjusted to loss_scale*``scale_factor``. scale_window (int, optional, default=1000): Number of consecutive iterations without an overflow to wait before increasing the loss scale. """ def __init__(self, init_scale=2**32, scale_factor=2., scale_window=1000): self.cur_scale = init_scale self.cur_iter = 0 self.last_overflow_iter = -1 self.scale_factor = scale_factor self.scale_window = scale_window # `params` is a list / generator of torch.Variable def has_overflow(self, params): for p in params: if p.grad is not None and DynamicLossScaler._has_inf_or_nan(p.grad.data): return True return False # `x` is a torch.Tensor def _has_inf_or_nan(x): try: # if x is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as x # (which is true for some recent version of pytorch). cpu_sum = float(x.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # cpu_sum = float(x.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False # `overflow` is boolean indicating whether the gradient overflowed def update_scale(self, overflow): if overflow: # self.cur_scale /= self.scale_factor self.cur_scale = max(self.cur_scale/self.scale_factor, 1) self.last_overflow_iter = self.cur_iter else: if (self.cur_iter - self.last_overflow_iter) % self.scale_window == 0: self.cur_scale *= self.scale_factor self.cur_iter += 1 @property def loss_scale(self): return self.cur_scale def scale_gradient(self, module, grad_in, grad_out): return tuple(self.loss_scale * g for g in grad_in) def backward(self, loss, retain_graph=False): scaled_loss = loss*self.loss_scale scaled_loss.backward(retain_graph=retain_graph) ############################################################## # Example usage below here -- assuming it's in a separate file ############################################################## """ TO-DO separate out into an example. if __name__ == "__main__": import torch from torch.autograd import Variable from dynamic_loss_scaler import DynamicLossScaler # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, 100, 10 # Create random Tensors to hold inputs and outputs, and wrap them in Variables. x = Variable(torch.randn(N, D_in), requires_grad=False) y = Variable(torch.randn(N, D_out), requires_grad=False) w1 = Variable(torch.randn(D_in, H), requires_grad=True) w2 = Variable(torch.randn(H, D_out), requires_grad=True) parameters = [w1, w2] learning_rate = 1e-6 optimizer = torch.optim.SGD(parameters, lr=learning_rate) loss_scaler = DynamicLossScaler() for t in range(500): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() * loss_scaler.loss_scale print('Iter {} loss scale: {}'.format(t, loss_scaler.loss_scale)) print('Iter {} scaled loss: {}'.format(t, loss.data[0])) print('Iter {} unscaled loss: {}'.format(t, loss.data[0] / loss_scaler.loss_scale)) # Run backprop optimizer.zero_grad() loss.backward() # Check for overflow has_overflow = DynamicLossScaler.has_overflow(parameters) # If no overflow, unscale grad and update as usual if not has_overflow: for param in parameters: param.grad.data.mul_(1. / loss_scaler.loss_scale) optimizer.step() # Otherwise, don't do anything -- ie, skip iteration else: print('OVERFLOW!') # Update loss scale for next iteration loss_scaler.update_scale(has_overflow) """ ================================================ FILE: KoSimCSE/apex/mlp/__init__.py ================================================ from .mlp import * ================================================ FILE: KoSimCSE/apex/mlp/mlp.py ================================================ from copy import copy import math import torch from torch import nn import mlp_cuda from .. import amp class MlpFunction(torch.autograd.Function): @staticmethod def forward(ctx, bias, activation, *args): output = mlp_cuda.forward(bias, activation, args) ctx.save_for_backward(*args) ctx.outputs = output ctx.bias = bias ctx.activation = activation return output[0] @staticmethod def backward(ctx, grad_o): grads = mlp_cuda.backward(ctx.bias, ctx.activation, grad_o, ctx.outputs, ctx.saved_tensors) del ctx.outputs return (None, None, *grads) mlp_function = amp.half_function(MlpFunction.apply) class MLP(torch.nn.Module): """Launch MLP in C++ Args: mlp_sizes (list of int): MLP sizes. Example: [1024,1024,1024] will create 2 MLP layers with shape 1024x1024 bias (bool): Default True: relu (bool): Default True """ def __init__(self, mlp_sizes, bias=True, activation='relu'): super(MLP, self).__init__() self.num_layers = len(mlp_sizes) - 1 self.mlp_sizes = copy(mlp_sizes) self.bias = 1 if bias else 0 if activation is 'none': self.activation = 0 elif activation is 'relu': self.activation = 1 elif activation is 'sigmoid': self.activation = 2 else: raise TypeError("activation must be relu or none.") self.weights = [] self.biases = [] for i in range(self.num_layers): w = torch.nn.Parameter(torch.empty(mlp_sizes[i+1], mlp_sizes[i])) self.weights.append(w) name = 'weight_{}'.format(i) setattr(self, name, w) if self.bias: b = torch.nn.Parameter(torch.empty(mlp_sizes[i+1])) self.biases.append(b) name = 'bias_{}'.format(i) setattr(self, name, b) self.reset_parameters() def reset_parameters(self): for weight in self.weights: dimsum = weight.size(0) + weight.size(1) std = math.sqrt(2. / float(dimsum)) nn.init.normal_(weight, 0., std) if self.bias: for bias in self.biases: std = math.sqrt(1. / float(bias.size(0))) nn.init.normal_(bias, 0., std) def forward(self, input): return mlp_function(self.bias, self.activation, input, *self.weights, *self.biases) def extra_repr(self): s = F"MLP sizes: {self.mlp_sizes}, Bias={self.bias}, activation={self.activation}" return s ================================================ FILE: KoSimCSE/apex/multi_tensor_apply/__init__.py ================================================ from .multi_tensor_apply import MultiTensorApply multi_tensor_applier = MultiTensorApply(2048*32) ================================================ FILE: KoSimCSE/apex/multi_tensor_apply/multi_tensor_apply.py ================================================ import torch class MultiTensorApply(object): available = False warned = False def __init__(self, chunk_size): try: import amp_C MultiTensorApply.available = True self.chunk_size = chunk_size except ImportError as err: MultiTensorApply.available = False MultiTensorApply.import_err = err def check_avail(self): if MultiTensorApply.available == False: raise RuntimeError( "Attempted to call MultiTensorApply method, but MultiTensorApply " "is not available, possibly because Apex was installed without " "--cpp_ext --cuda_ext. Original import error message:", MultiTensorApply.import_err) def __call__(self, op, noop_flag_buffer, tensor_lists, *args): self.check_avail() return op(self.chunk_size, noop_flag_buffer, tensor_lists, *args) ================================================ FILE: KoSimCSE/apex/normalization/__init__.py ================================================ from .fused_layer_norm import FusedLayerNorm ================================================ FILE: KoSimCSE/apex/normalization/fused_layer_norm.py ================================================ import math import torch import numbers from torch.nn.parameter import Parameter from torch.nn import init from torch.nn import functional as F import importlib global fused_layer_norm_cuda fused_layer_norm_cuda = None class FusedLayerNormAffineFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, weight, bias, normalized_shape, eps): global fused_layer_norm_cuda if fused_layer_norm_cuda is None: fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") ctx.normalized_shape = normalized_shape ctx.eps = eps input_ = input.contiguous() weight_ = weight.contiguous() bias_ = bias.contiguous() output, mean, invvar = fused_layer_norm_cuda.forward_affine( input_, ctx.normalized_shape, weight_, bias_, ctx.eps) ctx.save_for_backward(input_, weight_, bias_, mean, invvar) return output @staticmethod def backward(ctx, grad_output): input_, weight_, bias_, mean, invvar = ctx.saved_tensors grad_input = grad_weight = grad_bias = None grad_input, grad_weight, grad_bias = fused_layer_norm_cuda.backward_affine( grad_output.contiguous(), mean, invvar, input_, ctx.normalized_shape, weight_, bias_, ctx.eps) return grad_input, grad_weight, grad_bias, None, None class FusedLayerNormFunction(torch.autograd.Function): @staticmethod def forward(ctx, input, normalized_shape, eps): global fused_layer_norm_cuda if fused_layer_norm_cuda is None: fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") ctx.normalized_shape = normalized_shape ctx.eps = eps input_ = input.contiguous() output, mean, invvar = fused_layer_norm_cuda.forward( input_, ctx.normalized_shape, ctx.eps) ctx.save_for_backward(input_, mean, invvar) return output @staticmethod def backward(ctx, grad_output): input_, mean, invvar = ctx.saved_tensors grad_input = None grad_input = fused_layer_norm_cuda.backward( grad_output.contiguous(), mean, invvar, input_, ctx.normalized_shape, ctx.eps) return grad_input, None, None def fused_layer_norm_affine(input, normalized_shape, weight, bias, eps=1e-6): return FusedLayerNormAffineFunction.apply(input, weight, bias, normalized_shape, eps) def fused_layer_norm(input, normalized_shape, eps=1e-6): return FusedLayerNormFunction.apply(input, normalized_shape, eps) class FusedLayerNorm(torch.nn.Module): r"""Applies Layer Normalization over a mini-batch of inputs as described in the paper `Layer Normalization`_ . Currently only runs on cuda() tensors. .. math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated separately over the last certain number dimensions which have to be of the shape specified by :attr:`normalized_shape`. :math:`\gamma` and :math:`\beta` are learnable affine transform parameters of :attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``. .. note:: Unlike Batch Normalization and Instance Normalization, which applies scalar scale and bias for each entire channel/plane with the :attr:`affine` option, Layer Normalization applies per-element scale and bias with :attr:`elementwise_affine`. This layer uses statistics computed from input data in both training and evaluation modes. Args: normalized_shape (int or list or torch.Size): input shape from an expected input of size .. math:: [* \times \text{normalized}\_\text{shape}[0] \times \text{normalized}\_\text{shape}[1] \times \ldots \times \text{normalized}\_\text{shape}[-1]] If a single integer is used, it is treated as a singleton list, and this module will normalize over the last dimension which is expected to be of that specific size. eps: a value added to the denominator for numerical stability. Default: 1e-5 elementwise_affine: a boolean value that when set to ``True``, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases). Default: ``True``. Shape: - Input: :math:`(N, *)` - Output: :math:`(N, *)` (same shape as input) Examples:: >>> input = torch.randn(20, 5, 10, 10) >>> # With Learnable Parameters >>> m = apex.normalization.FusedLayerNorm(input.size()[1:]) >>> # Without Learnable Parameters >>> m = apex.normalization.FusedLayerNorm(input.size()[1:], elementwise_affine=False) >>> # Normalize over last two dimensions >>> m = apex.normalization.FusedLayerNorm([10, 10]) >>> # Normalize over last dimension of size 10 >>> m = apex.normalization.FusedLayerNorm(10) >>> # Activating the module >>> output = m(input) .. _`Layer Normalization`: https://arxiv.org/abs/1607.06450 """ def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True): super(FusedLayerNorm, self).__init__() global fused_layer_norm_cuda fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda") if isinstance(normalized_shape, numbers.Integral): normalized_shape = (normalized_shape,) self.normalized_shape = torch.Size(normalized_shape) self.eps = eps self.elementwise_affine = elementwise_affine if self.elementwise_affine: self.weight = Parameter(torch.Tensor(*normalized_shape)) self.bias = Parameter(torch.Tensor(*normalized_shape)) else: self.register_parameter('weight', None) self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): if self.elementwise_affine: init.ones_(self.weight) init.zeros_(self.bias) def forward(self, input): if not input.is_cuda: return F.layer_norm( input, self.normalized_shape, self.weight, self.bias, self.eps) if self.elementwise_affine: return FusedLayerNormAffineFunction.apply( input, self.weight, self.bias, self.normalized_shape,self.eps) else: return FusedLayerNormFunction.apply(input, self.normalized_shape, self.eps) def extra_repr(self): return '{normalized_shape}, eps={eps}, ' \ 'elementwise_affine={elementwise_affine}'.format(**self.__dict__) ================================================ FILE: KoSimCSE/apex/optimizers/__init__.py ================================================ from .fused_sgd import FusedSGD from .fused_adam import FusedAdam from .fused_novograd import FusedNovoGrad from .fused_lamb import FusedLAMB from .fused_adagrad import FusedAdagrad ================================================ FILE: KoSimCSE/apex/optimizers/fused_adagrad.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedAdagrad(torch.optim.Optimizer): """Implements Adagrad algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused Adagrad implements 2 fusions. * Fusion of the Adagrad update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedAdagrad`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedAdagrad(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedAdagrad` may be used with or without Amp. If you wish to use :class:`FusedAdagrad` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedAdagrad(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. It has been proposed in `Adaptive Subgradient Methods for Online Learning and Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-2) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-10) adagrad_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay (also known as AdamW) (default: False) .. _Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: http://jmlr.org/papers/v12/duchi11a.html """ def __init__(self, params, lr=1e-2, eps=1e-10, weight_decay=0., set_grad_none=True, adagrad_w_mode=False): defaults = dict(lr=lr, eps=eps, weight_decay=weight_decay) super(FusedAdagrad, self).__init__(params, defaults) self.adagrad_w_mode = 1 if adagrad_w_mode else 0 self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_adagrad = amp_C.multi_tensor_adagrad else: raise RuntimeError('apex.optimizers.FusedAdagrad requires cuda extensions') def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedAdagrad, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: # create lists for multi-tensor apply g_16, p_16, h_16 = [], [], [] g_32, p_32, h_32 = [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedAdagrad does not support sparse gradients') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['sum'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) h_16.append(state['sum']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) h_32.append(state['sum']) else: raise RuntimeError('FusedAdagrad only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_adagrad, self._dummy_overflow_buf, [g_16, p_16, h_16], group['lr'], group['eps'], self.adagrad_w_mode, group['weight_decay']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_adagrad, self._dummy_overflow_buf, [g_32, p_32, h_32], group['lr'], group['eps'], self.adagrad_w_mode, group['weight_decay']) return loss ================================================ FILE: KoSimCSE/apex/optimizers/fused_adam.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedAdam(torch.optim.Optimizer): """Implements Adam algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused Adam implements 2 fusions. * Fusion of the Adam update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedAdam` may be used as a drop-in replacement for ``torch.optim.AdamW``, or ``torch.optim.Adam`` with ``adam_w_mode=False``:: opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedAdam` may be used with or without Amp. If you wish to use :class:`FusedAdam` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedAdam(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. .. warning:: A previous version of :class:`FusedAdam` allowed a number of additional arguments to ``step``. These additional arguments are now deprecated and unnecessary. Adam was been proposed in `Adam: A Method for Stochastic Optimization`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ (default: False) NOT SUPPORTED in FusedAdam! adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) .. _Adam - A Method for Stochastic Optimization: https://arxiv.org/abs/1412.6980 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, adam_w_mode=True, weight_decay=0., amsgrad=False, set_grad_none=True): if amsgrad: raise RuntimeError('FusedAdam does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay) super(FusedAdam, self).__init__(params, defaults) self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.cuda.IntTensor([0]) self.multi_tensor_adam = amp_C.multi_tensor_adam else: raise RuntimeError('apex.optimizers.FusedAdam requires cuda extensions') def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedAdam, self).zero_grad() def step(self, closure=None, grads=None, output_params=None, scale=None, grad_norms=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. The remaining arguments are deprecated, and are only retained (for the moment) for error-checking purposes. """ if any(p is not None for p in [grads, output_params, scale, grad_norms]): raise RuntimeError('FusedAdam has been updated. Simply initialize it identically to torch.optim.Adam, and call step() with no arguments.') loss = None if closure is not None: loss = closure() for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedAdam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedAdam only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_adam, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], self.adam_w_mode, bias_correction, group['weight_decay']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_adam, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], self.adam_w_mode, bias_correction, group['weight_decay']) return loss ================================================ FILE: KoSimCSE/apex/optimizers/fused_lamb.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedLAMB(torch.optim.Optimizer): """Implements LAMB algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused LAMB implements 2 fusions. * Fusion of the LAMB update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedLAMB`'s usage is identical to any ordinary Pytorch optimizer:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedLAMB` may be used with or without Amp. If you wish to use :class:`FusedLAMB` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedLAMB(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. LAMB was proposed in `Large Batch Optimization for Deep Learning: Training BERT in 76 minutes`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) adam_w_mode (boolean, optional): Apply L2 regularization or weight decay True for decoupled weight decay(also known as AdamW) (default: True) grad_averaging (bool, optional): whether apply (1-beta2) to grad when calculating running averages of gradient. (default: True) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) max_grad_norm (float, optional): value used to clip global grad norm (default: 1.0) use_nvlamb (boolean, optional): Apply adaptive learning rate to 0.0 weight decay parameter (default: False) .. _Large Batch Optimization for Deep Learning - Training BERT in 76 minutes: https://arxiv.org/abs/1904.00962 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-6, weight_decay=0.01, amsgrad=False, adam_w_mode=True, grad_averaging=True, set_grad_none=True, max_grad_norm=1.0, use_nvlamb=False): if amsgrad: raise RuntimeError('FusedLAMB does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, max_grad_norm=max_grad_norm) super(FusedLAMB, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C self.multi_tensor_l2norm=amp_C.multi_tensor_l2norm # Skip buffer self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_lamb = amp_C.multi_tensor_lamb else: raise RuntimeError('apex.optimizers.FusedLAMB requires cuda extensions') self.adam_w_mode = 1 if adam_w_mode else 0 self.set_grad_none = set_grad_none self.use_nvlamb = use_nvlamb def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedLAMB, self).zero_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() # create separate grad lists for fp32 and fp16 params g_all_32, g_all_16 = [], [] for group in self.param_groups: for p in group['params']: if p.grad is None: continue if p.dtype == torch.float32: g_all_32.append(p.grad.data) elif p.dtype == torch.float16: g_all_16.append(p.grad.data) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') device = self.param_groups[0]["params"][0].device g_norm_32, g_norm_16 = torch.zeros(1, device=device), torch.zeros(1, device=device) # compute grad norm for two lists if len(g_all_32) > 0: g_norm_32 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_32], False)[0] if len(g_all_16) > 0: g_norm_16 = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [g_all_16], False)[0] # blend two grad norms to get global grad norm global_grad_norm = multi_tensor_applier(self.multi_tensor_l2norm, self._dummy_overflow_buf, [[g_norm_32, g_norm_16]], False)[0] max_grad_norm = self.defaults['max_grad_norm'] for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16, v_16 = [], [], [], [] g_32, p_32, m_32, v_32 = [], [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedLAMB does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) v_16.append(state['exp_avg_sq']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) v_32.append(state['exp_avg_sq']) else: raise RuntimeError('FusedLAMB only support fp16 and fp32.') if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_16, p_16, m_16, v_16], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm, self.use_nvlamb) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_lamb, self._dummy_overflow_buf, [g_32, p_32, m_32, v_32], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.adam_w_mode, global_grad_norm, max_grad_norm, self.use_nvlamb) return loss ================================================ FILE: KoSimCSE/apex/optimizers/fused_novograd.py ================================================ import torch from apex.multi_tensor_apply import multi_tensor_applier class FusedNovoGrad(torch.optim.Optimizer): """Implements NovoGrad algorithm. Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused NovoGrad implements 2 fusions. * Fusion of the NovoGrad update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedNovoGrad`'s usage is identical to any Pytorch optimizer:: opt = apex.optimizers.FusedNovoGrad(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedNovoGrad` may be used with or without Amp. If you wish to use :class:`FusedNovoGrad` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedNovoGrad(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. It has been proposed in `Jasper: An End-to-End Convolutional Neural Acoustic Model`_. More info: https://nvidia.github.io/OpenSeq2Seq/html/optimizers.html#novograd Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups. lr (float, optional): learning rate. (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its norm. (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability. (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) amsgrad (boolean, optional): whether to use the AMSGrad variant of this algorithm from the paper `On the Convergence of Adam and Beyond`_ NOT SUPPORTED now! (default: False) reg_inside_moment (bool, optional): whether do regularization (norm and L2) in momentum calculation. True for include, False for not include and only do it on update term. (default: False) grad_averaging (bool, optional): whether apply (1-beta1) to grad when calculating running averages of gradient. (default: True) norm_type (int, optional): which norm to calculate for each layer. 2 for L2 norm, and 0 for infinite norm. These 2 are only supported type now. (default: 2) init_zero (bool, optional): whether init norm with 0 (start averaging on 1st step) or first step norm (start averaging on 2nd step). True for init with 0. (default: False) set_grad_none (bool, optional): whether set grad to None when zero_grad() method is called. (default: True) .. _Jasper - An End-to-End Convolutional Neural Acoustic Model: https://arxiv.org/abs/1904.03288 .. _On the Convergence of Adam and Beyond: https://openreview.net/forum?id=ryQu7f-RZ """ def __init__(self, params, lr=1e-3, bias_correction=True, betas=(0.9, 0.999), eps=1e-8, weight_decay=0., amsgrad=False, reg_inside_moment=False, grad_averaging=True, norm_type=2, init_zero=False, set_grad_none=True): if amsgrad: raise RuntimeError('FusedNovoGrad does not support the AMSGrad variant.') defaults = dict(lr=lr, bias_correction=bias_correction, betas=betas, eps=eps, weight_decay=weight_decay, grad_averaging=grad_averaging, norm_type=norm_type, init_zero=init_zero) super(FusedNovoGrad, self).__init__(params, defaults) if multi_tensor_applier.available: import amp_C # Skip buffer # Creating the overflow buffer on the same device as the params tensors. self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_novograd = amp_C.multi_tensor_novograd else: raise RuntimeError('apex.optimizers.FusedNovoGrad requires cuda extensions') self.moment_mode = 0 if reg_inside_moment else 1 self.set_grad_none = set_grad_none def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedNovoGrad, self).zero_grad() def load_state_dict(self, state_dict): super(FusedNovoGrad, self).load_state_dict(state_dict) # in case exp_avg_sq is not on the same device as params, move it there for group in self.param_groups: if len(group['params']) > 0: group['exp_avg_sq'][0] = group['exp_avg_sq'][0].to(group['params'][0].device) group['exp_avg_sq'][1] = group['exp_avg_sq'][1].to(group['params'][0].device) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: bias_correction = 1 if group['bias_correction'] else 0 beta1, beta2 = group['betas'] grad_averaging = 1 if group['grad_averaging'] else 0 # assume same step across group now to simplify things # per parameter step can be easily support by making it tensor, or pass list into kernel if 'step' in group: group['step'] += 1 else: group['step'] = 1 # create lists for multi-tensor apply g_16, p_16, m_16 = [], [], [] g_32, p_32, m_32 = [], [], [] for p in group['params']: if p.grad is None: continue if p.grad.data.is_sparse: raise RuntimeError('FusedNovoGrad does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if len(state) == 0: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) if p.dtype == torch.float16: g_16.append(p.grad.data) p_16.append(p.data) m_16.append(state['exp_avg']) elif p.dtype == torch.float32: g_32.append(p.grad.data) p_32.append(p.data) m_32.append(state['exp_avg']) else: raise RuntimeError('FusedNovoGrad only support fp16 and fp32.') # we store per weight norm as one tensor for one group/precision combination # different from optim.Adam, we store norm here(not ^2) so we can unify calculation for norm types if 'exp_avg_sq' not in group: group['exp_avg_sq'] = [None, None] if group['init_zero']: # Creating the following parameters on the same device as the params tensors. group['exp_avg_sq'][0] = torch.cuda.FloatTensor(len(g_16), device=self.param_groups[0]["params"][0].device).contiguous().fill_(0) group['exp_avg_sq'][1] = torch.cuda.FloatTensor(len(g_32), device=self.param_groups[0]["params"][0].device).contiguous().fill_(0) else: # init with first step norm, so first blend have no effect if group['norm_type'] == 0: v_16 = [torch.max(torch.abs(g.to(torch.float32))).item() for g in g_16] v_32 = [torch.max(torch.abs(g)).item() for g in g_32] elif group['norm_type'] == 2: v_16 = [torch.sum(torch.pow(g.to(torch.float32), 2)).sqrt().item() for g in g_16] v_32 = [torch.sum(torch.pow(g, 2)).sqrt().item() for g in g_32] else: raise RuntimeError('FusedNovoGrad only support l2/inf norm now.') # Creating the following parameters on the same device as the params tensors. group['exp_avg_sq'][0] = torch.cuda.FloatTensor(v_16, device=self.param_groups[0]["params"][0].device) group['exp_avg_sq'][1] = torch.cuda.FloatTensor(v_32, device=self.param_groups[0]["params"][0].device) else: assert(len(g_16) == group['exp_avg_sq'][0].numel()) assert(len(g_32) == group['exp_avg_sq'][1].numel()) if(len(g_16) > 0): multi_tensor_applier(self.multi_tensor_novograd, self._dummy_overflow_buf, [g_16, p_16, m_16], group['exp_avg_sq'][0], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.moment_mode, group['norm_type']) if(len(g_32) > 0): multi_tensor_applier(self.multi_tensor_novograd, self._dummy_overflow_buf, [g_32, p_32, m_32], group['exp_avg_sq'][1], group['lr'], beta1, beta2, group['eps'], group['step'], bias_correction, group['weight_decay'], grad_averaging, self.moment_mode, group['norm_type']) return loss ================================================ FILE: KoSimCSE/apex/optimizers/fused_sgd.py ================================================ import torch from torch.optim.optimizer import Optimizer, required from apex.multi_tensor_apply import multi_tensor_applier class FusedSGD(Optimizer): r"""Implements stochastic gradient descent (optionally with momentum). Currently GPU-only. Requires Apex to be installed via ``pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./``. This version of fused SGD implements 2 fusions. * Fusion of the SGD update's elementwise operations * A multi-tensor apply launch that batches the elementwise updates applied to all the model's parameters into one or a few kernel launches. :class:`apex.optimizers.FusedSGD` may be used as a drop-in replacement for ``torch.optim.SGD``:: opt = apex.optimizers.FusedSGD(model.parameters(), lr = ....) ... opt.step() :class:`apex.optimizers.FusedSGD` may be used with or without Amp. If you wish to use :class:`FusedSGD` with Amp, you may choose any ``opt_level``:: opt = apex.optimizers.FusedSGD(model.parameters(), lr = ....) model, opt = amp.initialize(model, opt, opt_level="O0" or "O1 or "O2") ... opt.step() In general, ``opt_level="O1"`` is recommended. Nesterov momentum is based on the formula from `On the importance of initialization and momentum in deep learning`__. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float): learning rate momentum (float, optional): momentum factor (default: 0) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) dampening (float, optional): dampening for momentum (default: 0) nesterov (bool, optional): enables Nesterov momentum (default: False) Example: >>> optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) >>> optimizer.zero_grad() >>> loss_fn(model(input), target).backward() >>> optimizer.step() __ http://www.cs.toronto.edu/%7Ehinton/absps/momentum.pdf .. note:: The implementation of SGD with Momentum/Nesterov subtly differs from Sutskever et. al. and implementations in some other frameworks. Considering the specific case of Momentum, the update can be written as .. math:: v = \rho * v + g \\ p = p - lr * v where p, g, v and :math:`\rho` denote the parameters, gradient, velocity, and momentum respectively. This is in contrast to Sutskever et. al. and other frameworks which employ an update of the form .. math:: v = \rho * v + lr * g \\ p = p - v The Nesterov version is analogously modified. """ def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, wd_after_momentum=False, materialize_master_grads=True, set_grad_none=False): if lr is not required and lr < 0.0: raise ValueError("Invalid learning rate: {}".format(lr)) if momentum < 0.0: raise ValueError("Invalid momentum value: {}".format(momentum)) if weight_decay < 0.0: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov) if nesterov and (momentum <= 0 or dampening != 0): raise ValueError("Nesterov momentum requires a momentum and zero dampening") super(FusedSGD, self).__init__(params, defaults) self.wd_after_momentum = wd_after_momentum self.materialize_master_grads = materialize_master_grads self.most_recent_scale = 1.0 self.scale_set_by_backward = False self.set_grad_none = set_grad_none if multi_tensor_applier.available: import amp_C # Skip buffer self._dummy_overflow_buf = torch.tensor([0], dtype=torch.int, device=self.param_groups[0]["params"][0].device) self.multi_tensor_sgd = amp_C.multi_tensor_sgd else: raise RuntimeError('apex.optimizers.FusedSGD requires cuda extensions') def __setstate__(self, state): super(FusedSGD, self).__setstate__(state) for group in self.param_groups: group.setdefault('nesterov', False) def zero_grad(self): if self.set_grad_none: for group in self.param_groups: for p in group['params']: p.grad = None else: super(FusedSGD, self).zero_grad() def get_momentums(self, params): momentums = [] first_run = True for p in params: param_state = self.state[p] # torch.optim.SGD initializes momentum in the main loop, we have # to do it here, and track whether or not we've done so, so that # momentum application can be skipped in the main kernel. if 'momentum_buffer' not in param_state: first_run = True buf = param_state['momentum_buffer'] = torch.zeros_like(p.data) momentums.append(buf) else: first_run = False momentums.append(param_state['momentum_buffer']) return momentums, first_run def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() explicit_master_params = (hasattr(self, "_amp_stash") and hasattr(self._amp_stash, "fp32_from_fp16_groups")) for gid, group in enumerate(self.param_groups): weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] # For each group, there are 3 possible combinations we need to consider: # grad_type, param_to_update_type, momentum_type, requires_fp16_model_copy # 1. fp16, fp16, fp16, No # 2. fp32, fp32, fp32, No # 3. fp16, fp32, fp32, Yes first_runs = [True, True] # I think a bit of code divergence in exchange for naming clarity is worthwhile if explicit_master_params: stash = self._amp_stash fp32_params = [p for p in stash.fp32_from_fp32_groups[gid] if p.grad is not None] fp32_grads = [p.grad for p in stash.fp32_from_fp32_groups[gid] if p.grad is not None] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) if self.materialize_master_grads: fp16_model_params = [p for i, p in enumerate( stash.fp16_groups[gid]) if stash.fp32_from_fp16_groups[gid][i].grad is not None] fp32_from_fp16_grads = [p.grad for p in stash.fp32_from_fp16_groups[gid] if p.grad is not None] fp32_from_fp16_params = [p for p in stash.fp32_from_fp16_groups[gid] if p.grad is not None] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_set = [fp32_from_fp16_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_model_params] else: fp16_model_params = [p for p in stash.fp16_groups[gid] if p.grad is not None] fp16_model_grads = [p.grad for p in stash.fp16_groups[gid] if p.grad is not None] fp32_from_fp16_params = [p for i, p in enumerate( stash.fp32_from_fp16_groups[gid]) if stash.fp16_groups[gid][i].grad is not None] fp32_from_fp16_momentums, first_runs[0] = self.get_momentums(fp32_from_fp16_params) fp16_set = [fp16_model_grads, fp32_from_fp16_params, fp32_from_fp16_momentums, fp16_model_params] launch_sets= [fp16_set, [fp32_grads, fp32_params, fp32_momentums]] else: fp16_params = [p for p in group['params'] if (p.dtype == torch.float16 and p.grad is not None)] fp16_grads = [p.grad for p in group['params'] if (p.dtype == torch.float16 and p.grad is not None)] fp16_momentums, first_runs[0] = self.get_momentums(fp16_params) fp32_params = [p for p in group['params'] if (p.dtype == torch.float32 and p.grad is not None)] fp32_grads = [p.grad for p in group['params'] if (p.dtype == torch.float32 and p.grad is not None)] fp32_momentums, first_runs[1] = self.get_momentums(fp32_params) launch_sets = [[fp16_grads, fp16_params, fp16_momentums], [fp32_grads, fp32_params, fp32_momentums]] for s, (launch_set, first_run) in enumerate(zip(launch_sets, first_runs)): assert len(launch_set[0]) == len(launch_set[1]) assert len(launch_set[0]) == len(launch_set[2]) if len(launch_set[0]) > 0: multi_tensor_applier( self.multi_tensor_sgd, self._dummy_overflow_buf, launch_set, weight_decay, momentum, dampening, group['lr'], nesterov, first_run, self.wd_after_momentum, 1.0/self.most_recent_scale) self.most_recent_scale = 1.0 self.scale_set_by_backward = False return loss ================================================ FILE: KoSimCSE/apex/parallel/LARC.py ================================================ import torch from torch import nn from torch.nn.parameter import Parameter class LARC(object): """ :class:`LARC` is a pytorch implementation of both the scaling and clipping variants of LARC, in which the ratio between gradient and parameter magnitudes is used to calculate an adaptive local learning rate for each individual parameter. The algorithm is designed to improve convergence of large batch training. See https://arxiv.org/abs/1708.03888 for calculation of the local learning rate. In practice it modifies the gradients of parameters as a proxy for modifying the learning rate of the parameters. This design allows it to be used as a wrapper around any torch.optim Optimizer. ``` model = ... optim = torch.optim.Adam(model.parameters(), lr=...) optim = LARC(optim) ``` It can even be used in conjunction with apex.fp16_utils.FP16_optimizer. ``` model = ... optim = torch.optim.Adam(model.parameters(), lr=...) optim = LARC(optim) optim = apex.fp16_utils.FP16_Optimizer(optim) ``` Args: optimizer: Pytorch optimizer to wrap and modify learning rate for. trust_coefficient: Trust coefficient for calculating the lr. See https://arxiv.org/abs/1708.03888 clip: Decides between clipping or scaling mode of LARC. If `clip=True` the learning rate is set to `min(optimizer_lr, local_lr)` for each parameter. If `clip=False` the learning rate is set to `local_lr*optimizer_lr`. eps: epsilon kludge to help with numerical stability while calculating adaptive_lr """ def __init__(self, optimizer, trust_coefficient=0.02, clip=True, eps=1e-8): self.optim = optimizer self.trust_coefficient = trust_coefficient self.eps = eps self.clip = clip def __getstate__(self): return self.optim.__getstate__() def __setstate__(self, state): self.optim.__setstate__(state) @property def state(self): return self.optim.state def __repr__(self): return self.optim.__repr__() @property def param_groups(self): return self.optim.param_groups @param_groups.setter def param_groups(self, value): self.optim.param_groups = value def state_dict(self): return self.optim.state_dict() def load_state_dict(self, state_dict): self.optim.load_state_dict(state_dict) def zero_grad(self): self.optim.zero_grad() def add_param_group(self, param_group): self.optim.add_param_group( param_group) def step(self): with torch.no_grad(): weight_decays = [] for group in self.optim.param_groups: # absorb weight decay control from optimizer weight_decay = group['weight_decay'] if 'weight_decay' in group else 0 weight_decays.append(weight_decay) group['weight_decay'] = 0 for p in group['params']: if p.grad is None: continue param_norm = torch.norm(p.data) grad_norm = torch.norm(p.grad.data) if param_norm != 0 and grad_norm != 0: # calculate adaptive lr + weight decay adaptive_lr = self.trust_coefficient * (param_norm) / (grad_norm + param_norm * weight_decay + self.eps) # clip learning rate for LARC if self.clip: # calculation of adaptive_lr so that when multiplied by lr it equals `min(adaptive_lr, lr)` adaptive_lr = min(adaptive_lr/group['lr'], 1) p.grad.data += weight_decay * p.data p.grad.data *= adaptive_lr self.optim.step() # return weight decay control to optimizer for i, group in enumerate(self.optim.param_groups): group['weight_decay'] = weight_decays[i] ================================================ FILE: KoSimCSE/apex/parallel/README.md ================================================ ## Distributed Data Parallel distributed.py contains the source code for `apex.parallel.DistributedDataParallel`, a module wrapper that enables multi-process multi-GPU data parallel training optimized for NVIDIA's NCCL communication library. `apex.parallel.DistributedDataParallel` achieves high performance by overlapping communication with computation in the backward pass and bucketing smaller transfers to reduce the total number of transfers required. multiproc.py contains the source code for `apex.parallel.multiproc`, a launch utility that places one process on each of the node's available GPUs. #### [API Documentation](https://nvidia.github.io/apex/parallel.html) #### [Example/Walkthrough](https://github.com/NVIDIA/apex/tree/master/examples/distributed) #### [Imagenet example with Mixed Precision](https://github.com/NVIDIA/apex/tree/master/examples/imagenet) #### [Simple example with FP16_Optimizer](https://github.com/NVIDIA/apex/tree/master/examples/FP16_Optimizer_simple/distributed_apex) ### Synchronized Batch Normalization `apex.parallel.SyncBatchNorm` has similar APIs as with `torch.nn.BatchNorm*N*d`. It reduces stats on the first (channel) dimension of the Tensor and accepts arbitrary spatial dimensions. #### Installation Apex provides two sync BN implementation: 1. There is the Python-only implementation, which is the default implementation when install with `python setup.py install`. It uses PyTorch primitive operations and distributed communication package from `torch.distributed`. - _Python-only implementation requires input tensor to be of same data type as layer_ 2. We also provide implementation with kernels through CUDA/C++ extension with improved performance. We are experimenting with Welford and Kahan for reduction hoping to get better accuracy. To use the kernel implementation, user need to install Apex with CUDA extension enabled `python setup.py install --cuda_ext`. - _Custom kernel implementation supports fp16 input with fp32 layer as cudnn. This is required to run imagenet example in fp16._ - _Currently kernel implementation only supports GPU._ #### HowTo 1. User could use `apex.parallel.SyncBatchNorm` by building their module with the layer explicitly. ``` import apex input_t = torch.randn(3, 5, 20).cuda() sbn = apex.parallel.SyncBatchNorm(5).cuda() output_t = sbn(input) ``` 2. User could also take a constructed `torch.nn.Model` and replace all its `torch.nn.BatchNorm*N*d` modules with `apex.parallel.SyncBatchNorm` through utility function `apex.parallel.convert_syncbn_model`. ``` # model is an instance of torch.nn.Module import apex sync_bn_model = apex.parallel.convert_syncbn_model(model) ``` ================================================ FILE: KoSimCSE/apex/parallel/__init__.py ================================================ import torch if hasattr(torch.distributed, 'ReduceOp'): ReduceOp = torch.distributed.ReduceOp elif hasattr(torch.distributed, 'reduce_op'): ReduceOp = torch.distributed.reduce_op else: ReduceOp = torch.distributed.deprecated.reduce_op from .distributed import DistributedDataParallel, Reducer # This is tricky because I'd like SyncBatchNorm to be exposed the same way # for both the cuda-enabled and python-fallback versions, and I don't want # to suppress the error information. try: import syncbn from .optimized_sync_batchnorm import SyncBatchNorm except ImportError as err: from .sync_batchnorm import SyncBatchNorm SyncBatchNorm.syncbn_import_error = err def convert_syncbn_model(module, process_group=None, channel_last=False): ''' Recursively traverse module and its children to replace all instances of ``torch.nn.modules.batchnorm._BatchNorm`` with :class:`apex.parallel.SyncBatchNorm`. All ``torch.nn.BatchNorm*N*d`` wrap around ``torch.nn.modules.batchnorm._BatchNorm``, so this function lets you easily switch to use sync BN. Args: module (torch.nn.Module): input module Example:: >>> # model is an instance of torch.nn.Module >>> import apex >>> sync_bn_model = apex.parallel.convert_syncbn_model(model) ''' mod = module if isinstance(module, torch.nn.modules.instancenorm._InstanceNorm): return module if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): mod = SyncBatchNorm(module.num_features, module.eps, module.momentum, module.affine, module.track_running_stats, process_group, channel_last=channel_last) mod.running_mean = module.running_mean mod.running_var = module.running_var mod.num_batches_tracked = module.num_batches_tracked if module.affine: mod.weight.data = module.weight.data.clone().detach() mod.bias.data = module.bias.data.clone().detach() for name, child in module.named_children(): mod.add_module(name, convert_syncbn_model(child, process_group=process_group, channel_last=channel_last)) # TODO(jie) should I delete model explicitly? del module return mod def create_syncbn_process_group(group_size): ''' Creates process groups to be used for syncbn of a give ``group_size`` and returns process group that current GPU participates in. ``group_size`` must divide the total number of GPUs (world_size). ``group_size`` of 0 would be considered as =world_size. In this case ``None`` will be returned. ``group_size`` of 1 would be equivalent to using non-sync bn, but will still carry the overhead. Args: group_size (int): number of GPU's to collaborate for sync bn Example:: >>> # model is an instance of torch.nn.Module >>> import apex >>> group = apex.parallel.create_syncbn_process_group(group_size) ''' if group_size==0: return None world_size = torch.distributed.get_world_size() assert(world_size >= group_size) assert(world_size % group_size == 0) group=None for group_num in (range(world_size//group_size)): group_ids = range(group_num*group_size, (group_num+1)*group_size) cur_group = torch.distributed.new_group(ranks=group_ids) if (torch.distributed.get_rank()//group_size == group_num): group = cur_group #can not drop out and return here, every process must go through creation of all subgroups assert(group is not None) return group ================================================ FILE: KoSimCSE/apex/parallel/distributed.py ================================================ import torch import torch.distributed as dist from torch.nn.modules import Module from torch.autograd import Variable from collections import OrderedDict from itertools import chain import copy import importlib from ..multi_tensor_apply import multi_tensor_applier imported_flatten_impl = False def import_flatten_impl(): global flatten_impl, unflatten_impl, imported_flatten_impl try: import apex_C flatten_impl = apex_C.flatten unflatten_impl = apex_C.unflatten except ImportError: print("Warning: apex was installed without --cpp_ext. Falling back to Python flatten and unflatten.") flatten_impl = torch._utils._flatten_dense_tensors unflatten_impl = torch._utils._unflatten_dense_tensors imported_flatten_impl = True def flatten(bucket): if not imported_flatten_impl: import_flatten_impl() return flatten_impl(bucket) def unflatten(coalesced, bucket): if not imported_flatten_impl: import_flatten_impl() return unflatten_impl(coalesced, bucket) # apply_dist_call requires that tensors in 'bucket' are all the same type. def apply_flat_dist_call(bucket, call, extra_args=None): coalesced = flatten(bucket) if extra_args is not None: call(coalesced, *extra_args) else: call(coalesced) if call is dist.all_reduce: coalesced /= dist.get_world_size() for buf, synced in zip(bucket, unflatten(coalesced, bucket)): buf.copy_(synced) def split_half_float_double(tensors): dtypes = ["torch.cuda.HalfTensor", "torch.cuda.FloatTensor", "torch.cuda.DoubleTensor"] buckets = [] for i, dtype in enumerate(dtypes): bucket = [t for t in tensors if t.type() == dtype] if bucket: buckets.append(bucket) return buckets def split_by_type(tensors): buckets = OrderedDict() for tensor in tensors: tp = tensor.type() if tp not in buckets: buckets[tp] = [] buckets[tp].append(tensor) return buckets # flat_dist_call organizes 'tensors' by type. def flat_dist_call(tensors, call, extra_args=None): buckets = split_by_type(tensors) for tp in buckets: bucket = buckets[tp] apply_flat_dist_call(bucket, call, extra_args) def extract_tensors(maybe_tensor, tensor_list): if torch.is_tensor(maybe_tensor): tensor_list.append(maybe_tensor) else: try: for item in maybe_tensor: extract_tensors(item, tensor_list) except TypeError: return class Reducer(object): """ :class:`apex.parallel.Reducer` is a simple class that helps allreduce a module's parameters across processes. :class:`Reducer` is intended to give the user additional control: Unlike :class:`DistributedDataParallel`, :class:`Reducer` will not automatically allreduce parameters during ``backward()``. Instead, :class:`Reducer` waits for the user to call ``.reduce()`` manually. This enables, for example, delaying the allreduce to be carried out every several iterations instead of every single iteration. Like :class:`DistributedDataParallel`, :class:`Reducer` averages any tensors it allreduces over the number of participating processes. :class:`Reducer` is designed to work with the upstream launch utility script ``torch.distributed.launch`` with ``--nproc_per_node <= number of gpus per node``. When used with this launcher, :class:`Reducer` assumes 1:1 mapping of processes to GPUs. It also assumes that your script calls ``torch.cuda.set_device(args.rank)`` before creating the model. Args: module_or_grads_list: Either a network definition (module) being run in multi-gpu/distributed mode, or an iterable of gradients to be reduced. If a module is passed in, the Reducer constructor will sync the parameters across processes (broadcasting from rank 0) to make sure they're all initialized with the same values. If a list of gradients (that came from some module) is passed in, the user is responsible for manually syncing that module's parameters at the beginning of training. """ def __init__(self, module_or_grads_list): if isinstance(module_or_grads_list, Module): self.module = module_or_grads_list flat_dist_call([param.data for param in self.module.parameters()], dist.broadcast, (0,) ) else: self.module = None self.grads = [] extract_tensors(module_or_grads_list, self.grads) def reduce(self): if self.module: grads = [param.grad.data for param in self.module.parameters() if param.grad is not None] flat_dist_call(grads, dist.all_reduce) else: flat_dist_call(self.grads, dist.all_reduce) class DistributedDataParallel(Module): """ :class:`apex.parallel.DistributedDataParallel` is a module wrapper that enables easy multiprocess distributed data parallel training, similar to ``torch.nn.parallel.DistributedDataParallel``. Parameters are broadcast across participating processes on initialization, and gradients are allreduced and averaged over processes during ``backward()``. :class:`DistributedDataParallel` is optimized for use with NCCL. It achieves high performance by overlapping communication with computation during ``backward()`` and bucketing smaller gradient transfers to reduce the total number of transfers required. :class:`DistributedDataParallel` is designed to work with the upstream launch utility script ``torch.distributed.launch`` with ``--nproc_per_node <= number of gpus per node``. When used with this launcher, :class:`DistributedDataParallel` assumes 1:1 mapping of processes to GPUs. It also assumes that your script calls ``torch.cuda.set_device(args.rank)`` before creating the model. https://github.com/NVIDIA/apex/tree/master/examples/simple/distributed shows detailed usage. https://github.com/NVIDIA/apex/tree/master/examples/imagenet shows another example that combines :class:`DistributedDataParallel` with mixed precision training. Args: module: Network definition to be run in multi-gpu/distributed mode. message_size (int, default=1e7): Minimum number of elements in a communication bucket. delay_allreduce (bool, default=False): Delay all communication to the end of the backward pass. This disables overlapping communication with computation. allreduce_trigger_params (list, optional, default=None): If supplied, should contain a list of parameters drawn from the model. Allreduces will be kicked off whenever one of these parameters receives its gradient (as opposed to when a bucket of size message_size is full). At the end of backward(), a cleanup allreduce to catch any remaining gradients will also be performed automatically. If allreduce_trigger_params is supplied, the message_size argument will be ignored. allreduce_always_fp32 (bool, default=False): Convert any FP16 gradients to FP32 before allreducing. This can improve stability for widely scaled-out runs. gradient_average (bool, default=True): Option to toggle whether or not DDP averages the allreduced gradients over processes. For proper scaling, the default value of True is recommended. gradient_predivide_factor (float, default=1.0): Allows perfoming the average of gradients over processes partially before and partially after the allreduce. Before allreduce: ``grads.mul_(1.0/gradient_predivide_factor)``. After allreduce: ``grads.mul_(gradient_predivide_factor/world size)``. This can reduce the stress on the dynamic range of FP16 allreduces for widely scaled-out runs. .. warning:: If ``gradient_average=False``, the pre-allreduce division (``grads.mul_(1.0/gradient_predivide_factor)``) will still be applied, but the post-allreduce gradient averaging (``grads.mul_(gradient_predivide_factor/world size)``) will be omitted. """ def __init__(self, module, message_size=10000000, delay_allreduce=False, shared_param=None, allreduce_trigger_params=None, retain_allreduce_buffers=False, allreduce_always_fp32=False, num_allreduce_streams=1, allreduce_communicators=None, gradient_average=True, gradient_predivide_factor=1.0, gradient_average_split_factor=None, prof=False): super(DistributedDataParallel, self).__init__() # Backward/forward compatibility around # https://github.com/pytorch/pytorch/commit/540ef9b1fc5506369a48491af8a285a686689b36 and # https://github.com/pytorch/pytorch/commit/044d00516ccd6572c0d6ab6d54587155b02a3b86 if hasattr(dist, "get_backend"): self._backend = dist.get_backend() if hasattr(dist, "DistBackend"): self.backend_enum_holder = dist.DistBackend else: self.backend_enum_holder = dist.Backend else: self._backend = dist._backend self.backend_enum_holder = dist.dist_backend self.warn_on_half = True if self._backend == self.backend_enum_holder.GLOO else False self.prof = prof self.allreduce_different_streams = (num_allreduce_streams > 1) self.num_allreduce_streams = num_allreduce_streams self.allreduce_communicators = allreduce_communicators if self.allreduce_communicators: assert len(allreduce_communicators[0]) == num_allreduce_streams assert len(allreduce_communicators[0]) == len(allreduce_communicators[1]) assert self.allreduce_different_streams if self.allreduce_different_streams and delay_allreduce: raise ValueError("self.allreduce_different_streams may only be used if delay_allreduce=False.") if shared_param is not None: raise ValueError("shared_param is no longer supported as an option. It was misleadingly named from the start. It turns out overlapping communication with computation should work fine with shared parameters. If you still wish to delay communication to the end of the backward pass, use delay_allreduce=True|False instead.") self.world_size = float(dist.get_world_size()) self.retain_allreduce_buffers = retain_allreduce_buffers self.allreduce_always_fp32 = allreduce_always_fp32 self.gradient_average = gradient_average self.gradient_predivide_factor = gradient_predivide_factor self.custom_allreduce_triggers = False if allreduce_trigger_params is not None: if delay_allreduce: raise ValueError("Setting allreduce_trigger_params is only valid if delay_allreduce=False.") self.custom_allreduce_triggers = True self.allreduce_trigger_params = set([id(param) for param in allreduce_trigger_params]) self.delay_allreduce = delay_allreduce self.message_size = message_size self.main_stream = torch.cuda.current_stream() self.bucket_streams = [] self.bucket_events = [] self.module = module self._disable_allreduce = False if self._backend == self.backend_enum_holder.NCCL: for param in self.module.parameters(): assert param.is_cuda, "NCCL backend only supports model parameters to be on GPU." self.active_params = [] self.param_type_to_tmp_i = {"torch.cuda.HalfTensor" : 0, "torch.cuda.FloatTensor" : 1, "torch.cuda.DoubleTensor" : 2} if multi_tensor_applier.available: # TODO: I really need to centralize the C++ backed imports import amp_C self.multi_tensor_scale = amp_C.multi_tensor_scale self._overflow_buf = torch.cuda.IntTensor([0]) self.create_hooks() flat_dist_call([param.data for param in self.module.parameters()], dist.broadcast, (0,) ) def __setstate__(self, state): super(DistributedDataParallel, self).__setstate__(state) if self.allreduce_different_streams and delay_allreduce: raise ValueError("self.allreduce_different_streams may only be used if delay_allreduce=False.") if self.delay_allreduce: self.needs_refresh = True self.bucket_streams = [] self.bucket_events = [] def __getstate__(self): attrs = copy.copy(self.__dict__) if self._backend != self.backend_enum_holder.NCCL: del attrs['self.bucket_streams'] del attrs['self.bucket_events'] return attrs def enable_allreduce(self): self._disable_allreduce = False def disable_allreduce(self): self._disable_allreduce = True # Broadcast rank 0's bucket structure across all processes, and have all processes # regenerate their bucket structures to match. def sync_bucket_structure(self): # Append leftover buckets for tmp_bucket in self.tmp_buckets: if len(tmp_bucket) > 0: self.active_i_buckets.append(tmp_bucket) self.num_buckets = len(self.active_i_buckets) self.bucket_sizes = [len(bucket) for bucket in self.active_i_buckets] info_tensor = torch.cuda.IntTensor([self.num_buckets] + self.bucket_sizes + list(chain(*self.active_i_buckets))) dist.broadcast(info_tensor, 0) info = [int(entry) for entry in info_tensor] self.num_buckets = info[0] self.bucket_sizes = info[1:self.num_buckets + 1] self.buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] # Technically, active_i_buckets' work is done. But the information is still useful to # keep around. Therefore, refresh active_i_buckets based on rank 0 as well. self.active_i_buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] flattened_buckets = info[self.num_buckets + 1:] flat_i = 0 for bucket_idx in range(self.num_buckets): for bucket_loc in range(self.bucket_sizes[bucket_idx]): param_i = flattened_buckets[flat_i] self.active_i_buckets[bucket_idx][bucket_loc] = param_i self.param_id_to_bucket[id(self.active_params[param_i])] = (bucket_idx, bucket_loc) flat_i += 1 def create_hooks(self): # Fallback hook that's only called at the end of backward. # Used if you deliberately want to delay allreduces to the end, or to refresh the # bucket structure that will be used to overlap communication with computation in later # iterations. def allreduce_params(): # Bucket record refresh if not self.delay_allreduce: if self.needs_refresh: self.sync_bucket_structure() self.needs_refresh = False self.allreduce_fallback() def overlapping_backward_epilogue(): for stream, event in zip(self.bucket_streams, self.bucket_events): stream.record_event(event) torch.cuda.current_stream().wait_event(event) # Sanity checks that all the buckets were kicked off if self.next_bucket != self.num_buckets: raise RuntimeError("In epilogue, next_bucket ({}) != num_buckets ({}). ".format( self.next_bucket, self.num_buckets), "This probably indicates some buckets were not allreduced.") for actual, expected in zip(self.buckets_ready_size, self.bucket_sizes): if actual != expected: raise RuntimeError("Some param buckets were not allreduced.") self.grad_accs = [] for param in self.module.parameters(): if param.requires_grad: def wrapper(param): param_tmp = param.expand_as(param) grad_acc = param_tmp.grad_fn.next_functions[0][0] def allreduce_hook(*unused): if self.prof: torch.cuda.nvtx.range_push("allreduce_hook") if not self._disable_allreduce: if self.delay_allreduce or self.needs_refresh: # TODO: How do we want to handle multiple backward passes between # each forward, e.g., backward passes with retain_graph=True? # needs_refresh and callback_queued are both vulnerable states. if not self.delay_allreduce and self.needs_refresh: # Use the backward pass to build the bucket structure on the fly. active_i = self.param_id_to_active_i[id(param)] # Float, half, and double tensors are grouped into buckets separately. current_type = self.param_type_to_tmp_i[param.type()] self.tmp_buckets[current_type].append(active_i) ship_tmp_bucket = False if self.custom_allreduce_triggers: if id(param) in self.allreduce_trigger_params: ship_tmp_bucket = True else: self.tmp_numels[current_type] += param.numel() if self.tmp_numels[current_type] >= self.message_size: ship_tmp_bucket = True # To consider: If custom_allreduce_triggers are in use, ship all # tmp_buckets, not just tmp_buckets[current_type]. if ship_tmp_bucket: self.active_i_buckets.append(self.tmp_buckets[current_type]) self.tmp_buckets[current_type] = [] self.tmp_numels[current_type] = 0 if not self.callback_queued: Variable._execution_engine.queue_callback(allreduce_params) self.callback_queued = True else: if not self.callback_queued: Variable._execution_engine.queue_callback(overlapping_backward_epilogue) self.callback_queued = True self.comm_ready_buckets(param) if self.prof: torch.cuda.nvtx.range_pop() grad_acc.register_hook(allreduce_hook) self.grad_accs.append(grad_acc) wrapper(param) def _stream_this_bucket(self, bucket_idx): if self.allreduce_different_streams: return self.bucket_streams[bucket_idx%self.num_allreduce_streams] else: return self.bucket_streams[0] def _event_this_bucket(self, bucket_idx): if self.allreduce_different_streams: return self.bucket_events[bucket_idx%self.num_allreduce_streams] else: return self.bucket_events[0] def allreduce_bucket(self, bucket, bucket_idx, force_default_stream): tensor = flatten(bucket) if force_default_stream: bucket_stream = self.main_stream else: bucket_stream = self._stream_this_bucket(bucket_idx) bucket_event = self._event_this_bucket(bucket_idx) torch.cuda.current_stream().record_event(bucket_event) bucket_stream.wait_event(bucket_event) with torch.cuda.stream(bucket_stream): # self.main_stream.wait_stream(torch.cuda.current_stream()) # torch.cuda.synchronize() tensor_to_allreduce = tensor if self.allreduce_always_fp32: tensor_to_allreduce = tensor.float() if self.gradient_predivide_factor != 1.0: tensor_to_allreduce.mul_(1./self.gradient_predivide_factor) if self.allreduce_different_streams and not force_default_stream: dist.all_reduce(tensor_to_allreduce, group=self.bucket_pgs[bucket_idx%self.num_allreduce_streams]) else: dist.all_reduce(tensor_to_allreduce) if self.gradient_average: tensor_to_allreduce.mul_(self.gradient_predivide_factor/self.world_size) if self.allreduce_always_fp32 and tensor is not tensor_to_allreduce: tensor.copy_(tensor_to_allreduce) if not self.retain_allreduce_buffers: if multi_tensor_applier.available: multi_tensor_applier( self.multi_tensor_scale, self._overflow_buf, [unflatten(tensor, bucket), bucket], 1.0) else: for buf, synced in zip(bucket, unflatten(tensor, bucket)): buf.copy_(synced) # I think we actually do need this here. After allreduce_bucket returns, tensor will # eventually go out of scope and die, at which point it could otherwise be freed for # further reuse by the main stream while the allreduce/div/unflatten are underway in bucket_stream. tensor.record_stream(bucket_stream) return tensor def allreduce_maybe_retain(self, bucket, bucket_idx, force_default_stream=False): allreduced = self.allreduce_bucket(bucket, bucket_idx, force_default_stream) if self.retain_allreduce_buffers: if self.allreduce_buffers[bucket_idx] is not None: raise RuntimeError("The backward pass is attempting to replace an already-filled " "allreduce buffer. This is almost certainly an error.") self.allreduce_buffers[bucket_idx] = allreduced for view, grad in zip(unflatten(allreduced, bucket), bucket): grad.data = view # for buf, synced in zip(bucket, unflatten(allreduced, bucket)): # buf.copy_(synced) def allreduce_fallback(self): for stream, event in zip(self.bucket_streams, self.bucket_events): stream.record_event(event) torch.cuda.current_stream().wait_event(event) if self.retain_allreduce_buffers: grads = [param.grad for param in self.module.parameters() if param.grad is not None] else: grads = [param.grad.data for param in self.module.parameters() if param.grad is not None] split_buckets = split_half_float_double(grads) # If retain_allreduce_buffers is True and delay_allreduce is False, # this will only be done during the first backward pass, ignored by the # training script, and overwritten in the next forward pass. So it's harmless. if self.retain_allreduce_buffers: self.allreduce_buffers = [None for _ in range(len(split_buckets))] for i, bucket in enumerate(split_buckets): allreduced = self.allreduce_maybe_retain(bucket, i, force_default_stream=True) def comm_ready_buckets(self, param): # Need to do this in every hook for compatibility with Ruberry's streaming backward PR. # self.reduction_stream.wait_stream(torch.cuda.current_stream()) if self.prof: torch.cuda.nvtx.range_push("comm_ready_buckets") bucket_idx, bucket_loc = self.param_id_to_bucket[id(param)] if self.buckets[bucket_idx][bucket_loc] is not None: raise RuntimeError("The backward pass is attempting to replace an already-filled " "bucket slot. This is almost certainly an error.") if self.retain_allreduce_buffers: self.buckets[bucket_idx][bucket_loc] = param.grad else: self.buckets[bucket_idx][bucket_loc] = param.grad.data self.buckets_ready_size[bucket_idx] += 1 if self.buckets_ready_size[bucket_idx] == self.bucket_sizes[bucket_idx]: if bucket_idx == self.next_bucket: self.allreduce_maybe_retain(self.buckets[bucket_idx], bucket_idx) self.next_bucket += 1 # Reversing upstream's logic here, because we constructed our buckets based on # the order things were received during backward. if len(self.ready_buckets_not_reduced) > 0: sorted_todo = sorted(self.ready_buckets_not_reduced) for i in sorted_todo: # Nothing can be reduced now if i > self.next_bucket: break elif i == self.next_bucket: self.allreduce_maybe_retain(self.buckets[i], i) self.ready_buckets_not_reduced.remove(i) self.next_bucket += 1 else: raise ValueError("i should always be >= next_bucket") else: self.ready_buckets_not_reduced.add(bucket_idx) if self.prof: torch.cuda.nvtx.range_pop() def forward(self, *inputs, **kwargs): result = self.module(*inputs, **kwargs) if self.prof: torch.cuda.nvtx.range_push("forward pass DDP logic") if not self._disable_allreduce: if not self.delay_allreduce: param_list = [param for param in self.module.parameters() if param.requires_grad] # Conditions under which to refresh self.record # Forward has the authority to set needs_refresh to True, but only allreduce_params # in backward has the authority to set needs_refresh to False. # Parentheses are not necessary for correct order of operations, but make the intent clearer. if ((not self.active_params) or (len(param_list) != len(self.active_params)) or any([param1 is not param2 for param1, param2 in zip(param_list, self.active_params)])): self.needs_refresh = True if self.needs_refresh: self.active_i_buckets = [] self.buckets = [] self.tmp_buckets = [[], [], []] # [running half, float, double buckets] self.tmp_numels = [0, 0, 0] self.bucket_sizes = [] self.param_id_to_active_i = {id(param) : i for i, param in enumerate(param_list)} self.param_id_to_bucket = {} self.bucket_pgs = [] self.bucket_streams = [] self.bucket_events = [] else: # self.buckets = [[None for _ in range(self.bucket_sizes[i])] # for i in range(self.num_buckets)] if not self.buckets: self.buckets = [[None for _ in range(self.bucket_sizes[i])] for i in range(self.num_buckets)] else: assert len(self.buckets) == self.num_buckets, "len(buckets) = {}, expected {}".format( len(self.buckets), self.num_buckets) for b, bucket in enumerate(self.buckets): assert len(bucket) == self.bucket_sizes[b], "len(buckets[{}]) = {}, expected {})".format( b, len(buckets[b]), self.bucket_sizes[b]) for i in range(len(bucket)): bucket[i] = None if self.allreduce_communicators: self.bucket_pgs = self.allreduce_communicators[0] self.bucket_streams = self.allreduce_communicators[1] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False) for _ in range(self.num_allreduce_streams)] else: if self.allreduce_different_streams: if not self.bucket_pgs: self.bucket_pgs = [dist.new_group() for _ in range(self.num_allreduce_streams)] for i, bg in enumerate(self.bucket_pgs): print("rank {} created group {} with backend {}".format( dist.get_rank(), i, dist.get_backend(bg))) if self.allreduce_different_streams: if not self.bucket_streams: self.bucket_streams = [torch.cuda.Stream() for _ in range(self.num_allreduce_streams)] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False) for _ in range(self.num_allreduce_streams)] else: if not self.bucket_streams: self.bucket_streams = [torch.cuda.Stream()] self.bucket_events = [torch.cuda.Event(enable_timing=False, blocking=False)] self.buckets_ready_size = [0 for i in range(self.num_buckets)] if(self.retain_allreduce_buffers): self.allreduce_buffers = [None for _ in range(self.num_buckets)] self.next_bucket = 0 self.ready_buckets_not_reduced = set() self.active_params = param_list self.callback_queued = False if self.prof: torch.cuda.nvtx.range_pop() return result ================================================ FILE: KoSimCSE/apex/parallel/multiproc.py ================================================ import torch import sys import subprocess def docstring_hack(): """ Multiproc file which will launch a set of processes locally for multi-gpu usage: python -m apex.parallel.multiproc main.py ... """ pass argslist = list(sys.argv)[1:] world_size = torch.cuda.device_count() if '--world-size' in argslist: world_size = int(argslist[argslist.index('--world-size')+1]) else: argslist.append('--world-size') argslist.append(str(world_size)) workers = [] for i in range(world_size): if '--rank' in argslist: argslist[argslist.index('--rank')+1] = str(i) else: argslist.append('--rank') argslist.append(str(i)) stdout = None if i == 0 else open("GPU_"+str(i)+".log", "w") print(argslist) p = subprocess.Popen([str(sys.executable)]+argslist, stdout=stdout) workers.append(p) for p in workers: p.wait() ================================================ FILE: KoSimCSE/apex/parallel/optimized_sync_batchnorm.py ================================================ import torch from torch.nn.modules.batchnorm import _BatchNorm from torch.nn import functional as F import syncbn from .optimized_sync_batchnorm_kernel import SyncBatchnormFunction class SyncBatchNorm(_BatchNorm): """ synchronized batch normalization module extented from `torch.nn.BatchNormNd` with the added stats reduction across multiple processes. :class:`apex.parallel.SyncBatchNorm` is designed to work with `DistributedDataParallel`. When running in training mode, the layer reduces stats across all processes to increase the effective batchsize for normalization layer. This is useful in applications where batch size is small on a given process that would diminish converged accuracy of the model. The model uses collective communication package from `torch.distributed`. When running in evaluation mode, the layer falls back to `torch.nn.functional.batch_norm` Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` process_group: pass in a process group within which the stats of the mini-batch is being synchronized. ``None`` for using default process group channel_last: a boolean value that when set to ``True``, this module take the last dimension of the input tensor to be the channel dimension. Default: False Examples:: >>> # channel first tensor >>> sbn = apex.parallel.SyncBatchNorm(100).cuda() >>> inp = torch.randn(10, 100, 14, 14).cuda() >>> out = sbn(inp) >>> inp = torch.randn(3, 100, 20).cuda() >>> out = sbn(inp) >>> # channel last tensor >>> sbn = apex.parallel.SyncBatchNorm(100, channel_last=True).cuda() >>> inp = torch.randn(10, 14, 14, 100).cuda() """ def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, process_group=None, channel_last=False, fuse_relu=False): super(SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats) self.process_group = process_group self.channel_last = channel_last self.fuse_relu = fuse_relu def _specify_process_group(self, process_group): self.process_group = process_group def _specify_channel_last(self, channel_last): self.channel_last = channel_last def forward(self, input, z = None): # if input.dim() == 2, we switch to channel_last for efficient memory accessing channel_last = self.channel_last if input.dim() != 2 else True if not self.training and self.track_running_stats and not channel_last and not self.fuse_relu and z == None: # fall back to pytorch implementation for inference return F.batch_norm(input, self.running_mean, self.running_var, self.weight, self.bias, False, 0.0, self.eps) else: exponential_average_factor = 0.0 if self.training and self.track_running_stats: self.num_batches_tracked += 1 if self.momentum is None: exponential_average_factor = 1.0 / float(self.num_batches_tracked) else: exponential_average_factor = self.momentum return SyncBatchnormFunction.apply(input, z, self.weight, self.bias, self.running_mean, self.running_var, self.eps, self.training or not self.track_running_stats, exponential_average_factor, self.process_group, channel_last, self.fuse_relu) ================================================ FILE: KoSimCSE/apex/parallel/optimized_sync_batchnorm_kernel.py ================================================ import torch from torch.autograd.function import Function import syncbn from apex.parallel import ReduceOp class SyncBatchnormFunction(Function): @staticmethod def forward(ctx, input, z, weight, bias, running_mean, running_variance, eps, track_running_stats = True, momentum = 1.0, process_group = None, channel_last = False, fuse_relu = False): input = input.contiguous() world_size = 0 mean = None var_biased = None inv_std = None var = None out = None count = None if track_running_stats: if channel_last: count = int(input.numel()/input.size(-1)) mean, var_biased = syncbn.welford_mean_var_c_last(input) num_channels = input.size(-1) else: count = int(input.numel()/input.size(1)) mean, var_biased = syncbn.welford_mean_var(input) num_channels = input.size(1) if torch.distributed.is_initialized(): if not process_group: process_group = torch.distributed.group.WORLD device = mean.device world_size = torch.distributed.get_world_size(process_group) count_t = torch.empty(1, dtype=mean.dtype, device=mean.device).fill_(count) combined = torch.cat([mean.view(-1), var_biased.view(-1), count_t], dim=0) combined_list = [torch.empty_like(combined) for k in range(world_size)] torch.distributed.all_gather(combined_list, combined, process_group) combined = torch.stack(combined_list, dim=0) mean_all, invstd_all, count_all = torch.split(combined, num_channels, dim=1) count_all = count_all.view(-1) mean, var, inv_std = syncbn.welford_parallel(mean_all, invstd_all, count_all.to(torch.int32), eps) else: device = mean.device count_all = torch.cuda.IntTensor([count], device=device) inv_std = 1.0 / torch.sqrt(var_biased + eps) var = var_biased * (count) / (count-1) if count == 1 and world_size < 2: raise ValueError('Expected more than 1 value per channel when training, got input size{}'.format(input.size())) r_m_inc = mean if running_mean.dtype != torch.float16 else mean.half() r_v_inc = var if running_variance.dtype != torch.float16 else var.half() running_mean.data = running_mean.data * (1-momentum) + momentum*r_m_inc running_variance.data = running_variance.data * (1-momentum) + momentum*r_v_inc else: mean = running_mean.data inv_std = 1.0 / torch.sqrt(running_variance.data + eps) ctx.save_for_backward(input, weight, mean, inv_std, z, bias, count_all.to(torch.int32)) ctx.process_group = process_group ctx.channel_last = channel_last ctx.world_size = world_size ctx.fuse_relu = fuse_relu if channel_last: out = syncbn.batchnorm_forward_c_last(input, z, mean, inv_std, weight, bias, fuse_relu) else: out = syncbn.batchnorm_forward(input, mean, inv_std, weight, bias) return out @staticmethod def backward(ctx, grad_output): grad_output = grad_output.contiguous() # mini batch mean & var are calculated by forward path. # mu = 1./N*np.sum(h, axis = 0) # var = 1./N*np.sum((h-mu)**2, axis = 0) saved_input, weight, mean, inv_std, z, bias, count = ctx.saved_tensors process_group = ctx.process_group channel_last = ctx.channel_last world_size = ctx.world_size fuse_relu = ctx.fuse_relu grad_input = grad_z = grad_weight = grad_bias = None if fuse_relu: grad_output = syncbn.relu_bw_c_last(grad_output, saved_input, z, mean, inv_std, weight, bias) if isinstance(z, torch.Tensor) and ctx.needs_input_grad[1]: grad_z = grad_output.clone() # TODO: update kernel to not pre_divide by item_num if channel_last: sum_dy, sum_dy_xmu, grad_weight, grad_bias = syncbn.reduce_bn_c_last(grad_output, saved_input, mean, inv_std, weight) else: sum_dy, sum_dy_xmu, grad_weight, grad_bias = syncbn.reduce_bn(grad_output, saved_input, mean, inv_std, weight) # calculate grad_input if ctx.needs_input_grad[0]: if torch.distributed.is_initialized(): num_channels = sum_dy.shape[0] combined = torch.cat([sum_dy, sum_dy_xmu], dim=0) torch.distributed.all_reduce( combined, torch.distributed.ReduceOp.SUM, process_group, async_op=False) sum_dy, sum_dy_xmu = torch.split(combined, num_channels) if channel_last: grad_input = syncbn.batchnorm_backward_c_last(grad_output, saved_input, mean, inv_std, weight, sum_dy, sum_dy_xmu, count) else: grad_input = syncbn.batchnorm_backward(grad_output, saved_input, mean, inv_std, weight, sum_dy, sum_dy_xmu, count) if weight is None or not ctx.needs_input_grad[2]: grad_weight = None if weight is None or not ctx.needs_input_grad[3]: grad_bias = None return grad_input, grad_z, grad_weight, grad_bias, None, None, None, None, None, None, None, None ================================================ FILE: KoSimCSE/apex/parallel/sync_batchnorm.py ================================================ import torch from torch.nn.modules.batchnorm import _BatchNorm from torch.nn import functional as F from .sync_batchnorm_kernel import SyncBatchnormFunction from apex.parallel import ReduceOp class SyncBatchNorm(_BatchNorm): """ synchronized batch normalization module extented from ``torch.nn.BatchNormNd`` with the added stats reduction across multiple processes. :class:`apex.parallel.SyncBatchNorm` is designed to work with ``DistributedDataParallel``. When running in training mode, the layer reduces stats across all processes to increase the effective batchsize for normalization layer. This is useful in applications where batch size is small on a given process that would diminish converged accuracy of the model. The model uses collective communication package from ``torch.distributed``. When running in evaluation mode, the layer falls back to ``torch.nn.functional.batch_norm``. Args: num_features: :math:`C` from an expected input of size :math:`(N, C, L)` or :math:`L` from input of size :math:`(N, L)` eps: a value added to the denominator for numerical stability. Default: 1e-5 momentum: the value used for the running_mean and running_var computation. Can be set to ``None`` for cumulative moving average (i.e. simple average). Default: 0.1 affine: a boolean value that when set to ``True``, this module has learnable affine parameters. Default: ``True`` track_running_stats: a boolean value that when set to ``True``, this module tracks the running mean and variance, and when set to ``False``, this module does not track such statistics and always uses batch statistics in both training and eval modes. Default: ``True`` Example:: >>> sbn = apex.parallel.SyncBatchNorm(100).cuda() >>> inp = torch.randn(10, 100, 14, 14).cuda() >>> out = sbn(inp) >>> inp = torch.randn(3, 100, 20).cuda() >>> out = sbn(inp) """ warned = False def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True, process_group=None, channel_last=False): if channel_last == True: raise AttributeError("channel_last is not supported by primitive SyncBatchNorm implementation. Try install apex with `--cuda_ext` if channel_last is desired.") if not SyncBatchNorm.warned: if hasattr(self, "syncbn_import_error"): print("Warning: using Python fallback for SyncBatchNorm, possibly because apex was installed without --cuda_ext. The exception raised when attempting to import the cuda backend was: ", self.syncbn_import_error) else: print("Warning: using Python fallback for SyncBatchNorm") SyncBatchNorm.warned = True super(SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine, track_running_stats=track_running_stats) self.process_group = process_group def _specify_process_group(self, process_group): self.process_group = process_group def forward(self, input): torch.cuda.nvtx.range_push("sync_bn_fw_with_mean_var") mean = None var = None cast = None out = None # casting to handle mismatch input type to layer type if self.running_mean is not None: if self.running_mean.dtype != input.dtype: input = input.to(self.running_mean.dtype) cast = input.dtype elif self.weight is not None: if self.weight.dtype != input.dtype: input = input.to(self.weight.dtype) cast = input.dtype if not self.training and self.track_running_stats: # fall back to pytorch implementation for inference torch.cuda.nvtx.range_pop() out = F.batch_norm(input, self.running_mean, self.running_var, self.weight, self.bias, False, 0.0, self.eps) else: process_group = self.process_group world_size = 1 if not self.process_group: process_group = torch.distributed.group.WORLD self.num_batches_tracked += 1 with torch.no_grad(): channel_first_input = input.transpose(0, 1).contiguous() squashed_input_tensor_view = channel_first_input.view( channel_first_input.size(0), -1) # total number of data points for each variance entry. Used to calculate unbiased variance estimate m = None local_m = float(squashed_input_tensor_view.size()[1]) local_mean = torch.mean(squashed_input_tensor_view, 1) local_sqr_mean = torch.pow( squashed_input_tensor_view, 2).mean(1) if torch.distributed.is_initialized(): world_size = torch.distributed.get_world_size(process_group) torch.distributed.all_reduce( local_mean, ReduceOp.SUM, process_group) mean = local_mean / world_size torch.distributed.all_reduce( local_sqr_mean, ReduceOp.SUM, process_group) sqr_mean = local_sqr_mean / world_size m = local_m * world_size else: m = local_m mean = local_mean sqr_mean = local_sqr_mean # var(x) = E (( x - mean_x ) ** 2) # = 1 / N * sum ( x - mean_x ) ** 2 # = 1 / N * sum (x**2) - mean_x**2 var = sqr_mean - mean.pow(2) if self.running_mean is not None: self.running_mean = self.momentum * mean + \ (1 - self.momentum) * self.running_mean if self.running_var is not None: # as noted by the paper, we used unbiased variance estimate of the mini-batch # Var[x] = m / (m-1) * Eb (sample_variance) self.running_var = m / \ (m-1) * self.momentum * var + \ (1 - self.momentum) * self.running_var torch.cuda.nvtx.range_pop() out = SyncBatchnormFunction.apply(input, self.weight, self.bias, mean, var, self.eps, process_group, world_size) return out.to(cast) ================================================ FILE: KoSimCSE/apex/parallel/sync_batchnorm_kernel.py ================================================ import torch from torch.autograd.function import Function from apex.parallel import ReduceOp class SyncBatchnormFunction(Function): @staticmethod def forward(ctx, input, weight, bias, running_mean, running_variance, eps, process_group, world_size): torch.cuda.nvtx.range_push("sync_BN_fw") # transpose it to channel last to support broadcasting for input with different rank c_last_input = input.transpose(1, -1).contiguous().clone() ctx.save_for_backward(c_last_input, weight, bias, running_mean, running_variance) ctx.eps = eps ctx.process_group = process_group ctx.world_size = world_size c_last_input = (c_last_input - running_mean) / \ torch.sqrt(running_variance + eps) if weight is not None: c_last_input = c_last_input * weight if bias is not None: c_last_input = c_last_input + bias torch.cuda.nvtx.range_pop() return c_last_input.transpose(1, -1).contiguous().clone() @staticmethod def backward(ctx, grad_output): torch.cuda.nvtx.range_push("sync_BN_bw") # mini batch mean & var are calculated by forward path. # mu = 1./N*np.sum(h, axis = 0) # var = 1./N*np.sum((h-mu)**2, axis = 0) c_last_input, weight, bias, running_mean, running_variance = ctx.saved_tensors eps = ctx.eps process_group = ctx.process_group world_size = ctx.world_size grad_input = grad_weight = grad_bias = None num_features = running_mean.size()[0] # transpose it to channel last to support broadcasting for input with different rank torch.cuda.nvtx.range_push("carilli field") c_last_grad = grad_output.transpose(1, -1).contiguous() # squash non-channel dimension so we can easily calculate mean c_grad = c_last_grad.view(-1, num_features).contiguous() torch.cuda.nvtx.range_pop() # calculate grad_input if ctx.needs_input_grad[0]: # dh = gamma * (var + eps)**(-1. / 2.) * (dy - np.mean(dy, axis=0) # - (h - mu) * (var + eps)**(-1.0) * np.mean(dy * (h - mu), axis=0)) mean_dy = c_grad.mean(0) mean_dy_xmu = (c_last_grad * (c_last_input - running_mean)).view(-1, num_features).mean(0) if torch.distributed.is_initialized(): torch.distributed.all_reduce( mean_dy, ReduceOp.SUM, process_group) mean_dy = mean_dy / world_size torch.distributed.all_reduce( mean_dy_xmu, ReduceOp.SUM, process_group) mean_dy_xmu = mean_dy_xmu / world_size c_last_grad_input = (c_last_grad - mean_dy - (c_last_input - running_mean) / ( running_variance + eps) * mean_dy_xmu) / torch.sqrt(running_variance + eps) if weight is not None: c_last_grad_input.mul_(weight) grad_input = c_last_grad_input.transpose(1, -1).contiguous() # calculate grad_weight grad_weight = None if weight is not None and ctx.needs_input_grad[1]: # dgamma = np.sum((h - mu) * (var + eps)**(-1. / 2.) * dy, axis=0) grad_weight = ((c_last_input - running_mean) / torch.sqrt( running_variance + eps) * c_last_grad).view(-1, num_features).sum(0) # calculate grad_bias grad_bias = None if bias is not None and ctx.needs_input_grad[2]: # dbeta = np.sum(dy, axis=0) grad_bias = c_grad.sum(0) torch.cuda.nvtx.range_pop() return grad_input, grad_weight, grad_bias, None, None, None, None, None ================================================ FILE: KoSimCSE/apex/pyprof/FAQs.md ================================================ 1. How do I intercept the Adam optimizer in APEX ? ```python from apex import pyprof import fused_adam_cuda pyprof.nvtx.wrap(fused_adam_cuda, 'adam') ``` 2. If you are using JIT and/or AMP, the correct initialization sequence is 1. Let any JIT to finish. 2. Initlialize pyprof `pyprof.nvtx.init()`. 3. Initialize AMP. 3. How do I profile with `torch.distributed.launch` ? ```python nvprof -f -o net%p.sql \ --profile-from-start off \ --profile-child-processes \ python -m torch.distributed.launch net.py ``` ================================================ FILE: KoSimCSE/apex/pyprof/README.md ================================================ ## PyProf - PyTorch Profiling tool ### What does this tool do? Analyzing the performance of deep neural networks is hard. Getting kernels out of [NvProf]([https://developer.nvidia.com/nvidia-visual-profiler](https://developer.nvidia.com/nvidia-visual-profiler)) or [NSight Compute]([https://developer.nvidia.com/nsight-compute](https://developer.nvidia.com/nsight-compute)) provides some generic kernel name and its execution time, but not detailed information regarding the following: - Which layer launched it: e.g. the association of `ComputeOffsetsKernel` with a concrete PyTorch layer or API is not obvious. - What the tensor dimensions and precision were: without knowing the tensor dimensions and precision, it's impossible to reason about whether the actual (silicon) kernel time is close to maximum performance of such a kernel on the GPU. Knowing the tensor dimensions and precision, we can figure out the FLOPs and bandwidth required by a layer, and then determine how close to maximum performance the kernel is for that operation. - Forward-backward correlation: currently it's very hard to determine what the forward pass step was that resulted in the particular weight and data gradients (wgrad, dgrad), which makes it difficult to determine the tensor dimensions required by these backprop steps to assess their performance. - Did the kernel use [Tensor Cores]([https://www.youtube.com/watch?v=yyR0ZoCeBO8](https://www.youtube.com/watch?v=yyR0ZoCeBO8))? - Which line in the user's code resulted in launching this particular kernel (program trace)? PyProf addresses all of the issues above by: 1. Instrumenting PyTorch operations to capture the tensor dimensions and precision using [NVTX](https://devblogs.nvidia.com/cuda-pro-tip-generate-custom-application-profile-timelines-nvtx). This information is recorded at profile capture time, e.g. using [NvProf](https://developer.nvidia.com/nvidia-visual-profiler). 2. Querying the record produced by the profiler to correlate the kernel name and duration with PyTorch API/layer name, tensor dimensions, tensor precision, as well as calculating FLOPs and bandwidth for common operations. In addition, extra information from the profile is added for use by CUDA professionals, such as CUDA launch parameters (block/grid dimensions). Regarding FLOP and bandwidth implementations, these are usually quite straightforward. For example, for matrices AMxK and BKxN, the FLOP count for a matrix multiplication is 2 * M * N * K, and bandwidth is M * K + N * K + M * N. Note that these numbers are based on the algorithm, not the actual performance of the specific kernel. For more details, see NVIDIA's [Deep Learning Performance Guide](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html). Armed with such information, the user can determine various issues to help them tune the network. For instance, according to the [Tensor Core Performance Guide]([https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html)), the M, N and K dimensions that result in Tensor Core usage need to be divisible by 8. In fact, PyProf comes with a flag that lets the user obtain information regarding whether Tensor Cores were used by the kernel. Other useful information might include knowing that a particular kernel did not exploit much thread parallelism, as determined by the grid/block dimensions. Since many PyTorch kernels are open-source (or even custom written by the user, as in [CUDA Extensions]([https://pytorch.org/tutorials/advanced/cpp_extension.html](https://pytorch.org/tutorials/advanced/cpp_extension.html))), this provides the user with information that helps root cause performance issues and prioritize optimization work. ### How to get started? 1. Add the following lines to your PyTorch network: ```python import torch.cuda.profiler as profiler from apex import pyprof pyprof.nvtx.init() ``` Run the training/inference loop with the [PyTorch's NVTX context manager](https://pytorch.org/docs/stable/_modules/torch/autograd/profiler.html#emit_nvtx) `with torch.autograd.profiler.emit_nvtx()`. Optionally, you can use `profiler.start()` and `profiler.stop()` to pick an iteration (say after warm-up) for which you would like to capture data. Here's an example: ```python iters = 500 iter_to_capture = 100 # Define network, loss function, optimizer etc. # PyTorch NVTX context manager with torch.autograd.profiler.emit_nvtx(): for iter in range(iters): if iter == iter_to_capture: profiler.start() output = net(images) loss = criterion(output, labels) loss.backward() optimizer.step() if iter == iter_to_capture: profiler.stop() ``` 2. Run NVprof to generate a SQL (NVVP) file. This file can be opened with NVVP, as usual. ```sh # If you used profiler.start() and profiler.stop() in net.py nvprof -f -o net.sql --profile-from-start off -- python net.py # Profile everything nvprof -f -o net.sql -- python net.py ``` **Note:** if you're experiencing issues with hardware counters and you get a message such as `**_ERR_NVGPUCTRPERM The user running does not have permission to access NVIDIA GPU Performance Counters on the target device_**`, please follow the steps described in [Hardware Counters](#hardware-counters). 3. Run parser on the SQL file. The output is an ASCII file. Each line is a python dictionary which contains information about the kernel name, duration, parameters etc. This file can be used as input to other custom scripts as well. ```sh python -m apex.pyprof.parse net.sql > net.dict ``` 4. Run the profiler. The input is the python dictionary created above. The tool can produce a CSV output, a columnated output (similar to `column -t` for terminal readability) and a space separated output (for post processing by AWK for instance). The tool produces 20 columns of information for every GPU kernel but you can select a subset of columns using the `-c` flag. Note that a few columns might have the value "na" implying either its a work in progress or the tool was unable to extract that information. Assuming the directory is `prof`, here are a few examples of how to use `prof.py`. ```sh # Print usage and help. Lists all available output columns. python -m apex.pyprof.prof -h # Columnated output of width 150 with some default columns. python -m apex.pyprof.prof -w 150 net.dict # CSV output. python -m apex.pyprof.prof --csv net.dict # Space seperated output. python -m apex.pyprof.prof net.dict # Columnated output of width 130 with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof -w 130 -c idx,dir,kernel,params,sil net.dict # CSV output with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof --csv -c idx,dir,kernel,params,sil net.dict # Space separated output with columns index,direction,kernel name,parameters,silicon time. python -m apex.pyprof.prof -c idx,dir,kernel,params,sil net.dict # Input redirection. python -m apex.pyprof.prof < net.dict ``` 5. Profile-guided optimization If kernels that do matrix multiplication/GEMM or convolution use half precision (fp16) data but do not use Tensor Cores (the TC column in the profile analysis output doesn't show a "1"), one can follow some basic steps to increase the likelihood that a Tensor Core-compatible kernel will be chosen. For example, for GEMMs, M, N and K should be divisible by 8, and for convolutions, the number of input and output channels shuold be divisible by 8. For more information, see detailed Tensor Core guides such as: - Blog Post: [Tips for Optimizing GPU Performance Using Tensor Cores](https://devblogs.nvidia.com/optimizing-gpu-performance-tensor-cores/) - GTC Talk: [Tensor Core Deep Learning Performance Guide](https://developer.download.nvidia.com/video/gputechconf/gtc/2019/presentation/s9926-tensor-core-performance-the-ultimate-guide.pdf) For both Tensor Core and non-Tensor Core Deep Learning performance optimization tips, see NVIDIA's [Deep Learning Performance Guide](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html). ### TODOs 1. The support for conv transpose is currently missing. 2. PyProf currently works only with NvProf, but Nsight Compute support will be added in the future. ### Example 1. Run `nvprof` on the LeNet model in `examples/lenet.py`. This will output a SQL file called `net.sql`. ```sh nvprof -f -o net.sql --profile-from-start off -- python examples/lenet.py ``` **Note**: DO NOT add --analysis-metrics since that will change which table nvprof writes the kernels to (`CUPTI_ACTIVITY_KIND_KERNEL` instead of the usual `CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL`). Support for running with metrics may be added in the future. If you don't care about a full correlation analysis and you'd just like to view the timeline with detailed NVTX annotations, you can do so, e.g. in the NVIDIA Visual Profiler (NVVP). For example, you can call `nvvp net.sql` to view the annotated timeline. 2. Run the `parse.py` script on `net.sql` to extract kernel and runtime information and save it as `net.dict`. ```sh python -m apex.pyprof.parse net.sql > net.dict ``` This will produce a text file, which can be parsed by any external tool, but it can also be directly read one line at a time by Python by calling `eval` on the line being read. **Note: you do not need to process this output manually.** Here the output is just shown as an example of modularity - you can process the raw data yourself, or let the next step enrich the information further and dump a CSV. The output of this step will look as follows. Note that the dictionary has a lot more keys than the ones shown in the example. ``` >>> with open('torchvision.resnet50.adam.64.dict') as f: ... for line in f: ... d = eval(line) ... print(d['kShortName'], d['op'], d['kDuration'], d['block'], d['grid'], d['device'], d['stream'], d['trace']) ... nchwToNhwc3To4Kernel ['conv2d'] 376324 (256, 1, 1) (1568, 1, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] generic4Channel_kernel ['conv2d'] 10720 (512, 1, 1) (19, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] first_layer_fwd_kernel ['conv2d'] 411204 (128, 1, 1) (2, 7, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] nhwcToNchwKernel ['conv2d'] 342371 (256, 1, 1) (392, 2, 64) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:195'] elementwise_kernel ['__iadd__'] 2816 (128, 1, 1) (1, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:196'] batch_norm_collect_statistics_kernel ['batch_norm', 'batch_norm'] 929513 (512, 1, 1) (64, 1, 1) 0 7 ['imagenet.py:137', 'imagenet.py:129', '/opt/conda/lib/python3.6/site-packages/torchvision/models/resnet.py:196'] ``` 3. Run the `prof.py` script on `net.dict` to summarize the results into a CSV file, or to display the pretty-printed results on the screen. This step processes the raw output from step 2 to generate a nice output, but it also adds a lot of extra useful information inferred from the previous step, such as: - FLOPs - bandwidth (bytes in and out of GPU DRAM) - tensor core usage ```sh python -m apex.pyprof.prof --csv net.dict > results.csv ``` You can choose which columns you'd like to display. Here's a list from calling `python -m apex.pyprof.prof -h`: ``` idx: Index seq: PyTorch Sequence Id altseq: PyTorch Alternate Sequence Id tid: Thread Id layer: User annotated NVTX string (can be nested) trace: Function Call Trace dir: Direction sub: Sub Sequence Id mod: Module op: Operation kernel: Kernel Name params: Parameters sil: Silicon Time (in ns) tc: Tensor Core Usage device: GPU Device Id stream: Stream Id grid: Grid Dimensions block: Block Dimensions flops: Floating point ops (FMA = 2 FLOPs) bytes: Number of bytes in and out of DRAM ``` Let's have a look at the pretty-printed output: ``` python -m apex.pyprof.prof -w 100 -c kernel,op,sil,tc,flops,bytes,device,stream,block,grid torchvision.resnet50.adam.64.dict Kernel Op Sil(ns) TC FLOPs Bytes Dev Str Block Grid elementwise_kernel relu 381028 - 51380224 205520896 0 7 512,1,1 100352,1,1 volta_fp16_s884cudn conv2d 160002 1 1644167168 51388416 0 7 256,1,1 784,1,1 elementwise_kernel relu 96545 - 12845056 51380224 0 7 512,1,1 25088,1,1 volta_fp16_s884cudn conv2d 346083 1 6576668672 128483328 0 7 256,1,1 784,2,1 ``` Not using the pretty-print width (`-w`) option and adding `--csv` results in a CSV output instead: ``` python -m apex.pyprof.prof --csv -c kernel,mod,op,dir,sil,tc,flops,bytes,device,stream,block,grid torchvision.resnet50.adam.64.dict "Kernel","Module","Op","Direction","Sil(ns)","TC","FLOPs","Bytes","Device","Stream","Block","Grid" "nchwToNhwc3To4Kernel","torch.nn.functional","conv2d","fprop","376324","-","0","0","0","7","256,1,1","1568,1,64" "generic4Channel_kernel","torch.nn.functional","conv2d","fprop","10720","-","0","0","0","7","512,1,1","19,1,1" "first_layer_fwd_kernel","torch.nn.functional","conv2d","fprop","411204","-","0","0","0","7","128,1,1","2,7,64" "nhwcToNchwKernel","torch.nn.functional","conv2d","fprop","342371","-","0","0","0","7","256,1,1","392,2,64" "elementwise_kernel","Tensor","__iadd__","fprop","2816","-","1.0","8","0","7","128,1,1","1,1,1" "batch_norm_collect_statistics_kernel","torch.nn.functional","batch_norm","fprop","929513","-","411041792","411041792","0","7","512,1,1","64,1,1" "batch_norm_transform_input_kernel","torch.nn.functional","batch_norm","fprop","377539","-","411041792","411041792","0","7","512,1,1","64,64,1" "elementwise_kernel","torch.nn.functional","relu","fprop","381028","-","51380224","205520896","0","7","512,1,1","100352,1,1" "MaxPoolForward","torch.nn.functional","max_pool2d","fprop","406531","-","0","0","0","7","256,1,1","50176,1,1" "cudnn::gemm::computeOffsetsKernel","torch.nn.functional","conv2d","fprop","2464","-","0","0","0","7","128,1,1","25,1,1" ``` ### Hardware Counters Profiling GPU workloads may require access to [hardware performance counters]([https://en.wikipedia.org/wiki/Hardware_performance_counter](https://en.wikipedia.org/wiki/Hardware_performance_counter)). Due to a [fix](https://nvidia.custhelp.com/app/answers/detail/a_id/4738) in recent NVIDIA drivers addressing [CVE‑2018‑6260](https://nvd.nist.gov/vuln/detail/CVE-2018-6260), the hardware counters are disabled by default, and require elevated privileges to be enabled again. If you're using a recent driver, you may see the following message when trying to run nvprof: ```**_ERR_NVGPUCTRPERM The user running does not have permission to access NVIDIA GPU Performance Counters on the target device._**``` For details, see [here](https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters). _Permanent solution_ Follow the steps [here]([https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters](https://developer.nvidia.com/nvidia-development-tools-solutions-ERR_NVGPUCTRPERM-permission-issue-performance-counters)). The current steps for Linux are: ``` sudo systemctl isolate multi-user sudo modprobe -r nvidia_uvm nvidia_drm nvidia_modeset nvidia-vgpu-vfio nvidia sudo modprobe nvidia NVreg_RestrictProfilingToAdminUsers=0 sudo systemctl isolate graphical ``` The above steps should result in a permanent change. _Temporary solution_ When running on bare metal, you can run nvprof with `sudo`. If you're running in a Docker image, you can temporarily elevate your privileges with one of the following (oldest to newest syntax):
nvidia-docker run --privileged
docker run --runtime nvidia --privileged
docker run --gpus all --privileged
================================================ FILE: KoSimCSE/apex/pyprof/__init__.py ================================================ import warnings from . import nvtx, prof ================================================ FILE: KoSimCSE/apex/pyprof/examples/.gitignore ================================================ __pycache__ *.sql *.dict *.csv ================================================ FILE: KoSimCSE/apex/pyprof/examples/apex/README.md ================================================ This directory has examples of how to use `pyprof` with APEX extensions e.g. `fused_adam_cuda` and `fused_layer_norm_cuda`. ================================================ FILE: KoSimCSE/apex/pyprof/examples/apex/fused_adam.py ================================================ import torch import fused_adam_cuda from apex.optimizers import FusedAdam, FP16_Optimizer from apex import pyprof pyprof.nvtx.init() pyprof.nvtx.wrap(fused_adam_cuda, 'adam') model = torch.nn.Linear(10, 20).cuda().half() criterion = torch.nn.CrossEntropyLoss().cuda() optimizer = FusedAdam(model.parameters()) optimizer = FP16_Optimizer(optimizer) x = torch.ones(32, 10).cuda().half() target = torch.empty(32, dtype=torch.long).random_(20).cuda() y = model(x) loss = criterion(y, target) optimizer.zero_grad() loss.backward() optimizer.step() ================================================ FILE: KoSimCSE/apex/pyprof/examples/apex/fused_layer_norm.py ================================================ import torch import fused_layer_norm_cuda from apex.normalization import FusedLayerNorm from apex import pyprof pyprof.nvtx.init() pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'backward') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'forward_affine') pyprof.nvtx.wrap(fused_layer_norm_cuda, 'backward_affine') input = torch.randn(20, 5, 10, 10).cuda() # With Learnable Parameters m = FusedLayerNorm(input.size()[1:]).cuda() output = m(input) # Without Learnable Parameters m = FusedLayerNorm(input.size()[1:], elementwise_affine=False).cuda() output = m(input) # Normalize over last two dimensions m = FusedLayerNorm([10, 10]).cuda() output = m(input) # Normalize over last dimension of size 10 m = FusedLayerNorm(10).cuda() output = m(input) ================================================ FILE: KoSimCSE/apex/pyprof/examples/apex/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSimCSE/apex/pyprof/examples/custom_func_module/README.md ================================================ This directory has examples which show how to intercept (monkey patch) custom functions and modules with `pyprof`. No changes are required in `pyprof/parse`, however, users can add support for bytes and flops calculation for custom functions and modules in `pyprof/prof` by extending the `OperatorLayerBase` class. ================================================ FILE: KoSimCSE/apex/pyprof/examples/custom_func_module/custom_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof #Initialize pyprof pyprof.nvtx.init() class Foo(torch.autograd.Function): @staticmethod def forward(ctx, in1, in2): out = in1 + in2 #This could be a custom C/C++ function. return out @staticmethod def backward(ctx, grad): in1_grad = grad #This could be a custom C/C++ function. in2_grad = grad #This could be a custom C/C++ function. return in1_grad, in2_grad #Hook the forward and backward functions to pyprof pyprof.nvtx.wrap(Foo, 'forward') pyprof.nvtx.wrap(Foo, 'backward') foo = Foo.apply x = torch.ones(4,4).cuda() y = torch.ones(4,4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x,y) profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/custom_func_module/custom_module.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof pyprof.nvtx.init() class Foo(torch.nn.Module): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) def forward(self, input): return self.n*input + self.m #Hook the forward function to pyprof pyprof.nvtx.wrap(Foo, 'forward') foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x) profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/custom_func_module/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSimCSE/apex/pyprof/examples/imagenet/imagenet.py ================================================ #!/usr/bin/env python3 """ Example to run pyprof with imagenet models. """ import sys import torch import torch.nn as nn import torchvision.models as models import torch.cuda.profiler as profiler import argparse from apex import pyprof from apex.optimizers import FusedAdam def parseArgs(): parser = argparse.ArgumentParser(prog=sys.argv[0], description="Run popular imagenet models.") parser.add_argument("-m", type=str, default="resnet50", choices=["alexnet", "densenet121", "densenet161", "densenet169", "densenet201", "googlenet", "mnasnet0_5", "mnasnet0_75", "mnasnet1_0", "mnasnet1_3", "mobilenet_v2", "resnet18", "resnet34", "resnet50", "resnet101", "resnet152", "resnext50_32x4d", "resnext101_32x8d", "wide_resnet50_2", "wide_resnet101_2", "shufflenet_v2_x0_5", "shufflenet_v2_x1_0", "shufflenet_v2_x1_5", "shufflenet_v2_x2_0", "squeezenet1_0", "squeezenet1_1", "vgg11", "vgg11_bn", "vgg13", "vgg13_bn", "vgg16", "vgg16_bn", "vgg19", "vgg19_bn", "inception_v3"], help="Model.") parser.add_argument("-b", type=int, default=32, help="Batch size.") parser.add_argument("-o", type=str, default="adam", choices=["adam", "sgd"], help="Optimizer.") args = parser.parse_args() return args d = { "alexnet": {'H': 224, 'W': 224, 'opts': {}}, "densenet121": {'H': 224, 'W': 224, 'opts': {}}, "densenet161": {'H': 224, 'W': 224, 'opts': {}}, "densenet169": {'H': 224, 'W': 224, 'opts': {}}, "densenet201": {'H': 224, 'W': 224, 'opts': {}}, "googlenet": {'H': 224, 'W': 224, 'opts': {'aux_logits': False}}, "mnasnet0_5": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet0_75": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet1_0": {'H': 224, 'W': 224, 'opts': {}}, "mnasnet1_3": {'H': 224, 'W': 224, 'opts': {}}, "mobilenet_v2": {'H': 224, 'W': 224, 'opts': {}}, "resnet18": {'H': 224, 'W': 224, 'opts': {}}, "resnet34": {'H': 224, 'W': 224, 'opts': {}}, "resnet50": {'H': 224, 'W': 224, 'opts': {}}, "resnet101": {'H': 224, 'W': 224, 'opts': {}}, "resnet152": {'H': 224, 'W': 224, 'opts': {}}, "resnext50_32x4d": {'H': 224, 'W': 224, 'opts': {}}, "resnext101_32x8d": {'H': 224, 'W': 224, 'opts': {}}, "wide_resnet50_2": {'H': 224, 'W': 224, 'opts': {}}, "wide_resnet101_2": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x0_5": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x1_0": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x1_5": {'H': 224, 'W': 224, 'opts': {}}, "shufflenet_v2_x2_0": {'H': 224, 'W': 224, 'opts': {}}, "squeezenet1_0": {'H': 224, 'W': 224, 'opts': {}}, "squeezenet1_1": {'H': 224, 'W': 224, 'opts': {}}, "vgg11": {'H': 224, 'W': 224, 'opts': {}}, "vgg11_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg13": {'H': 224, 'W': 224, 'opts': {}}, "vgg13_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg16": {'H': 224, 'W': 224, 'opts': {}}, "vgg16_bn": {'H': 224, 'W': 224, 'opts': {}}, "vgg19": {'H': 224, 'W': 224, 'opts': {}}, "vgg19_bn": {'H': 224, 'W': 224, 'opts': {}}, "inception_v3": {'H': 299, 'W': 299, 'opts': {'aux_logits': False}}, } def main(): args = parseArgs() pyprof.nvtx.init() # pyprof.nvtx.wrap(fused_adam_cuda, 'adam') N = args.b C = 3 H = d[args.m]['H'] W = d[args.m]['W'] opts = d[args.m]['opts'] classes = 1000 net = getattr(models, args.m) net = net(**opts).cuda().half() net.train() x = torch.rand(N, C, H, W).cuda().half() target = torch.empty(N, dtype=torch.long).random_(classes).cuda() criterion = nn.CrossEntropyLoss().cuda() if (args.o == "sgd"): optimizer = torch.optim.SGD(net.parameters(), lr = 0.01, momentum=0.9) elif (args.o == "adam"): optimizer = FusedAdam(net.parameters()) else: assert False #Warm up without profiler for i in range(2): output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() with torch.autograd.profiler.emit_nvtx(): profiler.start() output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() profiler.stop() if __name__ == "__main__": main() ================================================ FILE: KoSimCSE/apex/pyprof/examples/imagenet/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python -m apex.pyprof.parse" prof="python -m apex.pyprof.prof" for net in "resnet50" do for optim in adam sgd do for batch in 32 64 do base="torchvision".$net.$optim.$batch sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql --profile-from-start off python imagenet.py -m ${net} -o $optim -b $batch" nvprof -fo $sql --profile-from-start off python imagenet.py -m ${net} -o $optim -b $batch #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict # \rm $sql $dict done done done ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/README.md ================================================ *As of this writing, these examples do not work because of changes being proposed in PyTorch.* There are two ways to use PyTorch JIT - Scripting - Tracing In addition, we can JIT a - Stand alone function - Class / class method This directory has an example for each of the 4 cases. Intercepting (monkey patching) JITted code has a few extra steps, which are explained through comments. ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/jit_script_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof #The following creates an object "foo" of type ScriptModule #The new object has a function called "forward" @torch.jit.script def foo(x, y): return torch.sigmoid(x) + y #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "foo" foo.__name__ = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(foo, 'forward') x = torch.zeros(4,4).cuda() y = torch.ones(4,4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x, y) profiler.stop() print(z) ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/jit_script_method.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof class Foo(torch.jit.ScriptModule): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) @torch.jit.script_method def forward(self, input): return self.n*input + self.m #Initialize pyprof after the JIT step pyprof.nvtx.init() #Hook up the forward function to pyprof pyprof.nvtx.wrap(Foo, 'forward') foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() z = foo(x) profiler.stop() print(z) ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/jit_trace_function.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof def foo(x, y): return torch.sigmoid(x) + y x = torch.zeros(4,4).cuda() y = torch.ones(4,4).cuda() #JIT the function using tracing #This returns an object of type ScriptModule with a forward method. traced_foo = torch.jit.trace(foo, (x,y)) #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "traced_foo" traced_foo.__dict__['__name__'] = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(traced_foo, 'forward') with torch.autograd.profiler.emit_nvtx(): profiler.start() z = traced_foo(x, y) profiler.stop() print(z) ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/jit_trace_method.py ================================================ #!/usr/bin/env python3 import torch import torch.cuda.profiler as profiler from apex import pyprof class Foo(torch.nn.Module): def __init__(self, size): super(Foo, self).__init__() self.n = torch.nn.Parameter(torch.ones(size)) self.m = torch.nn.Parameter(torch.ones(size)) def forward(self, input): return self.n*input + self.m foo = Foo(4) foo.cuda() x = torch.ones(4).cuda() #JIT the class using tracing traced_foo = torch.jit.trace(foo, x) #Initialize pyprof after the JIT step pyprof.nvtx.init() #Assign a name to the object "traced_foo" traced_foo.__dict__['__name__'] = "foo" #Hook up the forward function to pyprof pyprof.nvtx.wrap(traced_foo, 'forward') with torch.autograd.profiler.emit_nvtx(): profiler.start() z = traced_foo(x) profiler.stop() print(z) ================================================ FILE: KoSimCSE/apex/pyprof/examples/jit/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo $sql python $f" nvprof -fo $sql python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict $prof -w 130 $dict \rm $sql $dict done ================================================ FILE: KoSimCSE/apex/pyprof/examples/lenet.py ================================================ #!/usr/bin/env python3 import torch import torch.nn as nn import torch.nn.functional as F import torch.cuda.profiler as profiler import torch.optim as optim from apex import pyprof pyprof.nvtx.init() class LeNet5(nn.Module): def __init__(self): super(LeNet5, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features with torch.autograd.profiler.emit_nvtx(): net = LeNet5().cuda() input = torch.randn(1, 1, 32, 32).cuda() out = net(input) target = torch.randn(10) # a dummy target, for example target = target.view(1, -1).cuda() # make it the same shape as output criterion = nn.MSELoss() # create your optimizer optimizer = optim.SGD(net.parameters(), lr=0.01) # in your training loop: optimizer.zero_grad() # zero the gradient buffers profiler.start() output = net(input) loss = criterion(output, target) loss.backward() optimizer.step() # Does the update profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/operators.py ================================================ #!/usr/bin/env python3 """ This file checks all Python operators. """ import sys import torch import torch.cuda.profiler as profiler import operator import inspect #Import and initialize pyprof from apex import pyprof pyprof.nvtx.init() X = 1024 Y = 1024 fa = torch.rand(X, Y).cuda() fb = torch.rand(X, Y).cuda() fc = torch.rand(X, Y).cuda() ia = torch.randint(0, 100, (X, Y)).cuda() ib = torch.randint(0, 100, (X, Y)).cuda() sa = torch.ones(1,1).cuda() sb = torch.ones(1,1).cuda() ba = fa.byte() unaryOps = ["abs", "__abs__", "neg", "__neg__",] invertOps = ["inv", "invert", "__inv__", "__invert__",] #imlemented only for byte tensors #pos, __pos__ is not implemented for tensors binaryOps = [] binaryOps += [ "lt", "__lt__", "le", "__le__", "eq", "__eq__", "ne", "__ne__", "ge", "__ge__", "gt", "__gt__" ] binaryOps += [ "add", "__add__", "sub", "__sub__", "mul", "__mul__", "floordiv", "__floordiv__", "truediv", "__truediv__", "pow", "__pow__", "mod", "__mod__"] binaryOps += [ "and_", "__and__", "or_", "__or__", "xor", "__xor__", "lshift", "__lshift__", "rshift", "__rshift__"] inplaceOps = [] inplaceOps += ["iadd", "__iadd__", "isub", "__isub__", "imul", "__imul__", "ifloordiv", "__ifloordiv__", "itruediv", "__itruediv__", "imod", "__imod__",] #ipow, __ipow__ is not implemented in pytorch inplaceOps += [ "iand", "__iand__", "ior", "__ior__", "ixor", "__ixor__", "ilshift", "__ilshift__", "irshift", "__irshift__",] matmulOps = [ "matmul", "__matmul__" ] inplacematmulOps = [ "imatmul", "__imatmul__" ] reverseIntBinaryOps = ["__radd__", "__rsub__", "__rmul__", "__rfloordiv__", "__rpow__",] reverseFloatBinaryOps = ["__radd__", "__rsub__", "__rmul__", "__rdiv__", "__rtruediv__", "__rfloordiv__", "__rpow__",] ''' TODO .concat(a, b) .__concat__(a, b) .contains(a, b) .__contains__(a, b) .countOf(a, b) .delitem(a, b) .__delitem__(a, b) .getitem(a, b) .__getitem__(a, b) .indexOf(a, b) .setitem(a, b, c) .__setitem__(a, b, c) .length_hint(obj, default=0) .iconcat(a, b) .__iconcat__(a, b) .index(a) .__index__(a) ''' #Context manager with torch.autograd.profiler.emit_nvtx(): #Start profiler profiler.start() for op in unaryOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ia) for op in invertOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ba) for op in binaryOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(ia, ib) c = f(ia, 2) for op in inplaceOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) ia = f(ia, ib) ia = f(ia, 2) for op in matmulOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) c = f(fa, fb) for op in inplacematmulOps: assert hasattr(operator, op) f = getattr(operator, op) assert inspect.isbuiltin(f) fa = f(fa, fb) for op in reverseIntBinaryOps: assert hasattr(torch.Tensor, op) f = getattr(torch.Tensor, op) ia = f(ia, ib) for op in reverseFloatBinaryOps: assert hasattr(torch.Tensor, op) f = getattr(torch.Tensor, op) fa = f(fa, fb) ''' #c = fa[3] #c = fa[3][3] #c = torch.min(fa, 3) c = torch.sum(fa) c = torch.max(fa) c = -fa #fc[2][2] = fa[2][2] c = a_scalar and b_scalar c = a_scalar or b_scalar c = not a_scalar c = a is b c = a is not b ''' #Stop profiler profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/simple.py ================================================ #!/usr/bin/env python3 """ This simple file provides an example of how to - import the pyprof library and initialize it - use the emit_nvtx context manager - start and stop the profiler Only kernels within profiler.start and profiler.stop calls are profiled. To profile $ nvprof -f -o simple.sql --profile-from-start off ./simple.py """ import sys import torch import torch.cuda.profiler as profiler #Import and initialize pyprof from apex import pyprof pyprof.nvtx.init() a = torch.randn(5, 5).cuda() b = torch.randn(5, 5).cuda() #Context manager with torch.autograd.profiler.emit_nvtx(): #Start profiler profiler.start() c = a + b c = torch.mul(a,b) c = torch.matmul(a,b) c = torch.argmax(a, dim=1) c = torch.nn.functional.pad(a, (1,1)) #Stop profiler profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/user_annotation/README.md ================================================ Nvidia NVTX range markers (https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm) are a useful tool to capture and observe events and code ranges etc. Using PyTorch APIs e.g, `torch.cuda.nvtx.range_push("xxx")` and `torch.cuda.nvtx.range_pop()` users can easily add their own NVTX range markers. These markers can then be observed in the Nvidia Visual Profiler (NVVP). While inserting NVTX markers (strings), if the users follow a specific string pattern `"layer:your_string_here"` e.g. `"layer:conv1"` or `"layer:encoder_layer_3_self_attention`, then `pyprof` will display the strings `conv1` and `encoder_layer_3_self_attention` next to the associated kernels in the output of `prof.py` when used with the `-c layer` option. NVTX range markers can be nested and if users follow the above string pattern, the output of `prof.py` will show all the markers associated with a kernel. The file `resnet.py` (a simplified version of the torchvision model) shows an example of how users can add (nested) NVTX markers with information which can greatly aid in understanding and analysis of networks. Note that the pattern `"layer:your_string_here"` was chosen to aid information extraction by `pyprof`. The tool will work seamlessly even if there are other markers or no markers at all. ### To run ```sh nvprof -fo resnet.sql --profile-from-start off python resnet.py parse.py resnet.sql > resnet.dict prof.py --csv -c idx,layer,dir,mod,op,kernel,params,sil resnet.dict ``` The file `resnet.sql` can also be opened with NVVP as usual. ================================================ FILE: KoSimCSE/apex/pyprof/examples/user_annotation/resnet.py ================================================ #!/usr/bin/env python3 """ An example showing use of nested NVTX markers. """ import torch import torch.nn as nn import torch.cuda.profiler as profiler import torch.cuda.nvtx as nvtx from apex import pyprof pyprof.nvtx.init() def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class Bottleneck(nn.Module): expansion = 4 count = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = int(planes * (base_width / 64.)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride self.id = Bottleneck.count Bottleneck.count += 1 def forward(self, x): identity = x nvtx.range_push("layer:Bottleneck_{}".format(self.id)) nvtx.range_push("layer:Conv1") out = self.conv1(x) nvtx.range_pop() nvtx.range_push("layer:BN1") out = self.bn1(out) nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_push("layer:Conv2") out = self.conv2(out) nvtx.range_pop() nvtx.range_push("layer:BN2") out = self.bn2(out) nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_push("layer:Conv3") out = self.conv3(out) nvtx.range_pop() nvtx.range_push("layer:BN3") out = self.bn3(out) nvtx.range_pop() if self.downsample is not None: nvtx.range_push("layer:Downsample") identity = self.downsample(x) nvtx.range_pop() nvtx.range_push("layer:Residual") out += identity nvtx.range_pop() nvtx.range_push("layer:ReLU") out = self.relu(out) nvtx.range_pop() nvtx.range_pop() return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, groups=1, width_per_group=64, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=2) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride=1, dilate=False): norm_layer = self._norm_layer downsample = None previous_dilation = self.dilation if dilate: self.dilation *= stride stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample, self.groups, self.base_width, previous_dilation, norm_layer)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=self.dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def forward(self, x): nvtx.range_push("layer:conv1_x") x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) nvtx.range_pop() nvtx.range_push("layer:conv2_x") x = self.layer1(x) nvtx.range_pop() nvtx.range_push("layer:conv3_x") x = self.layer2(x) nvtx.range_pop() nvtx.range_push("layer:conv4_x") x = self.layer3(x) nvtx.range_pop() nvtx.range_push("layer:conv5_x") x = self.layer4(x) nvtx.range_pop() x = self.avgpool(x) x = torch.flatten(x, 1) nvtx.range_push("layer:FC") x = self.fc(x) nvtx.range_pop() return x def resnet50(): return ResNet(Bottleneck, [3, 4, 6, 3]) #Create model net = resnet50().cuda().half() net.train() #Create optimizer criterion = nn.CrossEntropyLoss().cuda() optimizer = torch.optim.SGD(net.parameters(), lr = 0.01, momentum=0.9) #Create synthetic input and label x = torch.rand(32, 3, 224, 224).cuda().half() target = torch.empty(32, dtype=torch.long).random_(1000).cuda() with torch.autograd.profiler.emit_nvtx(): profiler.start() output = net(x) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() profiler.stop() ================================================ FILE: KoSimCSE/apex/pyprof/examples/user_annotation/test.sh ================================================ #!/bin/bash set -e SCRIPT=`realpath $0` SCRIPTPATH=`dirname $SCRIPT` PYPROF="$SCRIPTPATH/../.." parse="python $PYPROF/parse/parse.py" prof="python $PYPROF/prof/prof.py" for f in *.py do base=`basename $f .py` sql=$base.sql dict=$base.dict #NVprof echo "nvprof -fo --profile-from-start off $sql python $f" nvprof -fo $sql --profile-from-start off python $f #Parse echo $parse $sql $parse $sql > $dict #Prof echo $prof $dict #$prof -w 130 $dict $prof --csv -c idx,layer,dir,mod,op,kernel,params,sil $dict \rm $sql $dict done ================================================ FILE: KoSimCSE/apex/pyprof/nvtx/__init__.py ================================================ from .nvmarker import init from .nvmarker import add_wrapper as wrap ================================================ FILE: KoSimCSE/apex/pyprof/nvtx/nvmarker.py ================================================ """ This file intercepts (monkey patches) the following functions and adds NVTX markers. torch.* torch.Tensor.* torch.nn.functional.* torch.nn.*.forward The NVTX markers (one or more) contain the following information call trace (a list of file_name:line_number) extra_repr() from torch.nn modules module/class name function name inputs (args and kwargs) scalar: name, type and value tensor: name, shape and datatype numpy: name, shape and datatype list/tuple: a sequence of scalars or tensors or numpy arrays """ import torch import torch.cuda.nvtx as nvtx import numpy import inspect as ins import traceback import math def isfunc(mod, f): assert hasattr(mod, f) attr = getattr(mod, f) #Ignore functions like _add if (len(f) >= 2): if f[0] == "_" and f[1] != "_": return False #Ignore functions from this list ignore = ['__all__', '__array__', '__array_priority__', '__array_wrap__', '__bool__', '__builtins__', '__cached__', '__class__', '__deepcopy__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__file__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__index__', '__init__', '__init_subclass__', '__iter__', '__len__', '__loader__', '__module__', '__name__', '__new__', '__nonzero__', '__package__', '__path__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__spec__', '__str__', '__subclasshook__', '__version__', '__weakref__'] #Add functions to this list if they cause recursion ignore += ['size', 'tolist', 'dim', 'is_storage', 'item'] if f in ignore: return False return ins.ismethod(attr) or ins.isfunction(attr) or ins.ismethoddescriptor(attr) or ins.isbuiltin(attr) def traceMarker(stack): d = {} cadena = [] for i in range(len(stack)-1): fi = stack[i] t = "{}:{}".format(fi.filename, fi.lineno) cadena.append(t) d['traceMarker'] = cadena return str(d) def modMarker(mod, fn_name, args): """ Returns the stringified extra_repr() of a module. """ assert(fn_name == 'forward') assert(len(args) > 0) d = {} d['mod'] = mod.__name__ d['strRepr'] = args[0].extra_repr() return str(d) def add_wrapper(mod, fn_name): assert isfunc(mod, fn_name) # Get a pointer to the original function func = getattr(mod, fn_name) # Check if the mod has a string representation # and is not a Script or Traced module (used by JIT) s = hasattr(mod, "extra_repr") and (type(mod) is not torch.jit.ScriptModule) and (type(mod) is not torch.jit.TopLevelTracedModule) def wrapper_func(*args, **kwargs): # Extract the stacktrace stack = traceback.extract_stack() # Push trace marker nvtx.range_push(traceMarker(stack)) # Push module marker if s: m = modMarker(mod, fn_name, args) nvtx.range_push(m) # Create and push argument marker cadena = argMarker(mod, fn_name, args, kwargs) nvtx.range_push(cadena) # Call the original function result = func(*args, **kwargs) # Pop argumet marker nvtx.range_pop() # Pop module marker if s: nvtx.range_pop() # Pop trace marker nvtx.range_pop() return result setattr(mod, fn_name, wrapper_func) def argMarker(mod, op, args, kwargs): #For this function args is a tuple and kwargs is a dict def tensor(arg, name=""): a = {} a['name'] = name a['type'] = "tensor" a['shape'] = tuple(arg.size()) a['dtype'] = str(arg.dtype).split(".")[-1] cadena['args'].append(a) def ndarray(arg, name=""): a = {} a['name'] = name a['type'] = "ndarray" a['shape'] = arg.shape a['dtype'] = str(arg.dtype).split(".")[-1] cadena['args'].append(a) def seq(arg, name=""): assert issequence(arg) a = {} a['name'] = name if isinstance(arg, list): a['type'] = "list" a['value'] = arg else: a['type'] = "tuple" # The arg could be torch.Size, which is a subclass of tuple # Therefore, explicitly convert to tuple a['value'] = tuple(arg) cadena['args'].append(a) def scalar(arg, name=""): a = {} a['name'] = name a['type'] = type(arg).__name__ #handle the case when the argument is +/- inf or nan if arg == float('inf'): a['value'] = "inf" elif arg == float('-inf'): a['value'] = "-inf" elif isinstance(arg, float) and math.isnan(arg): a['value'] = "nan" else: a['value'] = arg cadena['args'].append(a) def isscalar(arg): return (type(arg) is int) or (type(arg) is float) or (type(arg) is bool) or (arg is None) or (type(arg) is str) def issequence(arg): return isinstance(arg, list) or isinstance(arg, tuple) def foo(args, name): #args should be an iterable sequence e.g. list or tuple for arg in args: if isinstance(arg, torch.Tensor): if arg.dim() == 0: scalar(arg.item(), name) else: tensor(arg, name) elif isinstance(arg, numpy.ndarray): ndarray(arg, name) elif (isscalar(arg)): scalar(arg, name) elif issequence(arg): if (len(arg) == 0) or isscalar(arg[0]): #An empty sequence or a sequence of scalars seq(arg, name) else: # A sequence of tensors or numpy arrays foo(arg, name) ''' else: print("The following arg is none of Tensor, numpy array, scalar but a %s" % (str(type(arg)))) print("Mod: %s" % str(mod.__name__)) print("Op: %s" % str(op)) print(dir(arg)) ''' cadena = {} cadena['mod'] = mod.__name__ cadena['op'] = op cadena['args'] = [] foo(args, "") for k,v in kwargs.items(): foo((v,), k) return str(cadena) def patchClass(cls): for f in dir(cls): if isfunc(cls, f): add_wrapper(cls, f) def init(): string = "\n\nPyprof has been moved to its own dedicated repository and will " + \ "soon be removed from Apex. Please visit\n" + \ "https://github.com/NVIDIA/PyProf\n" + \ "for the latest version.\n\n" # print regardless of warning state print(string) print("Initializing NVTX monkey patches") for cls in [torch, torch.Tensor, torch.nn.functional,]: patchClass(cls) for cls in [torch.nn.RNN, torch.nn.RNNCell, torch.nn.LSTM, torch.nn.LSTMCell, torch.nn.GRU, torch.nn.GRUCell]: if isfunc(cls, 'forward'): add_wrapper(cls, 'forward') print("Done with NVTX monkey patching") ================================================ FILE: KoSimCSE/apex/pyprof/parse/__init__.py ================================================ ================================================ FILE: KoSimCSE/apex/pyprof/parse/__main__.py ================================================ import warnings try: from .parse import main except ImportError as e: warnings.warn("Did you make sure to install PyProf dependencies by using the --pyprof flag during Apex installation?)") raise e if __name__ == '__main__': main() ================================================ FILE: KoSimCSE/apex/pyprof/parse/db.py ================================================ import sys, sqlite3 class DB(object): """ This class provides functions for DB operations with exception handling. """ def __init__(self, dbFile): try: conn = sqlite3.connect(dbFile) conn.row_factory = sqlite3.Row c = conn.cursor() except: print("Error opening {}".format(dbFile)) sys.exit(1) self.conn = conn self.c = c def select(self, cmd): try: self.c.execute(cmd) #rows = self.c.fetchall() rows = [dict(row) for row in self.c.fetchall()] except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) #print(rows) return rows def insert(self, cmd, data): try: self.c.execute(cmd, data) except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) def execute(self, cmd): try: self.c.execute(cmd) except sqlite3.Error as e: print(e) sys.exit(1) except: print("Uncaught error in SQLite access while executing {}".format(cmd)) sys.exit(1) def commit(self): self.conn.commit() def close(self): self.c.close() self.conn.close() ================================================ FILE: KoSimCSE/apex/pyprof/parse/kernel.py ================================================ import cxxfilt, struct, binascii #Helper functions def demangle(name): """ Demangle a C++ string """ return cxxfilt.demangle(name) def encode_object_id(pid, tid): """ Given process id (pid) and thread id (tid), return the object id. object id = pid (little endian 4 bytes) + tid (little endian 8 bytes) """ objId = struct.pack(' start, "This assertion can fail for very large profiles. It usually fails when start = end = 0." self.kStartTime = start self.kEndTime = end self.kDuration = end - start assert (start > Kernel.profStart) self.device = int(info['deviceId']) self.stream = int(info['streamId']) self.grid = (info['gridX'], info['gridY'], info['gridZ']) self.block = (info['blockX'], info['blockY'], info['blockZ']) self.timeOffset = Kernel.profStart def setKernelName(self, name): cadena = demangle(name) self.kLongName = cadena self.kShortName = getShortName(cadena) def setRunTimeInfo(self, info): start, end, pid, tid = info self.rStartTime = start self.rEndTime = end self.rDuration = end - start self.pid = pid self.tid = tid self.objId = encode_object_id(pid, tid) def setMarkerInfo(self, info): self.layerMarkers, self.traceMarkers, self.reprMarkers, self.pyprofMarkers, self.seqMarkers, self.otherMarkers, self.altMarkers, self.seqId, self.altSeqId, self.layer = info self.subSeqId = 0 def setDirection(self): """ Set direction (fprop, bprop) based on PyTorch sequence markers. It is a heuristic and not a foolproof method. """ if any("Backward, seq = " in x for x in self.seqMarkers) or \ any("backward, seq = " in x for x in self.seqMarkers) or \ any("Backward0, seq = " in x for x in self.seqMarkers): self.dir = "bprop" else: self.dir = "fprop" def setOp(self): """ Detect and set the class/module (mod) and operation (op) of the kernel e.g. torch.nn.functional / linear, torch / sigmoid. The lookup sequence we use is NVTX markers inserted by pyprof NVTX markers inserted by PyTorch in bprop NVTX markers inserted by PyTorch in fprop It is a heuristic and not a foolproof method. """ def sanitize(name): name = name.replace("torch","") \ .replace("autograd","") \ .replace("_backward","") \ .replace("::","") \ .replace("jit","") \ .replace("(anonymous namespace)","") head, sep, tail = name.partition("Backward") return head #Check pyprof markers for m in self.pyprofMarkers: assert ("mod" in m) and ("op" in m) and ("args" in m) t = eval(m) self.op.append(t['op']) self.mod.append(t['mod']) if len(self.op): return #Check bprop kernel markers for m in self.seqMarkers: if ("backward, seq = " in m) or ("Backward, seq = " in m): op = m.split(",")[0] op = sanitize(op) self.op.append(op) self.mod.append('na') if len(self.op): return #Check markers with "seq = " for m in self.seqMarkers: if ", seq = " in m: op = m.split(",")[0] self.op.append(op) self.mod.append('na') if len(self.op): return #If nothing else if len(self.otherMarkers): self.op.append(self.otherMarkers[0]) self.mod.append('na') def print(self): """ Print kernel information. This is used by prof.py. """ a = lambda: None a.kShortName = self.kShortName a.kDuration = self.kDuration #a.layerMarkers = self.layerMarkers a.layer = self.layer a.trace = self.traceMarkers a.reprMarkers = self.reprMarkers a.marker = self.pyprofMarkers a.seqMarker = self.seqMarkers a.seqId = self.seqId a.subSeqId = self.subSeqId a.altSeqId = self.altSeqId a.dir = self.dir a.mod = self.mod a.op = self.op a.tid = self.tid a.device = self.device a.stream = self.stream a.grid = self.grid a.block = self.block a.kLongName = self.kLongName print(a.__dict__) ================================================ FILE: KoSimCSE/apex/pyprof/parse/nvvp.py ================================================ import sys class NVVP(object): """ This class gets kernel information from the SQL (nvvp) database. """ driverT = "CUPTI_ACTIVITY_KIND_DRIVER" runtimeT = "CUPTI_ACTIVITY_KIND_RUNTIME" kernelT = "CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL" markerT = "CUPTI_ACTIVITY_KIND_MARKER" stringT = "StringTable" def __init__(self, db): self.db = db self.markerId = 0 def getProfileStart(self): """ Get the profile start time """ profStart = sys.maxsize for table in [self.driverT, self.runtimeT, self.kernelT, self.markerT]: colname = "timestamp" if table is self.markerT else "start" cmd = "select {} from {} ORDER BY {} ASC LIMIT 1".format(colname, table, colname) result = self.db.select(cmd) assert(len(result) <= 1) if (len(result) == 1): assert(colname in result[0]) t = result[0][colname] if (t < profStart): profStart = t assert(profStart < sys.maxsize) return profStart def getString(self, id_): """ Get the string associated with an id. """ cmd = "select value from {} where _id_ = {}".format(self.stringT, id_) result = self.db.select(cmd) assert (len(result) == 1) return result[0]['value'] def createMarkerTable(self): """ Create a temporary table and index it to speed up repeated SQL quesries. The table is an INNER JOIN of CUPTI_ACTIVITY_KIND_MARKER with itself. """ cmd = 'CREATE TEMPORARY TABLE marker AS SELECT \ a._id_ as id, \ a.timestamp AS startTime, \ b.timestamp AS endTime, \ HEX(a.objectId) AS objectId, \ a.name AS name \ FROM {} AS a INNER JOIN {} AS b ON \ a.id = b.id and \ a.flags = 2 and b.flags = 4'.format(self.markerT, self.markerT) self.db.execute(cmd) self.db.execute('CREATE INDEX start_index ON marker (startTime)') self.db.execute('CREATE INDEX end_index ON marker (endTime)') self.db.execute('CREATE INDEX id_index ON marker (id)') def getCPUInfo(self, corrId): """ Given the correlation id, get CPU start, end, thread id, process id. The information can be in the runtime table or the driver table. """ #First look in the runtime table cmd = "select start,end,processId,threadId from {} where correlationId={}".format(self.runtimeT, corrId); result = self.db.select(cmd) assert (len(result) <= 1) if (len(result) == 0): #Look in the driver table cmd = "select start,end,processId,threadId from {} where correlationId={}".format(self.driverT, corrId); result = self.db.select(cmd) assert (len(result) == 1) info = result[0] start = info['start'] end = info['end'] pid = info['processId'] tid = info['threadId'] tid = tid & 0xffffffff #convert to unsigned assert (end > start) return [start, end, pid, tid] def getKernelInfo(self): """ Get GPU kernel info """ cmd = "select name,correlationId,start,end,deviceId,streamId,gridX,gridY,gridZ,blockX,blockY,blockZ from {}".format(self.kernelT) result = self.db.select(cmd) return result def getMarkerInfo(self, objId, startTime, endTime): """ This function first finds all NVTX markers encapsulating a runtime / driver kernel launch. It then splits the markers into many lists. layerMarkers : User added NVTX markers traceMarkers : Call trace markers (inserted by pyprof) reprMarkers : Markers containing the extra_repr() of a module (inserted by pyprof) pyprofMarkers: Markers containing args and kwargs (tensor shape, datatype etc.) seqMarkers : Markers containing PyTorch internal sequence markers (inserted by PyTorch) altSeqMarkers: Markers inserted by PyTorch between two kernel launches. Needs better explanation. otherMarkers : Markers not in either of the above categories. We extract seqId from the seq and altSeq markers. The seqId is used in bprop. We also extract information from the layerMarkers. """ layerMarkers = [] traceMarkers = [] reprMarkers = [] pyprofMarkers = [] seqMarkers = [] otherMarkers = [] altSeqMarkers = [] bprop = False #Helper functions def delete(objId, sTime): """ Delete rows from the temporary SQL table which are no longer required. This speeds up future queries. """ margin = 0 cmd = 'DELETE FROM marker WHERE objectId = "{}" AND endTime < {}'.format(objId, sTime - margin) #cmd = 'DELETE FROM marker WHERE endTime < {}'.format(sTime - margin) self.db.execute(cmd) def getLayerName(mlist): """ Get layer names from layer marker list. """ layers = [] assert(type(mlist) == list) for m in mlist: assert("layer:" in m) l = m.split(":")[1] layers.append(l) return layers def getSeqId(mlist): """ Get sequence ids from seq / alt seq marker list. """ ids = [] assert(type(mlist) == list) for m in mlist: assert(", seq = " in m) seq = int(m.split("=")[1]) ids.append(seq) #Remove duplicates ids = list(set(ids)) ids.sort() return ids def seqcompare(elem): """ Sorting function for sequence markers """ assert (", seq = " in elem) #sort by sequence id and then the string l = elem.split(" = ") return l[1] + l[0] def prune(mlist): """ Remove markers with the same seqId and if the strings are similar. This function works on a sorted sequence. """ assert (type(mlist) == list) assert (len(mlist)) a = mlist[0:1] for i in range(1,len(mlist)): m = mlist[i] pm = mlist[i-1] name,seq = m.split(",") pname,pseq = pm.split(",") similar = (name in pname) or (pname in name) if (seq == pseq) and similar: continue else: a.append(m) return a def filterTrace(mlist): """ Filter trace markers to remove certain file names. """ assert (type(mlist) == list) if len(mlist) == 0: return mlist mlist = mlist[-1] #The last stack trace will be a super set. mlist = eval(mlist) mlist = mlist['traceMarker'] assert (type(mlist) == list) mlist = list(filter(lambda x : "/torch/nn/modules/" not in x, mlist)) mlist = list(filter(lambda x : "/torch/nn/functional.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/tensor.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/autograd/__init__.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/_jit_internal.py" not in x, mlist)) mlist = list(filter(lambda x : "/pyprof/nvtx/nvmarker.py" not in x, mlist)) mlist = list(filter(lambda x : "/apex/optimizers/" not in x, mlist)) mlist = list(filter(lambda x : "/torch/_utils.py" not in x, mlist)) mlist = list(filter(lambda x : "/torch/optim/" not in x, mlist)) return mlist #Find all encapsulating markers cmd = 'SELECT id,name from marker where \ objectId = "{}" and \ startTime < {} and \ endTime > {} \ ORDER BY startTime ASC'.format(objId, startTime, endTime) result = self.db.select(cmd) #Bin markers into different lists for r in result: m = self.getString(r['name']) #Hack: If its a known gradient checkpointing marker, ignore it. if m.find("CheckpointFunctionBackward") >= 0: continue if ("_backward, seq =" in m) or ("Backward, seq =" in m) or ("Backward0, seq =" in m): bprop = True if ("mod" in m) and ("op" in m) and ("args" in m) and ("type" in m): pyprofMarkers.append(m) elif ("layer:" in m): layerMarkers.append(m) elif ("traceMarker" in m): traceMarkers.append(m) elif ("strRepr" in m): reprMarkers.append(m) elif (", seq = " in m): seqMarkers.append(m) else: otherMarkers.append(m) #Remove duplicates, sort and prune seqMarkers if (len(seqMarkers)): seqMarkers = list(set(seqMarkers)) seqMarkers.sort(key=seqcompare) seqMarkers = prune(seqMarkers) #Remove duplicates from otherMarkers otherMarkers = list(set(otherMarkers)) #Get markers with seq id (inserted by PyTorch) from the previous kernel to the present kernel #Only for fprop kernels if (len(result) and not bprop): loId = self.markerId hiId = result[-1]['id'] self.markerId = hiId #Get markers between loId and hiId cmd = 'SELECT id,name from marker where objectId = "{}" and id > {} and id < {} ORDER BY startTime ASC'.format(objId, loId, hiId) result1 = self.db.select(cmd) for r in result1: m = self.getString(r['name']) #Get only markers with seq id if (", seq=" in m): altSeqMarkers.append(m) #Remove duplicates, sort and prune altSeqMarkers if (len(altSeqMarkers)): altSeqMarkers = list(set(altSeqMarkers)) altSeqMarkers.sort(key=seqcompare) altSeqMarkers = prune(altSeqMarkers) delete(objId, startTime) return layerMarkers, filterTrace(traceMarkers), reprMarkers, pyprofMarkers, seqMarkers, otherMarkers, altSeqMarkers, getSeqId(seqMarkers), getSeqId(altSeqMarkers), getLayerName(layerMarkers) ================================================ FILE: KoSimCSE/apex/pyprof/parse/parse.py ================================================ #!/usr/bin/env python3 """ Parse the SQL db and print a dictionary for every kernel. """ import sys import argparse from tqdm import tqdm from .db import DB from .kernel import Kernel from .nvvp import NVVP def parseArgs(): parser = argparse.ArgumentParser(prog=sys.argv[0], description="Parse SQL (nvvp) db.") parser.add_argument("file", type=str, default=None, help="SQL db (nvvp) file.") args = parser.parse_args() return args def main(): args = parseArgs() db = DB(args.file) nvvp = NVVP(db) kInfo = nvvp.getKernelInfo() if len(kInfo) == 0: print("Found 0 kernels. Exiting.", file=sys.stderr) db.close() sys.exit(0) else: print("Found {} kernels. Getting info for each kernel.".format(len(kInfo)), file=sys.stderr) nvvp.createMarkerTable() prevSeqId = -1 prevSubSeqId = -1 prevOp = "na" Kernel.profStart = nvvp.getProfileStart() for i in tqdm(range(len(kInfo)), ascii=True): info = kInfo[i] k = Kernel() #Set kernel info k.setKernelInfo(info) #Get, set kernel name name = nvvp.getString(k.kNameId) k.setKernelName(name) #Get runtime info info = nvvp.getCPUInfo(k.corrId) k.setRunTimeInfo(info) #Get and set marker and seqid info info = nvvp.getMarkerInfo(k.objId, k.rStartTime, k.rEndTime) k.setMarkerInfo(info) #If the seqId contains both 0 and non zero integers, remove 0. if any(seq != 0 for seq in k.seqId) and (0 in k.seqId): k.seqId.remove(0) #Set direction (it uses seq id) k.setDirection() #Set op k.setOp() #The following code is based on heuristics. #TODO: Refactor. #Assign subSeqId, adjust seqId and altSeqId #seqId can be 0. #A kernel can have multiple seqIds both in fprop and bprop. #In bprop, seqIds might not decrease monotonically. I have observed a few blips. if len(k.seqId): assert (k.dir in ["fprop", "bprop"]) if (k.dir == "fprop"): #Check if there is a sequence id larger than the previous inc = (k.seqId[-1] > prevSeqId) if inc: currSeqId = [x for x in k.seqId if x > prevSeqId][0] else: currSeqId = prevSeqId else: currSeqId = k.seqId[0] #if ((currSeqId == prevSeqId) and (k.op == prevOp)): if ((currSeqId == prevSeqId) and (k.op == prevOp)) or ((k.op[0] == "forward") and (k.op == prevOp) and (k.mod[0] in ["LSTMCell", "GRUCell", "RNNCell"])): #The second condition is to trap cases when pytorch does not use cudnn for a LSTMCell. k.subSeqId = prevSubSeqId + 1 prevSeqId = currSeqId prevSubSeqId = k.subSeqId prevOp = k.op #Keep currSeqId in k.seqId, move everything else to k.altSeqId for s in k.seqId: if s != currSeqId: k.seqId.remove(s) k.altSeqId.append(s) for s in k.altSeqId: if s == currSeqId: k.altSeqId.remove(s) k.altSeqId = list(set(k.altSeqId)) if (len(k.altSeqId)): (k.altSeqId).sort() k.print() db.close() if __name__ == '__main__': main() ================================================ FILE: KoSimCSE/apex/pyprof/prof/__init__.py ================================================ from . import data, prof ================================================ FILE: KoSimCSE/apex/pyprof/prof/__main__.py ================================================ import warnings try: from .prof import main except ImportError as e: warnings.warn("Did you make sure to install PyProf dependencies by using the --pyprof flag during Apex installation?") raise e if __name__ == '__main__': main() ================================================ FILE: KoSimCSE/apex/pyprof/prof/activation.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Activation(OperatorLayerBase): """ This class handles the various activation functions. """ ops = ["celu", "elu", "elu_", "hardshrink", "hardtanh", "hardtanh_", "leaky_relu", "leaky_relu_", "logsigmoid", "prelu", "relu", "relu_", "relu6", "rrelu", "rrelu_", "selu", "sigmoid", "softplus", "softshrink", "softsign", "tanh", "tanhshrink", "threshold", "threshold_"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch.nn.functional", "torch", "Tensor"]) #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) >= 1) arg = args[0] assert (arg['type'] == "tensor") self.i = arg self.dir = d.dir def params(self): p = OrderedDict([('T', self.i['shape']),('type', self.i['dtype'])]) return p def flops(self): direction = self.dir tensor = self.i['shape'] t = self.i['dtype'] # TODO: revise elems = Utility.numElems(tensor) return elems def bytes(self): direction = self.dir tensor = self.i['shape'] t = self.i['dtype'] elems = Utility.numElems(tensor) elems = elems * (2 if direction == "fprop" else 3) return elems * Utility.typeToBytes(t) def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/base.py ================================================ from abc import ABC, abstractmethod class OperatorLayerBase(ABC): """ Base class for all layers and operators. Every derived class should have the following functions. """ @abstractmethod def tc(self): """ Tensor core usage by the kernel. Return "1" (yes), "0" (no, but possible), "-" (not applicable) """ pass @abstractmethod def params(self): """ Kernel parameters to be printed. """ pass @abstractmethod def flops(self): """ Note that 1 FMA = 2 flops. """ pass @abstractmethod def bytes(self): pass @abstractmethod def mod(self): """ Name of the module/class e.g. torch.nn.functional. """ pass @abstractmethod def op(self): """ Name of the operator e.g. sigmoid. """ pass ================================================ FILE: KoSimCSE/apex/pyprof/prof/blas.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase import numpy as np TC_GEMMS = ["884gemm", "1688gemm"] class Addmm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor",]) assert (op in ["addmm", "addmm_",]) #Get alpha and beta alpha = 1 beta = 1 if any(x['name'] == 'alpha' for x in args): alpha = list(filter(lambda x : x['name'] == "alpha", args))[0] alpha = alpha['value'] if any(x['name'] == 'beta' for x in args): beta = list(filter(lambda x : x['name'] == "beta", args))[0] beta = beta['value'] self.alpha = alpha self.beta = beta #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) == 3) C,A,B = args m,k1 = A['shape'] k2,n = B['shape'] assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] t3 = C['dtype'] assert(t1 == t2 == t3) self.A = A self.B = B self.C = C self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name return def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): return self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ def params(self): p = OrderedDict([('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p class Bmm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") and (op == "bmm") #Filter out named params (kwargs) args = list(filter(lambda x : x['name'] == "", args)) assert (len(args) == 2) A,B = args b1,m,k1 = A['shape'] b2,k2,n = B['shape'] assert (b1 == b2) assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) self.A = A self.B = B self.b = b1 self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def params(self): #p = OrderedDict([('A', A['shape']), ('B', B['shape']), ('type', t1)]) p = OrderedDict([('B',self.b), ('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p def flops(self): return self.b * self.m * self.n * self.k * 2 def bytes(self): b, m, n, k = self.b, self.m, self.n, self.k return Utility.typeToBytes(self.type) * b * (m*n + m*k + n*k) def op(self): return self.op_ def mod(self): return self.mod_ class Matmul(OperatorLayerBase): NON_GEMM = ["kernelPointwiseApply2", "reduce_1Block_kernel", "elementwise_kernel"] NON_TC = NON_GEMM + ["dot_kernel"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.name = d.name self.sub = d.sub assert ((mod == "torch") and (op == "matmul")) or ((mod == "Tensor") and (op == "__matmul__")) assert (len(args) == 2) assert any([x in d.name for x in Matmul.NON_TC + ["gemm", "gemv"]]) A,B = args t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) A = A['shape'] B = B['shape'] self.A = A self.B = B self.type = t1 # batch, MNK if (len(A) == 1) and (len(B) == 1): #dot product assert (A[0] == B[0]) self.b = (1,) self.m = 1 self.n = 1 self.k = A[0] elif (len(A) == 2) and (len(B) == 2): #gemm m,k1 = A k2,n = B assert(k1 == k2) self.b = (1,) self.m = m self.n = n self.k = k1 elif (len(A) == 1) and (len(B) == 2): #vector matrix k1 = A[0] k2,n = B assert(k1 == k2) self.b = (1,) self.m = 1 self.n = n self.k = k1 elif (len(A) == 2) and (len(B) == 1): #gemv m,k1 = A k2 = B[0] assert (k1 == k2) self.b = (1,) self.m = m self.n = 1 self.k = k1 elif (len(A) == 1) and (len(B) > 2): assert (A[0] == B[-2]) self.b = B[0:-2] self.m = 1 self.n = B[-1] self.k = B[-2] elif (len(B) == 1) and (len(A) > 2): assert (B[0] == A[-1]) self.b = A[0:-2] self.m = A[-2] self.n = 1 self.k = A[-1] else: assert (len(A) >= 2) assert (len(B) >= 2) assert (A[-1] == B[-2]) self.m = A[-2] self.n = B[-1] self.k = A[-1] aa = np.empty(A[0:-2]) bb = np.empty(B[0:-2]) self.b = np.broadcast(aa, bb).shape def params(self): return OrderedDict([('A', self.A), ('B', self.B), ('type', self.type)]) def tc(self): if self.name in Matmul.NON_TC: return "-" else: for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): # TODO: check bytes for non-GEMM cases if self.name in Matmul.NON_GEMM: return 2 * Utility.typeToBytes(self.type) * Utility.numElems(self.A) #could be B as well else: m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): # TODO: calculate actual FLOPs. At least we're not saying it's GEMM FLOPs for now. if self.name in Matmul.NON_GEMM: return 0 else: return Utility.numElems(self.b) * self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ class Mm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") and (op == "mm") assert (len(args) == 2) A,B = args m,k1 = A['shape'] k2,n = B['shape'] assert (k1 == k2) t1 = A['dtype'] t2 = B['dtype'] assert(t1 == t2) self.A = A self.B = B self.m = m self.n = n self.k = k1 self.type = t1 self.name = d.name return def params(self): p = OrderedDict([('M',self.n),('N',self.m),('K',self.k),('type',self.type)]) return p def tc(self): for s in TC_GEMMS: if s in self.name: return 1 return 0 def bytes(self): m, n, k = self.m, self.n, self.k return Utility.typeToBytes(self.type) * (m*n + m*k + n*k) def flops(self): return self.m * self.n * self.k * 2 def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/conv.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Conv(OperatorLayerBase): """ # N = batch size # C,H,W = input channels, height, width # K,P,Q = output channels, height, width # R,S = filter height, width # g = groups """ #todo: refine winograd and FFT convAuxList = ["nchwToNhwc", "nhwcToNchw", "OffsetsKernel",] winoAuxList = ["generateWinogradTilesKernel", "winogradWgradData", "winogradWgradOutput", "winogradWgradDelta"] fftAuxList = ["compute_gemm_pointers", "flip_filter", "fft2d_r2c_", "fft2d_c2r_", "fft1d_r2c", "fft1d_c2r"] miscAuxList = ["scaleTensor_kernel",] convList = ["_s884cudnn_", "_s1688cudnn_", "_scudnn_", "2d_grouped_direct_kernel", "cudnn::detail::implicit_convolve_sgemm", "cudnn::detail::dgrad2d_alg1_1", "cudnn::detail::wgrad_alg0_engine", "cudnn::detail::dgrad_engine", "dgrad_1x1_stride_2x2", "spatialDepthwiseConvolutionUpdateOutput"] winoList = ["winograd3x3Kernel", "_sgemm_"] fftList = ["fermiPlusCgemmLDS128_batched", "_gcgemm_",] miscList = [] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.dir = d.dir self.name = d.name self.sub = d.sub assert (mod == "torch.nn.functional") assert (op in ["conv1d", "conv2d"]) length = len(args) assert (length >= 2) and (length <= 7) i,w = args[0], args[1] assert (i['type'] == "tensor") assert (w['type'] == "tensor") #ignore bias if (length >= 4) and (args[3]['name'] == ""): s = args[3] elif any(x['name'] == 'stride' for x in args): s = list(filter(lambda x : x['name'] == 'stride', args))[0] else: s = {'name': 'stride', 'type': 'int', 'value': 1} if (length >= 5) and (args[4]['name'] == ""): p = args[4] elif any(x['name'] == 'padding' for x in args): p = list(filter(lambda x : x['name'] == 'padding', args))[0] else: p = {'name': 'padding', 'type': 'int', 'value': 0} if (length >= 6) and (args[5]['name'] == ""): d = args[5] elif any(x['name'] == 'dilation' for x in args): d = list(filter(lambda x : x['name'] == 'dilation', args))[0] else: d = {'name': 'dilation', 'type': 'int', 'value': 1} if (length == 7) and (args[6]['name'] == ""): g = args[6] elif any(x['name'] == 'groups' for x in args): g = list(filter(lambda x : x['name'] == 'groups', args))[0] else: g = {'name': 'groups', 'type': 'int', 'value': 1} if op == "conv1d": assert (len(i['shape']) == 3) assert (len(w['shape']) == 3) assert (i['dtype'] == w['dtype']) N, C1, W = i['shape'] K, C2, S = w['shape'] assert (C1 == C2) p = p['value'] if Utility.isscalar(p['type']) else p['value'][0] s = s['value'] if Utility.isscalar(s['type']) else s['value'][0] d = d['value'] if Utility.isscalar(d['type']) else d['value'][0] g = g['value'] assert (g == 1) H = 1 R = 1 P = 1 + (H - (((R-1))+1)) Q = 1 + (W + 2*p - (((S-1)*d)+1))/s P = int(P) Q = int(Q) if (H == 1): assert (P == 1) if (W == 1): assert (Q == 1) self.N = N self.C = C1 self.H = H self.W = W self.K = K self.P = P self.Q = Q self.R = R self.S = S self.ph = 0 self.pw = p self.U = 1 self.V = s self.dh = 1 self.dw = d self.g = g self.type = i['dtype'] elif op == "conv2d": assert (len(i['shape']) == 4) assert (len(w['shape']) == 4) assert (i['dtype'] == w['dtype']) N, C1, H, W = i['shape'] K, C2, R, S = w['shape'] if Utility.isscalar(p['type']): ph = pw = p['value'] else: assert (p['type'] == "tuple") ph, pw = p['value'] if Utility.isscalar(s['type']): sh = sw = s['value'] else: assert (s['type'] == "tuple") sh, sw = s['value'] if Utility.isscalar(d['type']): dh = dw = d['value'] else: assert (d['type'] == "tuple") dh, dw = d['value'] g = g['value'] assert (g >= 1) assert (C1 == C2*g) P = 1 + (H + 2*ph - (((R-1)*dh)+1))/sh Q = 1 + (W + 2*pw - (((S-1)*dw)+1))/sw P = int(P) Q = int(Q) if (H == 1): assert (P == 1) if (W == 1): assert (Q == 1) self.N = N self.C = C1 self.H = H self.W = W self.K = K self.P = P self.Q = Q self.R = R self.S = S self.ph = ph self.pw = pw self.U = sh self.V = sw self.dh = dh self.dw = dw self.g = g self.type = i['dtype'] else: assert False def params(self): p = OrderedDict([('N',self.N), ('C',self.C), ('H',self.H), ('W',self.W), ('K',self.K), ('P',self.P), ('Q',self.Q), ('R',self.R), ('S',self.S), ('ph',self.ph), ('pw',self.pw), ('U',self.U), ('V',self.V), ('dh',self.dh), ('dw',self.dw), ('g',self.g), ('type',self.type)]) return p def conv_bytes_flops(self, N, C, H, W, K, P, Q, R, S, g, t): f = 2*N*K*P*Q*C*R*S/g #for fprop elems = N*C*H*W + K*C*R*S/g + N*K*P*Q b = elems * Utility.typeToBytes(t) return b,f def bytes_flops(self): N,C,H,W,K,P,Q,R,S,ph,pw,U,V,dh,dw,g,t = self.params().values() if any(x in self.name for x in Conv.convAuxList+Conv.winoAuxList+Conv.fftAuxList+Conv.miscAuxList): bytes, flops = [0, 0] elif any(x in self.name for x in Conv.convList+Conv.winoList+Conv.fftList+Conv.miscList): if g == 1: bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) else: if "2d_grouped_direct_kernel" in self.name: #only 1 kernel is called bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) elif "spatialDepthwiseConvolutionUpdateOutput" in self.name: #one kernel for separable conv bytes, flops = self.conv_bytes_flops(N,C,H,W,K,P,Q,R,S,g,t) else: #a kernel per group is called bytes, flops = self.conv_bytes_flops(N,C/g,H,W,K/g,P,Q,R,S,1,t) elif ("calc_bias_diff" in self.name): #bias gradient elems = N*K*P*Q flops = elems bytes = 2 * elems * Utility.typeToBytes(t) #params = OrderedDict([('N',N), ('K',K), ('P',P), ('Q',Q), ('type', t)]) else: bytes, flops = [0, 0] return bytes, flops def bytes(self): b,_ = self.bytes_flops() return b def flops(self): _,f = self.bytes_flops() return f def tc(self): for s in ["884cudnn", "1688cudnn"]: if s in self.name: return 1 return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/convert.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Convert(OperatorLayerBase): """ Class to handle convert operations. """ ops = ["byte", "char", "double", "float", "half", "int", "long", "short", "to"] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op in Convert.ops) assert (len(args) == 1) #The argument could be a tensor or scalar t = args[0] if t['type'] == "tensor": shape = t['shape'] stype = t['dtype'] else: shape = (1,) stype = t['type'] if self.op_ == "to": op = stype self.shape = shape self.stype = stype self.dtype = op def params(self): p = OrderedDict([('T', self.shape), ('stype', self.stype), ('dtype', self.dtype)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def elems(self): return Utility.numElems(self.shape) def flops(self): return 0 def bytes(self): b = self.elems() * (Utility.typeToBytes(self.stype) + Utility.typeToBytes(self.dtype)) return b ================================================ FILE: KoSimCSE/apex/pyprof/prof/data.py ================================================ from .utility import Utility class Data(object): """ Class to store all the data for every kernel e.g. name, bytes, flops, device, stream etc. """ def __init__(self, kernel): #Available from NVprof self.tid = kernel['tid'] self.device = kernel['device'] self.stream = kernel['stream'] self.grid = str(kernel['grid']).replace(" ","").replace("(","").replace(")","") self.block = str(kernel['block']).replace(" ","").replace("(","").replace(")","") self.name = kernel['kShortName'].replace(" ","_") self.lName = kernel['kLongName'] self.sil = kernel['kDuration'] #units ns self.index = None #Markers self.argMarker = kernel['marker'] self.modMarker = kernel['reprMarkers'] self.seqMarker = kernel['seqMarker'] self.layer = kernel['layer'] self.trace = kernel['trace'] self.seqId = kernel['seqId'] self.altSeqId = kernel['altSeqId'] self.dir = kernel['dir'] self.sub = kernel['subSeqId'] self.mod = "na" self.op = "na" self.params = {"na":"na"} self.tc = "na" self.flops = 0 self.bytes = 0 def setParams(self, params): #Remove space from params qaz = "" for key,value in params.items(): if "type" not in key: qaz += "{}={},".format(key,value) else: if type(value) is str: qaz += "{},".format(Utility.typeToString(value)) else: qaz += "{}".format(value) self.params = qaz.replace(" ", "") ================================================ FILE: KoSimCSE/apex/pyprof/prof/dropout.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Dropout(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "dropout") #assert (len(args) == 1) self.shape = args[0]['shape'] self.type = args[0]['dtype'] self.dir = d.dir return def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def elems(self): return Utility.numElems(self.shape) def bytes(self): #Ignoring the cost of writing and reading the mask return Utility.typeToBytes(self.type) * self.elems() * 2 def flops(self): # Note: This is approximate and depends on the RNG return 5*self.elems() ================================================ FILE: KoSimCSE/apex/pyprof/prof/embedding.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Embedding(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "embedding") self.ishape = args[0]['shape'] self.itype = args[0]['dtype'] self.eshape = args[1]['shape'] self.etype = args[1]['dtype'] assert (len(self.eshape) == 2) self.dir = d.dir self.sub = d.sub return def params(self): p = OrderedDict([('I', self.ishape), ('itype', self.itype), ('E', self.eshape), ('etype', self.etype)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def bytes(self): ishape = self.ishape itype = self.itype eshape = self.eshape etype = self.etype ielems = Utility.numElems(ishape) b = 0 if self.dir == "fprop": #indices b += ielems * Utility.typeToBytes(itype) #read and write the embedding matrix b += ielems * eshape[1] * 2 * Utility.typeToBytes(etype) else: #3 times the size of the incoming gradient b = ielems * eshape[1] * 3 * Utility.typeToBytes(etype) if self.sub > 0: b = 0 return b def flops(self): # Note: not implemented yet return 0 ================================================ FILE: KoSimCSE/apex/pyprof/prof/index_slice_join_mutate.py ================================================ from collections import OrderedDict from .utility import Utility import numpy as np from .base import OperatorLayerBase class Cat(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") assert (op == "cat") assert (len(args) >= 2) t = args[0]['dtype'] shapes = [] for arg in args: if arg['type'] == "tensor": assert (arg['dtype'] == t) shapes.append(arg['shape']) self.type = t self.shapes = shapes def params(self): p = OrderedDict([('T', self.shapes), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): b = 0 for s in self.shapes: b += Utility.numElems(s) return 2 * b * Utility.typeToBytes(self.type) class Reshape(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "reshape") #Temporarily commenting three lines #assert (len(args) == 2) #t,s = args #assert s['type'] == "tuple" t = args[0] assert t['type'] == "tensor" self.type = t['dtype'] self.shape = t['shape'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return 0 class Gather(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") or (mod == "torch") assert (op == "gather") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 3) #Get input if (args[0]['name'] == ""): arg = args[0] else: arg = list(filter(lambda x : x['name'] == "input", args))[0] assert (arg['type'] == "tensor") self.shape = arg['shape'] self.type = arg['dtype'] def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return 2 * Utility.numElems(self.shape) * Utility.typeToBytes(self.type) class MaskedScatter(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "masked_scatter_") assert (len(args) == 3) dst, mask, src = args assert (dst['type'] == mask['type'] == src['type'] == "tensor") assert (mask['dtype'] == "uint8") assert (dst['dtype'] == src['dtype']) assert (dst['shape'] == mask['shape']) self.shape = dst['shape'] self.type = dst['dtype'] self.seqId = d.seqId def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): elems = Utility.numElems(self.shape) #src and dst b = 2 * elems * Utility.typeToBytes(self.type) #mask (uint8) b += elems if (self.seqId > 0): b = 0 return b class Nonzero(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "nonzero") assert (len(args) == 1) arg = args[0] self.shape = arg['shape'] self.type = arg['dtype'] self.seqId = d.seqId def params(self): p = OrderedDict([('T', self.shape),('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): elems = Utility.numElems(self.shape) dim = len(self.shape) #input tensor b = elems * Utility.typeToBytes(self.type) #in the worst case, the output is a (elems x dim) tensor of type "long" b += elems * dim * Utility.typeToBytes("int64") if self.seqId > 0: return 0 else: return b class IndexSelect(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") or (mod == "torch") assert (op == "index_select") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 3) #Get input, dim and index if (args[0]['name'] == ""): t = args[0] else: t = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): d = args[1] else: d = list(filter(lambda x : x['name'] == "dim", args))[0] if (args[2]['name'] == ""): i = args[2] else: i = list(filter(lambda x : x['name'] == "index", args))[0] assert (t['type'] == i['type'] == "tensor") assert (d['type'] == "int") assert (i['dtype'] == "int64") assert (len(i['shape']) == 1) shape = t['shape'] dim = d['value'] indices = i['shape'][0] assert (dim < len(shape)) self.shape = shape self.dim = dim self.indices = indices self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape),('D', self.dim),('I', self.indices),('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def bytes(self): #determine the shape of the output tensor shape = list(self.shape) shape[self.dim] = self.indices b = 0 #time to read the input and write the output elems = Utility.numElems(shape) b += 2 * elems * Utility.typeToBytes(self.type) #time to read the indices b += self.indices * Utility.typeToBytes("int64") return b class MaskedSelect(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.sub = d.sub assert (mod == "Tensor") or (mod == "torch") assert (op == "masked_select") #Filter out the "out" parameter args = list(filter(lambda x : x['name'] != 'out', args)) assert (len(args) == 2) #Get input and mask if (args[0]['name'] == ""): t = args[0] else: t = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): m = args[1] else: m = list(filter(lambda x : x['name'] == "mask", args))[0] assert (m['dtype'] == "uint8") tensor = t['shape'] mask = m['shape'] #check for broadcast condition if (tensor != mask): array1 = np.empty(list(tensor)) array2 = np.empty(list(mask)) try: out = np.broadcast(array1, array2).shape except: assert False self.tshape = tensor self.mshape = mask self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.tshape),('M', self.mshape),('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): tensor = self.tshape mask = self.mshape t = self.type #in the worst case, #output elements = #input elements b = 2 * Utility.numElems(tensor) * Utility.typeToBytes(t) #mask tensor (assuming uint8) b += Utility.numElems(mask) return b def flops(self): return 0 ================================================ FILE: KoSimCSE/apex/pyprof/prof/linear.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Linear(OperatorLayerBase): ''' Notes: If the bias occurs before the GEMM, then its 1 write (bias expansion). If the bias occurs after, then its 1 read and 1 write. bias in bprop is a reduction and hence is 1 read. ''' gemmKernels = ["gemm", "gemv", "dot_kernel", "splitKreduce_kernel", "reduce_1Block_kernel"] biasKernels = ["kernelReduceContigDim", "kernelReduceNoncontigDim_shared", "elementwise_kernel", "reduce_kernel"] def setXWBMNK(self, args): x = None w = None b = None if (len(args) == 2): x,w = args elif (len(args) == 3): x,w,b = args assert (x['type'] == w['type'] == "tensor") if (b['type'] == "tensor"): assert(len(b['shape']) == 1) elif (b['type'] == "NoneType"): assert b['value'] is None b = None else: assert False else: assert False assert(len(w['shape']) == 2) k1 = x['shape'][-1] n,k2 = w['shape'] assert(k1 == k2) if b is not None: assert(b['shape'][0] == n) t1 = x['dtype'] t2 = w['dtype'] assert(t1 == t2) # X, W, B self.x = x['shape'] self.w = w['shape'] self.b = b['shape'] if b is not None else None self.type = t1 # M, N, K #n = Utility.numElems(x[0:-1]) n = self.x[0:-1] k = self.x[-1] m,k1 = self.w assert (k == k1) self.m = m self.n = n self.k = k def tc(self): if self.op() == "linear": return 1 if "884gemm" in self.name else 0 else: return "-" def __init__(self, d): self.name = d.name self.dir = d.dir self.sub = d.sub marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "torch.nn.functional") assert (op == "linear") self.setXWBMNK(args) if any(x in d.name for x in Linear.gemmKernels): self.op_ = "linear" else: assert (d.name in Linear.biasKernels) self.op_ = "bias" ''' elif (("kernelPointwiseApply2" in d.name) or ("kernelReduceContigDim" in d.name) or ("kernelReduceNoncontigDim_shared" in d.name)): #bias expansion was before the gemm self.op_ = "bias" elif ("elementwise_kernel" in d.name): #Bias addition happens later with a broadcast tensor self.op_ = "bias" assert (len(d.argMarker) == 2) marker = eval(d.argMarker[1]) mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "Tensor") assert (op == "__iadd__") assert (len(args) == 2) mn = args[0]['shape'] b = args[1]['shape'] assert (len(b) == 1) assert (mn == (self.n + (self.m,))) assert (b == self.b) else: assert False ''' def params(self): #p = OrderedDict([('X', self.x), ('W', self.w), ('B', self.b), ('type', self.type)]) m, n, k, x, w, t = self.m, self.n, self.k, self.x, self.w, self.type if len(n) == 1: n = n[0] if self.op_ == "linear": if self.dir == "fprop": p = OrderedDict([('M', m), ('N', n), ('K', k), ('type', t)]) elif self.dir == "bprop": if self.sub == 0: #dgrad (most likely) p = OrderedDict([('M', k), ('N', n), ('K', m), ('type', t)]) elif self.sub == 1: #wgrad (most likely) p = OrderedDict([('M', k), ('N', m), ('K', n), ('type', t)]) else: #This happens when there are additional kernels for reduction p = OrderedDict([('X', x), ('W', w), ('type', t)]) else: assert False elif self.op_ == "bias": p = OrderedDict([('M', m), ('N', n), ('type', t)]) else: assert False return p def op(self): return self.op_ def bytesFlops(self): m = self.m n = Utility.numElems(self.n) k = self.k if self.op_ == "linear": if self.dir == "fprop": f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) elif self.dir == "bprop": if self.sub == 0: #dgrad (most likely) f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) elif self.sub == 1: #wgrad (most likely) f = m * n * k * 2 b = m*n + m*k + n*k * Utility.typeToBytes(self.type) else: #This happens when there are additional kernels for reduction f = 0 b = 0 else: assert False elif self.op_ == "bias": f = m * n b = 2 * m * n * Utility.typeToBytes(self.type) else: assert False return b,f def bytes(self): b, f = self.bytesFlops() return b def flops(self): b, f = self.bytesFlops() return f def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/loss.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase #TODO: Add support for additional loss functions. class MSELoss(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "mse_loss") assert (len(args) == 3) #Get input, target and reduction if (args[0]['name'] == ""): x = args[0] else: x = list(filter(lambda x : x['name'] == "input", args))[0] if (args[1]['name'] == ""): y = args[1] else: y = list(filter(lambda x : x['name'] == "target", args))[0] if (args[2]['name'] == ""): r = args[2] else: r = list(filter(lambda x : x['name'] == "reduction", args))[0] assert (x['type'] == y['type'] == "tensor") assert (x['shape'] == y['shape']) assert (x['dtype'] == y['dtype']) assert (r['type'] == "str") assert (r['value'] in ["none", "mean", "sum"]) self.shape = x['shape'] self.type = x['dtype'] self.red = r['value'] self.dir = d.dir def params(self): p = OrderedDict([('T', self.shape), ('type', self.type), ('red', self.red)]) return p def elems(self): red = self.red e = Utility.numElems(self.shape) if self.dir == "fprop": if red == "none": e *= 3 else: e *= 2 else: if red == "none": e *= 4 else: e *= 3 return e def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): return self.elems() * 2 + 1 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/misc.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Foo(OperatorLayerBase): """ An object of Foo is instantiated when we detect an unsupported operator. """ def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args shapes = [] types = [] for arg in args: if arg['type'] == "tensor": shapes.append(arg['shape']) types.append(arg['dtype']) self.shape = shapes self.type = types def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def bytes(self): return 0 class Copy(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "copy_") assert (len(args) == 2) dst, src = args assert (src['type'] == dst['type']) assert (src['shape'] == dst['shape']) self.shape = src['shape'] self.stype = src['dtype'] self.dtype = dst['dtype'] def params(self): #The data type might be different p = OrderedDict([('T', self.shape), ('stype', self.stype), ('dtype', self.dtype)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def flops(self): return 0 def elems(self): return Utility.numElems(self.shape) def bytes(self): return self.elems() * (Utility.typeToBytes(self.stype) + Utility.typeToBytes(self.dtype)) class Clone(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "clone") assert (len(args) == 1) t = args[0] self.shape = t['shape'] self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def bytes(self): return 2 * self.elems() * Utility.typeToBytes(self.type) class Contiguous(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "contiguous") assert (len(args) == 1) t = args[0] self.shape = t['shape'] self.type = t['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def flops(self): return 0 def bytes(self): return 2 * Utility.numElems(self.shape) * Utility.typeToBytes(self.type) def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ class Any(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "Tensor") assert (op == "any") assert (len(args) == 1) #could be 2 as well, the second argument is a bool t = args[0] self.shape = t['shape'] self.type = t['dtype'] self.sub = d.sub return def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def flops(self): return 0 def bytes(self): return Utility.numElems(self.shape) * Utility.typeToBytes(self.type) ================================================ FILE: KoSimCSE/apex/pyprof/prof/normalization.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class BatchNorm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (op == "batch_norm") assert (len(args) == 8) i = args[0] assert (i['type'] == "tensor") self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def flops(self): # Variance algo-dependent, but this is a reasonable value. return self.elems() * 8 def bytes(self): e = self.elems() if self.dir == "fprop": e *= 4 else: e *= 5 return e * Utility.typeToBytes(self.type) ================================================ FILE: KoSimCSE/apex/pyprof/prof/optim.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase #TODO: Add support for other optimizers. class Adam(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert(op == "adam") assert (len(args) == 12) or (len(args) == 14) w, hw, m, v, g = args[0:5] assert (w['shape'] == m['shape'] == v['shape'] == g['shape']) assert (hw['shape'] == w['shape']) or (hw['shape'] == (0,)) #hw could be null assert (w['type'] == m['type'] == v['type'] == g['type'] == hw['type'] == "tensor") assert (w['dtype'] == m['dtype'] == v['dtype'] == "float32") self.w = w self.g = g def params(self): p = OrderedDict([('T',self.w['shape']), ('wtype',self.w['dtype']), ('gtype',self.g['dtype'])]) return p def flops(self): return 0 def bytes(self): wshape = self.w['shape'] wtype = self.w['dtype'] gtype = self.g['dtype'] b = 0 elems = Utility.numElems(wshape) #Get time to stream read/write w, m, v b += 6 * elems * Utility.typeToBytes(wtype) #Get time to read "g" b += elems * Utility.typeToBytes(gtype) if wtype != gtype: #mixed precision #Get time to write "hw b += elems * Utility.typeToBytes(gtype) return b def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/output.py ================================================ import errno, os, sys class Output(): """ This class handles printing of a columed output and a CSV. """ # The table below is organized as # user_option: [output_header, attribute_in_Data_class, type, min_width_in_columed_output] table = { "idx": ["Idx", "index", int, 7], "seq": ["SeqId", "seqId", str, 7], "altseq": ["AltSeqId", "altSeqId", str, 7], "tid": ["TId", "tid", int, 12], "layer": ["Layer", "layer", str, 10], "trace": ["Trace", "trace", str, 25], "dir": ["Direction", "dir", str, 5], "sub": ["Sub", "sub", int, 3], "mod": ["Module", "mod", str, 15], "op": ["Op", "op", str, 15], "kernel": ["Kernel", "name", str, 0], "params": ["Params", "params", str, 0], "sil": ["Sil(ns)", "sil", int, 10], "tc": ["TC", "tc", str, 2], "device": ["Device", "device", int, 3], "stream": ["Stream", "stream", int, 3], "grid": ["Grid", "grid", str, 12], "block": ["Block", "block", str, 12], "flops": ["FLOPs", "flops", int, 12], "bytes": ["Bytes", "bytes", int, 12] } def __init__(self, args): self.cols = args.c self.csv = args.csv self.col = True if (args.w > 0) else False self.width = args.w w = 0 for col in self.cols: assert col in Output.table.keys() w += Output.table[col][3] if ((self.col) and (w > self.width)): print("Minimum width required to print {} = {}. Exiting.".format(",".join(self.cols), w)) sys.exit(1) remainder = self.width - w if ("kernel" in self.cols) and ("params" in self.cols): Output.table["kernel"][3] = int(remainder/2) Output.table["params"][3] = int(remainder/2) elif ("kernel" in self.cols): Output.table["kernel"][3] = remainder elif ("params" in self.cols): Output.table["params"][3] = remainder #header format cadena = "" for col in self.cols: _,_,t,w = Output.table[col] cadena += "%-{}.{}s ".format(w,w) self.hFormat = cadena #data format cadena = "" for col in self.cols: _,_,t,w = Output.table[col] if (t == str): cadena += "%-{}.{}s ".format(w,w) elif (t == int): cadena += "%{}d ".format(w) self.dFormat = cadena def foo(self, cadena, pformat): if self.csv: cadena = ",".join(map(lambda x : '"' + str(x) + '"', cadena)) elif self.col: cadena = pformat % cadena else: cadena = " ".join(map(str,cadena)) try: print(cadena) except IOError as e: #gracefully handle pipes if e.errno == errno.EPIPE: # Python flushes standard streams on exit; redirect remaining output # to devnull to avoid another BrokenPipeError at shutdown devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) sys.exit(0) else: sys.exit(-1) def header(self): cadena = () for col in self.cols: h = Output.table[col][0] cadena = cadena + (h,) self.foo(cadena, self.hFormat) def data(self, a): if a.dir == "": direc = "na" else: direc = a.dir if a.op == "": op = "na" else: op = a.op if a.mod == "": mod = "na" else: mod = a.mod cadena = () for col in self.cols: attr = Output.table[col][1] val = getattr(a, attr) if col == "layer": assert(type(val) == list) val = ":".join(val) val = "-" if val == "" else val if col == "trace": assert(type(val) == list) if self.col and len(val): val = val[-1] val = val.split("/")[-1] else: val = ",".join(val) val = "-" if val == "" else val if col in ["seq", "altseq"]: assert(type(val) == list) val = ",".join(map(str,val)) val = "-" if val == "" else val cadena = cadena + (val,) self.foo(cadena, self.dFormat) ================================================ FILE: KoSimCSE/apex/pyprof/prof/pointwise.py ================================================ import numpy as np from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Pointwise(OperatorLayerBase): ops = [] ops += ["__abs__", "__neg__", "__invert__"] ops += ["__add__", "__sub__", "__mul__", "__floordiv__", "__truediv__", "__pow__", "__mod__"] ops += ["__radd__", "__rsub__", "__rmul__", "__rdiv__", "__rtruediv__", "__rfloordiv__", "__rpow__"] ops += ["__iadd__", "__isub__", "__imul__", "__itruediv__",] ops += ["__lt__", "__gt__", "__ge__", "__le__", "__eq__", "__ne__",] ops += ["lt", "lt_", "gt", "gt_", "ge", "ge_", "le", "le_", "eq", "eq_", "ne", "ne_",] ops += ["__and__", "__or__", "__xor__", "__lshift__", "__rshift__"] ops += ["__iand__", "__ior__", "__ixor__", "__ilshift__", "__irshift__"] ops += ["abs", "abs_", "neg", "neg_"] ops += ["add", "add_", "div", "div_", "mul", "mul_", "reciprocal", "reciprocal_", "remainder", "remainder_", "sub", "sub_",] ops += ["addcdiv", "addcdiv_", "addcmul", "addcmul_"] ops += ["exp", "exp_", "exp1m", "exp1m_", "log", "log_", "log10", "log10_", "log1p", "log1p_", "log2", "log2_", "pow", "pow_", "rsqrt", "rsqrt_", "sqrt", "sqrt_",] ops += ["ceil", "ceil_", "clamp", "clamp_", "floor", "floor_", "fmod", "fmod_", "frac", "frac_", "round", "round_", "sign", "sign_", "trunc", "trunc_"] ops += ["acos", "acos_", "asin", "asin_", "atan", "atan_", "atan2", "atan2_", "cos", "cos_", "cosh", "cosh_", "sin", "sin_", "sinh", "sinh_", "tan", "tan_", "sigmoid", "sigmoid_", "tanh", "tanh_"] ops += ["digamma", "erf", "erf_", "erfc", "erfc_", "erfinv", "erfinv_", "lerp", "lerp_", "mvlgamma",] @staticmethod def foo(d): return d['name'],d['type'],d['shape'],d['dtype'] def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.dir = d.dir assert (d.dir in ["fprop", "bprop"]) assert (op in Pointwise.ops) #Filter out all named parameters (kwargs). #This might require revisiting in future. args = list(filter(lambda x : x['name'] == "", args)) #Filter out non tensors args = list(filter(lambda x : x['type'] == "tensor", args)) if (len(args) == 0): self.shape = [(1,)] self.type = "float32" #FIX elif (len(args) == 1): in0 = args[0] _,t0,s0,dt0 = Pointwise.foo(in0) assert (t0 == "tensor") self.shape = [s0,] self.type = dt0 elif (len(args) == 2): in0,in1 = args _,t0,s0,dt0 = Pointwise.foo(in0) _,t1,s1,dt1 = Pointwise.foo(in1) assert (t0 == t1 == "tensor") assert (dt0 == dt1) self.shape = [s0,s1] self.type = dt0 elif (len(args) == 3): in0,in1,in2 = args _,t0,s0,dt0 = Pointwise.foo(in0) _,t1,s1,dt1 = Pointwise.foo(in1) _,t2,s2,dt2 = Pointwise.foo(in2) assert (t0 == t1 == t2 == "tensor") assert (dt0 == dt1 == dt2) self.shape = [s0,s1,s2] self.type = dt0 else: assert False return def params(self): p = OrderedDict([('T',self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): tensor = self.shape t = self.type if (len(tensor) == 1): elems = 2 * Utility.numElems(tensor[0]) elif (len(tensor) == 2): if (tensor[0] == tensor[1]): # same shape elems = Utility.numElems(tensor[0]) if self.dir == "fprop": elems *= 3 else: if (self.op_ in ["add", "__add__", "sub", "__sub__", "__isub__"]): elems *= 2 elif (self.op_ in ["__mul__", "__rmul__", "div", "__truediv__"]): elems *= 3 else: assert False else: #check for broadcast conditions array1 = np.empty(list(tensor[0])) array2 = np.empty(list(tensor[1])) try: out = np.broadcast(array1, array2).shape except: assert False elems = Utility.numElems(tensor[0]) elems += Utility.numElems(tensor[1]) elems += Utility.numElems(out) #TODO bprop elif (len(tensor) == 3): if (tensor[0] == tensor[1] == tensor[2]): #same shape elems = Utility.numElems(tensor[0]) elems *= 4 else: assert False else: assert False return elems def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): # Note: some cases may still be missing. f = 0 if self.op_ in ["__abs__", "__neg__", "__add__", "__sub__", "__mul__", "__radd__", "__rmul__", "__iadd__", "__isub__", "__imul__", "__itruediv__", "abs", "abs_", "neg", "neg_", "add", "add_", "div", "div_", "mul", "mul_", "sub", "sub_", "exp", "exp_", "sign", "sign_", "trunc", "trunc_", "sin", "sin_", "cos", "cos_", "sinh", "sinh_", "cosh", "cosh_", "sqrt", "sqrt_", "rsqrt", "rsqrt_", "__lt__", "__gt__", "__ge__", "__le__", "__eq__", "__ne__", "lt", "lt_", "gt", "gt_", "ge", "ge_", "le", "le_", "eq", "eq_", "ne", "ne_", "ceil", "ceil_", "clamp", "clamp_", "floor", "floor_", "round", "sign", "sign_", "trunc", "trunc_"]: # We're counting only one operand, not two (2 operands, 1 op) f = self.elems() / 2 elif self.op_ in ["fmod", "fmod_"]: f = self.elems() elif self.op_ in ["tanh", "tanh_", "sigmoid", "sigmoid_", "log", "log_", "log2", "log2_", "log10", "log10_"]: f = self.elems() * 2 elif self.op_ in ["asin", "asin_", "acos", "acos_", "atan", "atan_"]: # no intrinsic, hence slow execution # surprisingly, asin/acos and atan were all the same (via nvprof measurement) f = self.elems() * 10 return f ================================================ FILE: KoSimCSE/apex/pyprof/prof/pooling.py ================================================ from .collections import OrderedDict from .utility import Utility # Work in progress. #poolFuncs = ["max_pool2d_with_indices_forward", "max_pool2d_with_indices"] class MaxPool2d(object): def parse(marker): def convert2Tuple(arg): assert (arg['type'] in ["int", "tuple"]) if arg['type'] == "int": return (arg['value'], arg['value']) else: return arg['value'] mod = marker['mod'] op = marker['op'] args = marker['args'] assert (mod == "torch.nn.functional") assert (op == "max_pool2d") assert (len(args) >= 2) #input assert (args[0]['name'] == "") inp = args[0] assert (inp['type'] == "tensor") i = inp['shape'] t = inp['dtype'] assert (len(i) == 4) #nchw tensor #kernel if (args[1]['name'] == ""): k = args[1] else: k = list(filter(lambda x : x['name'] == "kernel_size", args))[0] k = convert2Tuple(k) #stride s = k #default value if ((len(args) >= 3) and args[2] == ""): s = args[2] s = convert2Tuple(s) elif any(x['name'] == "stride" for x in args): s = list(filter(lambda x : x['name'] == "stride", args))[0] s = convert2Tuple(s) #padding p = (0,0) if ((len(args) >= 4) and args[3] == ""): p = args[3] p = convert2Tuple(p) elif any(x['name'] == "padding" for x in args): p = list(filter(lambda x : x['name'] == "padding", args))[0] p = convert2Tuple(p) params = OrderedDict([('T', i), ('K', k), ('s',s), ('p',p), ('type', t)]) return params ================================================ FILE: KoSimCSE/apex/pyprof/prof/prof.py ================================================ #!/usr/bin/env python3 """ This script reads the output (Python dictionary) created by parse.py. For every kernel (line) in the input it determines module / class name e.g. torch.nn.functional operator name e.g. linear kernel parameters e.g. GEMM M, N, K, datatype bytes flops tensor core usage direction (fprop, bprop) and other things. Please see the tool usage. """ from .usage import parseArgs from .output import Output from .utility import Utility from .pointwise import Pointwise from .convert import Convert from .blas import * from .embedding import Embedding from .reduction import * from .dropout import Dropout from .softmax import * #from pooling import * # work in progress from .linear import Linear from .optim import Adam from .misc import * from .conv import Conv from .activation import Activation from .index_slice_join_mutate import Cat, Reshape, MaskedScatter, Gather, Nonzero, IndexSelect, MaskedSelect from .recurrentCell import RNNCell from .normalization import BatchNorm from .randomSample import RandPerm from .loss import MSELoss from .data import Data def findFpropKernel(seq): #Find the last fprop kernel with the same seqId #First look at seqId and then at altSeqId for idx in reversed(range(len(kernels))): k = kernels[idx] if (seq in k['seqId']) and (k['dir'] == "fprop"): return idx for idx in reversed(range(len(kernels))): k = kernels[idx] if (seq in k['altSeqId']) and (k['dir'] == "fprop"): return idx return -1 #print("Error: seqId {} not found.".format(seq), file=sys.stderr) #assert False def foo(mod, op, d): if (op[0] == "linear"): xx = Linear(d) # rnncell, lstmcell, grucell elif (mod[0] in["LSTMCell", "GRUCell"]) and (op[0] == "forward"): xx = RNNCell(d) elif op[0] in ["conv1d", "conv2d",]: xx = Conv(d) elif (op[0] in Pointwise.ops): xx = Pointwise(d) elif (op[0] in Convert.ops): xx = Convert(d) elif op[0] in ["__matmul__", "matmul"]: xx = Matmul(d) elif op[0] == "embedding": xx = Embedding(d) #reduction elif op[0] == "sum": xx = Sum(d) elif op[0] == "mean": xx = Mean(d) elif op[0] == "norm": xx = Norm(d) elif op[0] == "dropout": xx = Dropout(d) #Index, Slice, Join, Mutate elif (op[0] == "cat"): xx = Cat(d) elif (op[0] == "reshape"): xx = Reshape(d) elif (op[0] == "masked_scatter_"): xx = MaskedScatter(d) elif (op[0] == "gather"): xx = Gather(d) elif (op[0] == "nonzero"): xx = Nonzero(d) elif (op[0] == "index_select"): xx = IndexSelect(d) elif (op[0] == "masked_select"): xx = MaskedSelect(d) #blas elif op[0] in ["addmm", "addmm_"]: xx = Addmm(d) elif op[0] == "mm": xx = Mm(d) elif op[0] == "bmm": xx = Bmm(d) #softmax elif op[0] == "softmax": xx = Softmax(d) elif op[0] == "log_softmax": xx = LogSoftmax(d) #loss elif op[0] == "mse_loss": xx = MSELoss(d) #optimizers elif op[0] == "adam": xx = Adam(d) #normalization elif op[0] == "batch_norm": xx = BatchNorm(d) #random elif op[0] == "randperm": xx = RandPerm(d) #misc elif op[0] == "copy_": xx = Copy(d) elif op[0] == "clone": xx = Clone(d) elif op[0] == "contiguous": xx = Contiguous(d) elif op[0] == "any": xx = Any(d) elif (op[0] in Activation.ops): xx = Activation(d) elif op[0] == "to": xx = Convert(d) else: xx = Foo(d) return xx def main(): #Read cmd line arguments cmdArgs = parseArgs() output = Output(cmdArgs) output.header() idx = -1 #Read in all the kernel info for line in cmdArgs.file: idx += 1 kernel = eval(line) assert(kernel) kernels.append(kernel) k = kernel d = Data(k) mod = k['mod'] op = k['op'] flops = 0 params = {"na":"na"} tc = "na" bytes = 0 if (d.dir == "bprop"): d.seqMarker = k['seqMarker'] seq = k['seqId'] if len(seq) > 1: pass seq = k['seqId'][:1] assert (len(seq) == 1), seq #assert (seq[0] != 0) assert (len(d.seqMarker) > 0) #If there is no useful marker associated, use the #sequence number to find the kernel from fprop if len(d.argMarker) == 0: index = findFpropKernel(seq[0]) if index >= 0: d.argMarker = kernels[index]['marker'] d.modMarker = kernels[index]['reprMarkers'] mod = kernels[index]['mod'] op = kernels[index]['op'] d.layer = kernels[index]['layer'] d.trace = kernels[index]['trace'] # Check if marker has our annotations if len(d.argMarker) and Utility.hasNVTX(d.argMarker[0]): xx = foo(mod, op, d) bytes = xx.bytes() flops = xx.flops() op = xx.op() params = xx.params() tc = xx.tc() if type(op) is list: if len(op): op = op[0] else: op = "" if type(mod) is list: if len(mod): mod = mod[0] else: mod = "" d.index = idx+1 # The following 8 come from operator class functions. d.setParams(params) d.tc = tc d.flops = flops d.bytes = bytes d.mod = mod d.op = op output.data(d) kernels = [] if __name__ == '__main__': main() ================================================ FILE: KoSimCSE/apex/pyprof/prof/randomSample.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class RandPerm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch") assert (op == "randperm") assert (len(args) == 1) n = args[0] assert n['type'] == "int" self.n = n['value'] def params(self): p = OrderedDict([('N', self.n)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): return self.n * Utility.typeToBytes("int64") def flops(self): # Depends on RNG but this is probably a reasonable assumption. return self.n * 3 ================================================ FILE: KoSimCSE/apex/pyprof/prof/recurrentCell.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase def hasTileSize(name): if ("sgemm" in name) or ("884gemm" in name) or ("hgemm" in name): return True else: return False def ctaTile(name): name = name.split("_") name = list(filter(lambda x : "x" in x, name)) name = list(filter(lambda x : "slice" not in x, name)) assert(len(name) == 1) name = name[0].split("x") assert(len(name) == 2) name = list(map(int, name)) return name[0], name[1] class RNNCell(OperatorLayerBase): """ This class supports RNNCell, LSTMCell and GRUCell. """ def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args self.name = d.name self.dir = d.dir self.sub = d.sub self.grid = d.grid assert (op == "forward") assert (mod in ["LSTMCell", "GRUCell", "RNNCell"]) assert (len(args) in [2,3]) x,h = args[0],args[1] b1,ii = x['shape'] b2,hh = h['shape'] assert b1 == b2 assert x['dtype'] == h['dtype'] t = x['dtype'] self.cell = mod self.inp = ii self.hid = hh self.b = b1 self.type = t self.multiple = 1 if self.cell == "LSTMCell": self.multiple = 4 elif self.cell == "GRUCell": self.multiple = 3 self.gemm = None self.m = None self.n = None self.k = None self.elems = 0 self.bar() def params(self): if self.gemm is None: p = OrderedDict([('cell', self.cell), ('X', self.inp), ('H', self.hid), ('B', self.b), ('type', self.type)]) else: assert self.m is not None assert self.n is not None assert self.k is not None p = OrderedDict([('gemm', self.gemm), ('M', self.m), ('N', self.n), ('K', self.k), ('type', self.type)]) return p def tc(self): if "gemm" in self.name: return 1 if "884gemm" in self.name else 0 else: return "-" def op(self): return self.op_ def mod(self): return self.mod_ def bytes(self): if self.gemm is not None: m, n, k, t = self.m, self.n, self.k, self.type b = (m*k + k*n + m*n) * Utility.typeToBytes(t) elif self.elems != 0: b = self.elems * Utility.typeToBytes(self.type) else: b = 0 return b def flops(self): if self.gemm is not None: m, n, k = self.m, self.n, self.k f = 2*m*n*k elif self.elems != 0: f = 0 #TODO else: f = 0 return f def bar(self): cell = self.cell X = self.inp H = self.hid B = self.b t = self.type subseqId = self.sub direc = self.dir name = self.name grid = self.grid multiple = self.multiple if direc == "fprop": subseqId = subseqId % 3 if subseqId == 0: #layer gemm self.gemm = "layer" self.m = multiple*H self.n = B self.k = X elif subseqId == 1: #recurrent gemm self.gemm = "recur" self.m = multiple*H self.n = B self.k = H else: layerGemmElems = multiple*H*B recurGemmElems = multiple*H*B cElems = H*B hElems = H*B totElems = layerGemmElems + recurGemmElems + 2*cElems + hElems self.elems = totElems else: if ("gemm" in name) and hasTileSize(name): #gemm #Get cta tile size tileX, tileY = ctaTile(name) #Get grid dimensions grid = grid.split(",") gridX,gridY,gridZ = map(lambda x : int(x), grid) gemmM = tileX * gridX gemmN = tileY * gridY if name[-3:] == "_nn": # dgrad if (gemmM == H): # recurrent dgrad #Ideally gemmN = B, but we have a limited set of tile sizes. gemmN = B gemmK = multiple*H self.gemm = "recur" self.m = gemmM self.n = gemmN self.k = gemmK elif (gemmM == X): # layer dgrad #assert(gemmN % B == 0) gemmK = multiple*H self.gemm = "layer" self.m = gemmM self.n = gemmN self.k = gemmK else: pass elif name[-3:] == "_nt": #wgrad if (gemmM == H): #recurrent wgrad assert (gemmN == multiple*H) gemmK = B self.gemm = "recur" self.m = gemmM self.n = gemmN self.k = gemmK elif (gemmM == X): #layer wgrad assert (gemmN == multiple*H) gemmK = B self.gemm = "layer" self.m = gemmM self.n = gemmN self.k = gemmK else: pass else: pass else: pass return ================================================ FILE: KoSimCSE/apex/pyprof/prof/reduction.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Mean(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "mean") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) i = args[0] self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir self.sub = d.sub def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def bytes(self): if self.sub == 0: return self.elems() * Utility.typeToBytes(self.type) else: return 0 def flops(self): if self.sub == 0: return self.elems() + 1 else: return 0 class Sum(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "sum") assert (len(args) >= 1) #Get input if (args[0]['name'] == ""): i = args[0] else: i = list(filter(lambda x : x['name'] == "input", args))[0] self.shape = i['shape'] self.type = i['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: This is incorrect, need to calculate actual flops (say via nvprof) return self.elems() def bytes(self): return self.elems() * Utility.typeToBytes(self.type) class Norm(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod in ["torch", "Tensor"]) assert (op == "norm") #assert (len(args) == 1) i = args[0] self.shape = i['shape'] self.type = i['dtype'] def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def bytes(self): return self.elems() * Utility.typeToBytes(self.type) def flops(self): # square and add plus sqrt return 2 * self.elems() + 1 def tc(self): return "-" def op(self): return self.op_ def mod(self): return self.mod_ ================================================ FILE: KoSimCSE/apex/pyprof/prof/softmax.py ================================================ from collections import OrderedDict from .utility import Utility from .base import OperatorLayerBase class Softmax(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "softmax") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) self.shape = args[0]['shape'] self.type = args[0]['dtype'] self.dir = d.dir return def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: exp, sum-reduce, divide #flops = elems * 3 return 0 def bytes(self): b = self.elems() * Utility.typeToBytes(self.type) b *= 3 if self.dir == "fprop" else 5 #verify return b class LogSoftmax(OperatorLayerBase): def __init__(self, d): marker = eval(d.argMarker[0]) mod = marker['mod'] op = marker['op'] args = marker['args'] self.marker = marker self.mod_ = mod self.op_ = op self.args = args assert (mod == "torch.nn.functional") assert (op == "log_softmax") #Filter out named parameters args = list(filter(lambda x : x['name'] == '', args)) assert (len(args) <= 2) #Get input if (args[0]['name'] == ""): i = args[0] else: i = list(filter(lambda x : x['name'] == "input", args))[0] t = i['dtype'] self.shape = i['shape'] self.type = i['dtype'] self.dir = d.dir return def op(self): return self.op_ def mod(self): return self.mod_ def tc(self): return "-" def params(self): p = OrderedDict([('T', self.shape), ('type', self.type)]) return p def elems(self): return Utility.numElems(self.shape) def flops(self): # Note: exp, sum-reduce, divide, log #flops = elems * 4 return 0 def bytes(self): b = self.elems() * Utility.typeToBytes(self.type) b *= 3 if self.dir == "fprop" else 5 #verify return b ================================================ FILE: KoSimCSE/apex/pyprof/prof/usage.py ================================================ import sys import argparse def parseArgs(): """ Print usage and parse arguments. """ def check_cols(value): valid = ["idx", "seq", "altseq", "tid", "layer", "trace", "dir", "sub", "mod", "op", "kernel", "params", "sil", "tc", "device", "stream", "grid", "block", "flops", "bytes"] cols = value.split(",") for col in cols: if col not in valid: raise argparse.ArgumentTypeError("{} is not a valid column name. Valid column names are {}.".format(col, ",".join(valid))) return cols def openFile(f): try: d = open(f, "r") return d except IOError: print("Error opening file {}. Exiting.".format(f), file=sys.stderr) sys.exit(1) parser = argparse.ArgumentParser(prog=sys.argv[0], description="PyTorch Profiler", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("file", nargs='?', type=str, default=None, help="Output of parse.py (Python dictionary).") parser.add_argument("-c", type=check_cols, default="idx,dir,sub,mod,op,kernel,params,sil", help='''Comma seperated names of columns to print. idx: Index seq: PyTorch Sequence Id altseq: PyTorch Alternate Sequence Id tid: Thread Id layer: User annotated NVTX string (can be nested) trace: Function Call Trace dir: Direction sub: Sub Sequence Id mod: Module op: Operattion kernel: Kernel Name params: Parameters sil: Silicon Time (in ns) tc: Tensor Core Usage device: GPU Device Id stream: Stream Id grid: Grid Dimensions block: Block Dimensions flops: Floating point ops (FMA = 2 FLOPs) bytes: Number of bytes in and out of DRAM e.g. -c idx,kernel,sil''') group = parser.add_mutually_exclusive_group() group.add_argument("--csv", action="store_true", default=False, help="Print a CSV output.") group.add_argument("-w", type=int, default=0, help="Width of columnated output.") args = parser.parse_args() if args.file is None: args.file = sys.stdin else: args.file = openFile(args.file) return args ================================================ FILE: KoSimCSE/apex/pyprof/prof/utility.py ================================================ from functools import reduce class Utility(object): @staticmethod def numElems(shape): assert (type(shape) == tuple) return reduce(lambda x,y: x*y, shape, 1) @staticmethod def typeToBytes(t): if (t in ["uint8", "int8", "byte", "char", "bool"]): return 1 elif (t in ["float16", "half", "int16", "short"]): return 2 elif (t in ["float32", "float", "int32", "int"]): return 4 elif (t in ["int64", "long", "float64", "double"]): return 8 assert False @staticmethod def typeToString(t): if (t in ["uint8", "byte", "char",]): return "uint8" elif (t in ["int8",]): return "int8" elif (t in ["int16", "short",]): return "int16" elif (t in ["float16", "half"]): return "fp16" elif (t in ["float32", "float"]): return "fp32" elif (t in ["int32", "int",]): return "int32" elif (t in ["int64", "long"]): return "int64" elif (t in ["float64", "double",]): return "fp64" elif (t in ["bool",]): return "bool" assert False @staticmethod def hasNVTX(marker): if type(marker) is str: try: marker = eval(marker) except: return False if type(marker) is dict: keys = marker.keys() return ("mod" in keys) and ("op" in keys) and ("args" in keys) else: return False @staticmethod def isscalar(t): return (t in ["float", "int"]) ================================================ FILE: KoSimCSE/apex/reparameterization/README.md ================================================ Under construction... ================================================ FILE: KoSimCSE/apex/reparameterization/__init__.py ================================================ from .weight_norm import WeightNorm from .reparameterization import Reparameterization def apply_weight_norm(module, name='', dim=0, hook_child=True): r""" Applies weight normalization to a parameter in the given module. If no parameter is provided, applies weight normalization to all parameters in model (except 1-d vectors and scalars). .. math:: \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|} Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by `name` (e.g. "weight") with two parameters: one specifying the magnitude (e.g. "weight_g") and one specifying the direction (e.g. "weight_v"). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every :meth:`~Module.forward` call. By default, with `dim=0`, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use `dim=None`. See https://arxiv.org/abs/1602.07868 Args: module (nn.Module): containing module name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute the norm hook_child (boolean, optional): adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. Default: True Returns: The original module with the weight norm hook Example:: >>> m = apply_weight_norm(nn.Linear(20, 40), name='weight') Linear (20 -> 40) >>> m.weight_g.size() torch.Size([40, 1]) >>> m.weight_v.size() torch.Size([40, 20]) """ return apply_reparameterization(module, reparameterization=WeightNorm, hook_child=hook_child, name=name, dim=dim) def remove_weight_norm(module, name='', remove_all=False): """ Removes the weight normalization reparameterization of a parameter from a module. If no parameter is supplied then all weight norm parameterizations are removed. Args: module (nn.Module): containing module name (str, optional): name of weight parameter Example: >>> m = apply_weight_norm(nn.Linear(20, 40)) >>> remove_weight_norm(m) """ return remove_reparameterization(module, reparameterization=WeightNorm, name=name, remove_all=remove_all) def apply_reparameterization(module, reparameterization=None, name='', dim=0, hook_child=True): """ Applies a given weight reparameterization (such as weight normalization) to a parameter in the given module. If no parameter is given, applies the reparameterization to all parameters in model (except 1-d vectors and scalars). Args: module (nn.Module): containing module reparameterization (Reparameterization): reparamaterization class to apply name (str, optional): name of weight parameter dim (int, optional): dimension over which to perform reparameterization op hook_child (boolean, optional): adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. Default: True Returns: The original module with the reparameterization hook Example:: >>> m = apply_reparameterization(nn.Linear(20, 40), WeightNorm) Linear (20 -> 40) """ assert reparameterization is not None if name != '': Reparameterization.apply(module, name, dim, reparameterization, hook_child) else: names = list(module.state_dict().keys()) for name in names: apply_reparameterization(module, reparameterization, name, dim, hook_child) return module def remove_reparameterization(module, reparameterization=Reparameterization, name='', remove_all=False): """ Removes the given reparameterization of a parameter from a module. If no parameter is supplied then all reparameterizations are removed. Args: module (nn.Module): containing module reparameterization (Reparameterization): reparamaterization class to apply name (str, optional): name of weight parameter remove_all (bool, optional): if True, remove all reparamaterizations of given type. Default: False Example: >>> m = apply_reparameterization(nn.Linear(20, 40),WeightNorm) >>> remove_reparameterization(m) """ if name != '' or remove_all: to_remove = [] for k, hook in module._forward_pre_hooks.items(): if isinstance(hook, reparameterization) and (hook.name == name or remove_all): hook.remove(module) to_remove.append(k) if len(to_remove) > 0: for k in to_remove: del module._forward_pre_hooks[k] return module if not remove_all: raise ValueError("reparameterization of '{}' not found in {}" .format(name, module)) else: modules = [module]+[x for x in module.modules()] for m in modules: remove_reparameterization(m, reparameterization=reparameterization, remove_all=True) return module ================================================ FILE: KoSimCSE/apex/reparameterization/reparameterization.py ================================================ import torch from torch.nn.parameter import Parameter import sys class Reparameterization(object): """ Class interface for performing weight reparameterizations Arguments: name (str): name of weight parameter dim (int): dimension over which to compute the norm module (nn.Module): parent module to which param `name` is registered to retain_forward (bool, optional): if False deletes weight on call to module.backward. Used to avoid memory leaks with DataParallel Default: True Attributes: reparameterization_names (list, str): contains names of all parameters needed to compute reparameterization. backward_hook_key (int): torch.utils.hooks.RemovableHandle.id for hook used in module backward pass. """ def __init__(self, name, dim, module, retain_forward=True): self.name = name self.dim = dim self.evaluated = False self.retain_forward = retain_forward self.reparameterization_names = [] self.backward_hook_key = None self.module = module def compute_weight(self, module=None, name=None): """ Computes reparameterized weight value to assign value to module attribute with name `name`. See WeightNorm class for example. Arguments: module (nn.Module): module with weight we'd like to reparameterize Returns: w (Tensor): Tensor object containing value of reparameterized weight """ raise NotImplementedError def reparameterize(self, name, weight, dim): """ Creates Parameters to be used for reparameterization and creates names that for attributes for the module these Parameters will correspond to. The parameters will be registered according to the names provided. See WeightNorm class for example. Arguments: module (nn.Module): module with weight we'd like to reparameterize name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute parameterization Returns: names (list, str): names of Parameters to be used for reparameterization params (list, Parameter): Parameters to be used for reparameterization """ raise NotImplementedError @staticmethod def apply(module, name, dim, reparameterization=None, hook_child=True): """ Applies reparametrization to module's `name` parameter and modifies instance attributes as appropriate. `hook_child` adds reparameterization hook to direct parent of the parameters. If False, it's added to `module` instead. """ if reparameterization is None: reparameterization = Reparameterization module2use, name2use = Reparameterization.get_module_and_name(module, name) # does not work on sparse if name2use is None or isinstance(module2use, (torch.nn.Embedding, torch.nn.EmbeddingBag)): return if hook_child: fn = reparameterization(name2use, dim, module2use) else: fn = reparameterization(name, dim, module) weight = getattr(module2use, name2use) if weight.dim() <= 1: return # remove weight from parameter list del module2use._parameters[name2use] # add parameters of reparameterization of parameter to module names, params = fn.reparameterize(name2use, weight, dim) for n, p in zip(names, params): module2use.register_parameter(n, p) # add parameters to reparameterization so they can be removed later fn.reparameterization_names = names setattr(module2use, name2use, None) hook_module = module2use if not hook_child: hook_module = module # recompute weight before every forward() hook_module.register_forward_pre_hook(fn) # remove weight during backward handle = hook_module.register_backward_hook(fn.backward_hook) # get hook key so we can delete it later fn.backward_hook_key = handle.id return fn @staticmethod def get_module_and_name(module, name): """ recursively fetches (possible) child module and name of weight to be reparameterized """ name2use = None module2use = None names = name.split('.') if len(names) == 1 and names[0] != '': name2use = names[0] module2use = module elif len(names) > 1: module2use = module name2use = names[0] for i in range(len(names)-1): module2use = getattr(module2use, name2use) name2use = names[i+1] return module2use, name2use def get_params(self, module): """gets params of reparameterization based on known attribute names""" return [getattr(module, n) for n in self.reparameterization_names] def remove(self, module): """removes reparameterization and backward hook (does not remove forward hook)""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) for p in self.get_params(module2use): p.requires_grad = False weight = self.compute_weight(module2use, name2use) delattr(module2use, name2use) for n in self.reparameterization_names: del module2use._parameters[n] module2use.register_parameter(name2use, Parameter(weight.data)) del module._backward_hooks[self.backward_hook_key] def __call__(self, module, inputs): """callable hook for forward pass""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) _w = getattr(module2use, name2use) if not self.evaluated or _w is None: setattr(module2use, name2use, self.compute_weight(module2use, name2use)) self.evaluated = True def backward_hook(self, module, grad_input, grad_output): """callable hook for backward pass""" module2use, name2use = Reparameterization.get_module_and_name(module, self.name) wn = getattr(module2use, name2use) self.evaluated = False ================================================ FILE: KoSimCSE/apex/reparameterization/weight_norm.py ================================================ import torch from torch.nn.parameter import Parameter from ..fp16_utils import Fused_Weight_Norm import time from .reparameterization import Reparameterization def _norm(p, dim): """Computes the norm over all dimensions except dim""" if dim is None: return p.norm() elif dim == 0: output_size = (p.size(0),) + (1,) * (p.dim() - 1) return p.contiguous().view(p.size(0), -1).norm(dim=1).view(*output_size) elif dim == p.dim() - 1: output_size = (1,) * (p.dim() - 1) + (p.size(-1),) return p.contiguous().view(-1, p.size(-1)).norm(dim=0).view(*output_size) return _norm(p.transpose(0, dim), 0).transpose(0, dim) HALF_TYPES = (torch.cuda.HalfTensor, torch.HalfTensor) class WeightNorm(Reparameterization): r""" Weight normalization is a reparameterization that decouples the magnitude of a weight tensor from its direction. This replaces the parameter specified by `name` (e.g. "weight") with two parameters: one specifying the magnitude (e.g. "weight_g") and one specifying the direction (e.g. "weight_v"). Weight normalization is implemented via a hook that recomputes the weight tensor from the magnitude and direction before every :meth:`~Module.forward` call. .. math:: \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|} By default, with `dim=0`, the norm is computed independently per output channel/plane. To compute a norm over the entire weight tensor, use `dim=None`. """ def compute_weight(self, module=None, name=None): """ Computes weight normalized weight value to assign value to module attribute with name `name`. Arguments: module (nn.Module): module with weight we'd like to reparameterize Returns: w (Tensor): Tensor object containing value of reparameterized weight """ if module is None: module = self.module if name is None: name = self.name module, name = Reparameterization.get_module_and_name(module, name) g = getattr(module, name + '_g') v = getattr(module, name + '_v') fused_weight_norm = Fused_Weight_Norm.apply v = v.contiguous() w = fused_weight_norm(v, g, self.dim) return w def reparameterize(self, name, weight, dim): """ Creates Parameters v and gto be used for weight normalization and creates names that for attributes for the module these Parameters will correspond to. The parameters will be registered according to the names provided. Arguments: module (nn.Module): module with weight we'd like to reparameterize name (str, optional): name of weight parameter dim (int, optional): dimension over which to compute parameterization Returns: names (list, str): names of Parameters to be used for reparameterization params (list, Parameter): Parameters to be used for reparameterization """ names = [name + '_g', name + '_v'] params = [Parameter(_norm(weight, dim).data), Parameter(weight.data)] return names, params ================================================ FILE: KoSimCSE/data/dataloader.py ================================================ import numpy import torch import logging from torch.utils.data import DataLoader, Dataset from transformers import AutoModel, AutoTokenizer logger = logging.getLogger(__name__) class ModelDataLoader(Dataset): def __init__(self, file_path, args, metric, tokenizer, type_): self.type = type_ self.args = args self.metric = metric """NLI""" self.anchor = [] self.positive = [] self.negative = [] """STS""" self.label = [] self.sentence_1 = [] self.sentence_2 = [] # ------------------------------------- self.bert_tokenizer = tokenizer self.file_path = file_path """ [CLS]: 2 [PAD]: 0 [UNK]: 1 """ self.init_token = self.bert_tokenizer.cls_token self.pad_token = self.bert_tokenizer.pad_token self.unk_token = self.bert_tokenizer.unk_token self.init_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.init_token) self.pad_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.pad_token) self.unk_token_idx = self.bert_tokenizer.convert_tokens_to_ids(self.unk_token) def load_data(self, type): with open(self.file_path) as file: lines = file.readlines() for line in lines: self.data2tensor(line, type) if type == 'train': assert len(self.anchor) == len(self.positive) == len(self.negative) else: assert len(self.sentence_1) == len(self.sentence_2) == len(self.label) def data2tensor(self, line, type): split_data = line.split('\t') if type == 'train': anchor_sen, positive_sen, negative_sen = split_data anchor = self.bert_tokenizer(anchor_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, pad_to_max_length="right") positive = self.bert_tokenizer(positive_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, pad_to_max_length="right") negative = self.bert_tokenizer(negative_sen, truncation=True, return_tensors="pt", max_length=self.args.max_len, pad_to_max_length="right") self.anchor.append(anchor) self.positive.append(positive) self.negative.append(negative) else: sentence_1, sentence_2, label = split_data sentence_1 = self.bert_tokenizer(sentence_1, truncation=True, return_tensors="pt", max_length=self.args.max_len, pad_to_max_length="right") sentence_2 = self.bert_tokenizer(sentence_2, truncation=True, return_tensors="pt", max_length=self.args.max_len, pad_to_max_length="right") self.sentence_1.append(sentence_1) self.sentence_2.append(sentence_2) self.label.append(float(label.strip())/5.0) def __getitem__(self, index): if self.type == 'train': inputs = {'anchor': { 'source': torch.LongTensor(self.anchor[index]['input_ids']), 'attention_mask': self.anchor[index]['attention_mask'], 'token_type_ids': torch.LongTensor(self.anchor[index]['token_type_ids']) }, 'positive': { 'source': torch.LongTensor(self.positive[index]['input_ids']), 'attention_mask': self.positive[index]['attention_mask'], 'token_type_ids': torch.LongTensor(self.positive[index]['token_type_ids']) }, 'negative': { 'source': torch.LongTensor(self.negative[index]['input_ids']), 'attention_mask': self.negative[index]['attention_mask'], 'token_type_ids': torch.LongTensor(self.negative[index]['token_type_ids']) }} else: inputs = {'sentence_1': { 'source': torch.LongTensor(self.sentence_1[index]['input_ids']), 'attention_mask': self.sentence_1[index]['attention_mask'], 'token_type_ids': torch.LongTensor(self.sentence_1[index]['token_type_ids']) }, 'sentence_2': { 'source': torch.LongTensor(self.sentence_2[index]['input_ids']), 'attention_mask': self.sentence_2[index]['attention_mask'], 'token_type_ids': torch.LongTensor(self.sentence_2[index]['token_type_ids']) }, 'label': { 'value': torch.FloatTensor([self.label[index]])} } for key, value in inputs.items(): for inner_key, inner_value in value.items(): inputs[key][inner_key] = inner_value.squeeze(0) inputs = self.metric.move2device(inputs, self.args.device) return inputs def __len__(self): if self.type == 'train': return len(self.anchor) else: return len(self.label) # Get train, valid, test data loader and BERT tokenizer def get_loader(args, metric): tokenizer = AutoTokenizer.from_pretrained(args.model) path_to_train_data = args.path_to_data + '/' + args.train_data path_to_valid_data = args.path_to_data + '/' + args.valid_data path_to_test_data = args.path_to_data + '/' + args.test_data if args.train == 'True' and args.test == 'False': train_iter = ModelDataLoader(path_to_train_data, args, metric, tokenizer, type_='train') valid_iter = ModelDataLoader(path_to_valid_data, args, metric, tokenizer, type_='valid') train_iter.load_data('train') valid_iter.load_data('valid') loader = {'train': DataLoader(dataset=train_iter, batch_size=args.batch_size, shuffle=True), 'valid': DataLoader(dataset=valid_iter, batch_size=args.batch_size, shuffle=True)} elif args.train == 'False' and args.test == 'True': test_iter = ModelDataLoader(path_to_test_data, args, metric, tokenizer, type_='test') test_iter.load_data('test') loader = {'test': DataLoader(dataset=test_iter, batch_size=args.batch_size, shuffle=True)} else: loader = None return loader, tokenizer def convert_to_tensor(corpus, tokenizer, device): inputs = tokenizer(corpus, truncation=True, return_tensors="pt", max_length=50, pad_to_max_length="right") embedding = inputs['input_ids'] attention_mask = inputs['attention_mask'] token_type_ids = inputs['token_type_ids'] inputs = {'source': torch.LongTensor(embedding).to(device), 'token_type_ids': torch.LongTensor(token_type_ids).to(device), 'attention_mask': attention_mask.to(device)} return inputs def example_model_setting(model_ckpt, model_name): from model.simcse.bert import BERT device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') model = BERT(AutoModel.from_pretrained(model_name)) tokenizer = AutoTokenizer.from_pretrained(model_name) model.load_state_dict(torch.load(model_ckpt)['model']) model.to(device) model.eval() return model, tokenizer, device if __name__ == '__main__': get_loader('test') ================================================ FILE: KoSimCSE/main.py ================================================ from model.setting import Setting, Arguments from model.simcse.processor import Processor def main(args, logger) -> None: processor = Processor(args) config = processor.model_setting() logger.info('Model Setting Complete') if args.train == 'True': logger.info('Start Training') for epoch in range(args.epochs): processor.train(epoch+1) if args.test == 'True': logger.info("Start Test") processor.test() processor.metric.print_size_of_model(config['model']) processor.metric.count_parameters(config['model']) if __name__ == '__main__': args, logger = Setting().run() main(args, logger) ================================================ FILE: KoSimCSE/model/loss.py ================================================ import torch import logging import numpy as np import torch.nn as nn from model.utils import Metric from scipy.stats import pearsonr, spearmanr from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances logger = logging.getLogger(__name__) class Loss(): def __init__(self, args): self.args = args self.cos = nn.CosineSimilarity(dim=-1) self.metric = Metric(args) def train_loss_fct(self, config, inputs, a, p, n): positive_similarity = self.cos(a.unsqueeze(1), p.unsqueeze(0)) / self.args.temperature negative_similarity = self.cos(a.unsqueeze(1), n.unsqueeze(0)) / self.args.temperature cosine_similarity = torch.cat([positive_similarity, negative_similarity], dim=1).to(self.args.device) labels = torch.arange(cosine_similarity.size(0)).long().to(self.args.device) loss = config['criterion'](cosine_similarity, labels) return loss def evaluation_during_training(self, embeddings1, embeddings2, labels, indicator): embeddings1 = embeddings1.cpu().numpy() embeddings2 = embeddings2.cpu().numpy() labels = labels['value'].cpu().numpy().flatten() cosine_scores = 1 - (paired_cosine_distances(embeddings1, embeddings2)) manhattan_distances = -paired_manhattan_distances(embeddings1, embeddings2) euclidean_distances = -paired_euclidean_distances(embeddings1, embeddings2) dot_products = [np.dot(emb1, emb2) for emb1, emb2 in zip(embeddings1, embeddings2)] eval_pearson_cosine, _ = pearsonr(labels, cosine_scores) eval_spearman_cosine, _ = spearmanr(labels, cosine_scores) eval_pearson_manhattan, _ = pearsonr(labels, manhattan_distances) eval_spearman_manhattan, _ = spearmanr(labels, manhattan_distances) eval_pearson_euclidean, _ = pearsonr(labels, euclidean_distances) eval_spearman_euclidean, _ = spearmanr(labels, euclidean_distances) eval_pearson_dot, _ = pearsonr(labels, dot_products) eval_spearman_dot, _ = spearmanr(labels, dot_products) score = {'eval_pearson_cosine': eval_pearson_cosine, 'eval_spearman_cosine': eval_spearman_cosine, 'eval_pearson_manhattan': eval_pearson_manhattan, 'eval_spearman_manhattan': eval_spearman_manhattan, 'eval_pearson_euclidean': eval_pearson_euclidean, 'eval_spearman_euclidean': eval_spearman_euclidean, 'eval_pearson_dot': eval_pearson_dot, 'eval_spearman_dot': eval_spearman_dot} self.metric.update_indicator(indicator, score) return max(eval_spearman_cosine, eval_spearman_manhattan, eval_spearman_euclidean, eval_spearman_dot) ================================================ FILE: KoSimCSE/model/setting.py ================================================ import torch import random import logging import numpy as np from argparse import ArgumentParser class Arguments(): def __init__(self): self.parser = ArgumentParser() def add_type_of_processing(self): self.add_argument('--opt_level', type=str, default='O1') self.add_argument('--fp16', type=str, default='True') self.add_argument('--train', type=str, default='True') self.add_argument('--test', type=str, default='True') self.add_argument('--device', type=str, default=torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')) def add_hyper_parameters(self): self.add_argument('--model', type=str, default='klue/bert-base') self.add_argument('--patient', type=int, default=10) self.add_argument('--dropout', type=int, default=0.1) self.add_argument('--max_len', type=int, default=50) self.add_argument('--batch_size', type=int, default=256) self.add_argument('--epochs', type=int, default=3) self.add_argument('--eval_steps', type=int, default=250) self.add_argument('--seed', type=int, default=12) self.add_argument('--lr', type=float, default=0.00005) self.add_argument('--weight_decay', type=float, default=0.1) self.add_argument('--warmup_ratio', type=float, default=0.05) self.add_argument('--temperature', type=float, default=0.05) def add_data_parameters(self): self.add_argument('--train_data', type=str, default='train_nli.tsv') self.add_argument('--valid_data', type=str, default='valid_sts.tsv') self.add_argument('--test_data', type=str, default='test_sts.tsv') self.add_argument('--task', type=str, default='NLU') self.add_argument('--path_to_data', type=str, default='./data/') self.add_argument('--path_to_save', type=str, default='./output/') self.add_argument('--path_to_saved_model', type=str, default='./output/') self.add_argument('--ckpt', type=str, default='best_checkpoint.pt') def print_args(self, args): for idx, (key, value) in enumerate(args.__dict__.items()): if idx == 0:print("argparse{\n", "\t", key, ":", value) elif idx == len(args.__dict__) - 1:print("\t", key, ":", value, "\n}") else:print("\t", key, ":", value) def add_argument(self, *args, **kw_args): return self.parser.add_argument(*args, **kw_args) def parse(self): args = self.parser.parse_args() self.print_args(args) return args class Setting(): def set_logger(self): _logger = logging.getLogger() formatter = logging.Formatter( '[%(levelname)s] %(asctime)s [ %(message)s ] | file::%(filename)s | line::%(lineno)s') stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) _logger.addHandler(stream_handler) _logger.setLevel(logging.DEBUG) return _logger def set_seed(self, args): seed = args.seed random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) def run(self): parser = Arguments() parser.add_type_of_processing() parser.add_hyper_parameters() parser.add_data_parameters() args = parser.parse() logger = self.set_logger() self.set_seed(args) return args, logger ================================================ FILE: KoSimCSE/model/simcse/bert.py ================================================ import torch from torch import nn class BERT(nn.Module): def __init__(self, bert): super(BERT, self).__init__() self.bert = bert def forward(self, config, inputs, mode): if mode == 'train': anchor_pooler, _ = self.bert(input_ids=inputs['anchor']['source'], token_type_ids=inputs['anchor']['token_type_ids'], attention_mask=inputs['anchor']['attention_mask'], return_dict=False) positive_pooler, _ = self.bert(input_ids=inputs['positive']['source'], token_type_ids=inputs['positive']['token_type_ids'], attention_mask=inputs['positive']['attention_mask'], return_dict=False) negative_pooler, _ = self.bert(input_ids=inputs['negative']['source'], token_type_ids=inputs['negative']['token_type_ids'], attention_mask=inputs['negative']['attention_mask'], return_dict=False) return anchor_pooler[:, 0], positive_pooler[:, 0], negative_pooler[:, 0] else: sentence_1_pooler, _ = self.bert(input_ids=inputs['sentence_1']['source'], token_type_ids=inputs['sentence_1']['token_type_ids'], attention_mask=inputs['sentence_1']['attention_mask'], return_dict=False) sentence_2_pooler, _ = self.bert(input_ids=inputs['sentence_2']['source'], token_type_ids=inputs['sentence_2']['token_type_ids'], attention_mask=inputs['sentence_2']['attention_mask'], return_dict=False) return sentence_1_pooler[:, 0], sentence_2_pooler[:, 0] def encode(self, inputs, device): embeddings, _ = self.bert(input_ids=inputs['source'].to(device), token_type_ids=inputs['token_type_ids'].to(device), attention_mask=inputs['attention_mask'].to(device), return_dict=False) return embeddings[:, 0] ================================================ FILE: KoSimCSE/model/simcse/processor.py ================================================ import os import logging from apex import amp import torch.nn as nn from tqdm import tqdm import torch.quantization import torch.optim as optim from model.loss import Loss from model.utils import Metric from transformers import AutoModel from model.simcse.bert import BERT from data.dataloader import get_loader from transformers import get_linear_schedule_with_warmup logger = logging.getLogger(__name__) class Processor(): def __init__(self, args): self.args = args self.config = None self.metric = Metric(args) self.loss = Loss(args) self.total_steps = 0 self.model_checker = {'early_stop': False, 'early_stop_patient': 0, 'best_valid_score': 0} self.dev_progress = {'score': 0, 'iter': 0} self.model_progress = {'loss': 0, 'iter': 0} def run(self, inputs, indicator=None, type=None): if type == 'train': anchor_embeddings, positive_embeddings, negative_embeddings = self.config['model'](self.config, inputs, type) loss = self.loss.train_loss_fct(self.config, inputs, anchor_embeddings, positive_embeddings, negative_embeddings) return loss else: sentence_1_embeddings, sentence_2_embeddings = self.config['model'](self.config, inputs, type) score = self.loss.evaluation_during_training(sentence_1_embeddings, sentence_2_embeddings, inputs['label'], indicator) return score def progress(self, loss): self.model_progress['loss'] += loss self.model_progress['iter'] += 1 def progress_validation(self, score): self.dev_progress['score'] += score self.dev_progress['iter'] += 1 def return_value(self): loss = self.model_progress['loss'].data.cpu().numpy() / self.model_progress['iter'] acc = self.model_progress['acc'].data.cpu().numpy() / self.model_progress['iter'] return loss, acc def get_object(self, tokenizer, model): no_decay = ['bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': self.args.weight_decay}, {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} ] criterion = nn.CrossEntropyLoss() optimizer = optim.AdamW(optimizer_grouped_parameters, lr=self.args.lr) return criterion, optimizer def get_scheduler(self, optim, train_loader): train_total = len(train_loader) * self.args.epochs scheduler = get_linear_schedule_with_warmup(optim, num_warmup_steps=self.args.warmup_ratio * train_total, num_training_steps=train_total) return scheduler, train_total def model_setting(self): loader, tokenizer = get_loader(self.args, self.metric) model = BERT(AutoModel.from_pretrained(self.args.model)) model.to(self.args.device) criterion, optimizer = self.get_object(tokenizer, model) if self.args.train == 'True': scheduler, total_steps = self.get_scheduler(optimizer, loader['train']) self.total_steps = total_steps else: scheduler = None config = {'loader': loader, 'optimizer': optimizer, 'criterion': criterion, 'scheduler': scheduler, 'tokenizer': tokenizer, 'args': self.args, 'model': model} if config['args'].fp16 == 'True': config['model'], config['optimizer'] = amp.initialize( config['model'], config['optimizer'], opt_level=config['args'].opt_level) self.config = config return self.config def train(self, epoch): self.config['model'].train() for step, batch in enumerate(tqdm(self.config['loader']['train'])): self.config['optimizer'].zero_grad() inputs = batch train_loss = self.run(inputs, type='train') if self.args.fp16 == 'True': with amp.scale_loss(train_loss, self.config['optimizer']) as scaled_loss: scaled_loss.backward() else: train_loss.backward() self.config['optimizer'].step() self.config['scheduler'].step() self.progress(train_loss.data) if self.model_progress['iter'] % self.args.eval_steps == 0 or self.model_progress['iter'] == self.total_steps: valid_score = self.valid() performance = {'tl': train_loss, 'vs': valid_score, 'ep': epoch, 'step': self.model_progress['iter']} self.metric.save_model(self.config, performance, self.model_checker) self.config['model'].train() def valid(self): self.config['model'].eval() self.dev_progress = self.dev_progress.fromkeys(self.dev_progress, 0) score_indicator = {'eval_pearson_cosine': 0, 'eval_spearman_cosine': 0, 'eval_pearson_manhattan': 0, 'eval_spearman_manhattan': 0, 'eval_pearson_euclidean': 0, 'eval_spearman_euclidean': 0, 'eval_pearson_dot': 0, 'eval_spearman_dot': 0} with torch.no_grad(): for step, batch in enumerate(self.config['loader']['valid']): inputs = batch score = self.run(inputs, indicator=score_indicator, type='valid') self.progress_validation(score) score = self.metric.cal_dev_score(self.dev_progress, score_indicator) return score def test(self): self.config['model'].load_state_dict(torch.load(self.args.path_to_saved_model)['model'], strict=False) self.config['model'].eval() self.dev_progress = self.dev_progress.fromkeys(self.dev_progress, 0) score_indicator = {'eval_pearson_cosine': 0, 'eval_spearman_cosine': 0, 'eval_pearson_manhattan': 0, 'eval_spearman_manhattan': 0, 'eval_pearson_euclidean': 0, 'eval_spearman_euclidean': 0, 'eval_pearson_dot': 0, 'eval_spearman_dot': 0} with torch.no_grad(): for step, batch in enumerate(self.config['loader']['test']): inputs = batch score = self.run(inputs, indicator=score_indicator, type='test') self.progress_validation(score) logger.info('### TEST SCORE ###') score = self.metric.cal_dev_score(self.dev_progress, score_indicator) ================================================ FILE: KoSimCSE/model/utils.py ================================================ import os import torch import logging from tensorboardX import SummaryWriter logger = logging.getLogger(__name__) writer = SummaryWriter() class Metric(): def __init__(self, args): self.args = args def get_lr(self, optimizer): return optimizer.state_dict()['param_groups'][0]['lr'] def count_parameters(self, model): print(sum(p.numel() for p in model.parameters() if p.requires_grad)) def cal_acc(self, yhat, y): with torch.no_grad(): yhat = yhat.max(dim=-1)[1] acc = (yhat == y).float().mean() return acc def cal_time(self, start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs def cal_dev_score(self, score, indicator): validation_score = score['score'] / score['iter'] for key, value in indicator.items(): indicator[key] /= score['iter'] print("\n\nCosine-Similarity :\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_cosine'], indicator['eval_spearman_cosine'])) print("Manhattan-Distance:\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_manhattan'], indicator['eval_spearman_manhattan'])) print("Euclidean-Distance:\tPearson: {:.4f}\tSpearman: {:.4f}".format( indicator['eval_pearson_euclidean'], indicator['eval_spearman_euclidean'])) print("Dot-Product-Similarity:\tPearson: {:.4f}\tSpearman: {:.4f}\n".format( indicator['eval_pearson_dot'], indicator['eval_spearman_dot'])) return validation_score def update_indicator(self, indicator, score): for key, value in indicator.items(): if key == 'eval_spearman_cosine': indicator[key] += score['eval_spearman_cosine'] elif key == 'eval_pearson_cosine': indicator[key] += score['eval_pearson_cosine'] elif key == 'eval_spearman_manhattan': indicator[key] += score['eval_spearman_manhattan'] elif key == 'eval_pearson_manhattan': indicator[key] += score['eval_pearson_manhattan'] elif key == 'eval_spearman_euclidean': indicator[key] += score['eval_spearman_euclidean'] elif key == 'eval_pearson_euclidean': indicator[key] += score['eval_pearson_euclidean'] elif key == 'eval_spearman_dot': indicator[key] += score['eval_spearman_dot'] elif key == 'eval_pearson_dot': indicator[key] += score['eval_pearson_dot'] def draw_graph(self, cp): writer.add_scalars('loss_graph', {'train': cp['tl'], 'valid': cp['vl']}, cp['ep']) writer.add_scalars('acc_graph', {'train': cp['tma'], 'valid': cp['vma']}, cp['ep']) def performance_check(self, cp, config): print(f'\t==Epoch: {cp["ep"] + 1:02} | Epoch Time: {cp["epm"]}m {cp["eps"]}s==') print(f'\t==Train Loss: {cp["tl"]:.4f} | Train acc: {cp["tma"]:.4f}==') print(f'\t==Valid Loss: {cp["vl"]:.4f} | Valid acc: {cp["vma"]:.4f}==') print(f'\t==Epoch latest LR: {self.get_lr(config["optimizer"]):.9f}==\n') def print_size_of_model(self, model): torch.save(model.state_dict(), "temp.p") print('Size (MB):', os.path.getsize("temp.p") / 1e6) os.remove('temp.p') def move2device(self, sample, device): if len(sample) == 0: return {} def _move_to_device(maybe_tensor, device): if torch.is_tensor(maybe_tensor): return maybe_tensor.to(device) elif isinstance(maybe_tensor, dict): return { key: _move_to_device(value, device) for key, value in maybe_tensor.items() } elif isinstance(maybe_tensor, list): return [_move_to_device(x, device) for x in maybe_tensor] elif isinstance(maybe_tensor, tuple): return [_move_to_device(x, device) for x in maybe_tensor] else: return maybe_tensor return _move_to_device(sample, device) def save_model(self, config, cp, pco): if not os.path.exists(config['args'].path_to_save): os.makedirs(config['args'].path_to_save) sorted_path = config['args'].path_to_save + "kosimcse-" + config['args'].model.replace("/", "-") + '.pt' if cp['vs'] > pco['best_valid_score']: pco['best_valid_score'] = cp['vs'] state = {'model': config['model'].state_dict(), 'optimizer': config['optimizer'].state_dict()} torch.save(state, sorted_path) print(f'\t## SAVE {sorted_path} |' f' valid_score: {cp["vs"]:.4f} |' f' epochs: {cp["ep"]} |' f' steps: {cp["step"]} ##\n') def pytorch_cos_sim(a, b): """ Computes the cosine similarity cos_sim(a[i], b[j]) for all i and j. This function can be used as a faster replacement for 1-scipy.spatial.distance.cdist(a,b) :return: Matrix with res[i][j] = cos_sim(a[i], b[j]) """ if not isinstance(a, torch.Tensor): a = torch.tensor(a) if not isinstance(b, torch.Tensor): b = torch.tensor(b) if len(a.shape) == 1: a = a.unsqueeze(0) if len(b.shape) == 1: b = b.unsqueeze(0) a_norm = a / a.norm(dim=1)[:, None] b_norm = b / b.norm(dim=1)[:, None] return torch.mm(a_norm, b_norm.transpose(0, 1)) ================================================ FILE: KoSimCSE/output/empty.txt ================================================ ## ================================================ FILE: KoSimCSE/requirements.txt ================================================ torch >= 1.7.0 mxnet >= 1.4.0 gluonnlp >= 0.6.0 sentencepiece >= 0.1.6 onnxruntime >= 0.3.0 transformers == 2.8.0 ================================================ FILE: KoSimCSE/run_example.sh ================================================ #!/bin/bash echo "Start Training (BERT-BASE)" CUDA_VISIBLE_DEVICES=0 python main.py \ --model klue/bert-base \ --test False \ --max_len 50 \ --batch_size 512 \ --epochs 2 \ --eval_steps 250 \ --lr 0.0001 \ --warmup_ratio 0.1 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --train_data train_nli.tsv \ --valid_data valid_sts.tsv echo "Start Testing (BERT-BASE)" CUDA_VISIBLE_DEVICES=0 python main.py \ --model klue/bert-base \ --train False \ --test True \ --max_len 50 \ --batch_size 512 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --test_data test_sts.tsv \ --path_to_saved_model output/kosimcse-klue-bert-base.pt echo "Start Training (RoBERTa-BASE)" CUDA_VISIBLE_DEVICES=0 python main.py \ --model klue/roberta-base \ --test False \ --max_len 50 \ --batch_size 512 \ --epochs 2 \ --eval_steps 125 \ --lr 0.0001 \ --warmup_ratio 0.2 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --train_data train_nli.tsv \ --valid_data valid_sts.tsv echo "Start Testing (RoBERTa-BASE)" CUDA_VISIBLE_DEVICES=0 python main.py \ --model klue/roberta-base \ --train False \ --test True \ --max_len 50 \ --batch_size 512 \ --temperature 0.05 \ --path_to_data ../Dataset/ \ --test_data test_sts.tsv \ --path_to_saved_model output/kosimcse-klue-roberta-base.pt ================================================ FILE: LICENSE ================================================ Attribution-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. l. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. m. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: README.md ================================================ # Korean-Sentence-Embedding The Korean Sentence Embedding Repository offers pre-trained models that can be easily downloaded and used immediately. Additionally, it provides an optimized environment for customized model training. ## Quick tour > **Note**
> All the pretrained models are uploaded in Huggingface Model Hub. Check https://huggingface.co/BM-K ```python import torch from transformers import AutoModel, AutoTokenizer def cal_score(a, b): if len(a.shape) == 1: a = a.unsqueeze(0) if len(b.shape) == 1: b = b.unsqueeze(0) a_norm = a / a.norm(dim=1)[:, None] b_norm = b / b.norm(dim=1)[:, None] return torch.mm(a_norm, b_norm.transpose(0, 1)) * 100 model = AutoModel.from_pretrained('BM-K/KoSimCSE-roberta-multitask') # or 'BM-K/KoSimCSE-bert-multitask' tokenizer = AutoTokenizer.from_pretrained('BM-K/KoSimCSE-roberta-multitask') # or 'BM-K/KoSimCSE-bert-multitask' sentences = ['치타가 들판을 가로 질러 먹이를 쫓는다.', '치타 한 마리가 먹이 뒤에서 달리고 있다.', '원숭이 한 마리가 드럼을 연주한다.'] inputs = tokenizer(sentences, padding=True, truncation=True, return_tensors="pt") embeddings, _ = model(**inputs, return_dict=False) score01 = cal_score(embeddings[0][0], embeddings[1][0]) # 84.09 # '치타가 들판을 가로 질러 먹이를 쫓는다.' @ '치타 한 마리가 먹이 뒤에서 달리고 있다.' score02 = cal_score(embeddings[0][0], embeddings[2][0]) # 23.21 # '치타가 들판을 가로 질러 먹이를 쫓는다.' @ '원숭이 한 마리가 드럼을 연주한다.' ``` ## Update history ** Updates on Mar.08.2023 ** - Update Unsupervised Models ** Updates on Feb.24.2023 ** - Upload KoSimCSE clustering example ** Updates on Nov.15.2022 ** - Upload KoDiffCSE-unsupervised training code ** Updates on Oct.27.2022 ** - Upload KoDiffCSE-unsupervised performance ** Updates on Oct.21.2022 ** - Upload KoSimCSE-unsupervised performance ** Updates on Jun.01.2022 ** - Release KoSimCSE-multitask models ** Updates on May.23.2022 ** - Upload KoSentenceT5 training code - Upload KoSentenceT5 performance ** Updates on Mar.01.2022 ** - Release KoSimCSE ** Updates on Feb.11.2022 ** - Upload KoSimCSE training code - Upload KoSimCSE performance ** Updates on Jan.26.2022 ** - Upload KoSBERT training code - Upload KoSBERT performance ## Baseline Models Baseline models used for korean sentence embedding - [KLUE-PLMs](https://github.com/KLUE-benchmark/KLUE/blob/main/README.md) | Model | Embedding size | Hidden size | # Layers | # Heads | |----------------------|----------------|-------------|----------|---------| | KLUE-BERT-base | 768 | 768 | 12 | 12 | | KLUE-RoBERTa-base | 768 | 768 | 12 | 12 | > **Warning**
> Large pre-trained models need a lot of GPU memory to train ## Available Models 1. Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks [[SBERT]-[EMNLP 2019]](https://arxiv.org/abs/1908.10084) 2. SimCSE: Simple Contrastive Learning of Sentence Embeddings [[SimCSE]-[EMNLP 2021]](https://arxiv.org/abs/2104.08821) 3. Sentence-T5: Scalable Sentence Encoders from Pre-trained Text-to-Text Models [[Sentence-T5]-[ACL findings 2022]](https://arxiv.org/abs/2108.08877) 4. DiffCSE: Difference-based Contrastive Learning for Sentence Embeddings [[DiffCSE]-[NAACL 2022]](https://arxiv.org/abs/2204.10298) ## Datasets - [kakaobrain KorNLU Datasets](https://github.com/kakaobrain/KorNLUDatasets) (Supervised setting) - [wiki-corpus](https://github.com/jeongukjae/korean-wikipedia-corpus) (Unsupervised setting) ## Setups [![Python](https://img.shields.io/badge/python-3.8.5-blue?logo=python&logoColor=FED643)](https://www.python.org/downloads/release/python-385/) [![Pytorch](https://img.shields.io/badge/pytorch-1.7.1-red?logo=pytorch)](https://pytorch.org/get-started/previous-versions/) ### KoSentenceBERT - 🤗 [Model Training](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSBERT) - Dataset (Supervised) - Training: snli_1.0_train.ko.tsv, sts-train.tsv (multi-task) - Performance can be further improved by adding multinli data to training. - Validation: sts-dev.tsv - Test: sts-test.tsv ### KoSimCSE - 🤗 [Model Training](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSimCSE) - Dataset (Supervised) - Training: snli_1.0_train.ko.tsv + multinli.train.ko.tsv (Supervised setting) - Validation: sts-dev.tsv - Test: sts-test.tsv - Dataset (Unsupervised) - Training: wiki_corpus.txt - Validation: sts-dev.tsv - Test: sts-test.tsv ### KoSentenceT5 - 🤗 [Model Training](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSentenceT5) - Dataset (Supervised) - Training: snli_1.0_train.ko.tsv + multinli.train.ko.tsv - Validation: sts-dev.tsv - Test: sts-test.tsv ### KoDiffCSE - 🤗 [Model Training](https://github.com/BM-K/KoDiffCSE) - Dataset (Unsupervised) - Training: wiki_corpus.txt - Validation: sts-dev.tsv - Test: sts-test.tsv ## Performance-supervised | Model | Average | Cosine Pearson | Cosine Spearman | Euclidean Pearson | Euclidean Spearman | Manhattan Pearson | Manhattan Spearman | Dot Pearson | Dot Spearman | |------------------------|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:| | KoSBERTSKT | 77.40 | 78.81 | 78.47 | 77.68 | 77.78 | 77.71 | 77.83 | 75.75 | 75.22 | | KoSBERT | 80.39 | 82.13 | 82.25 | 80.67 | 80.75 | 80.69 | 80.78 | 77.96 | 77.90 | | KoSRoBERTa | 81.64 | 81.20 | 82.20 | 81.79 | 82.34 | 81.59 | 82.20 | 80.62 | 81.25 | | | | | | | | | | | | KoSentenceBART | 77.14 | 79.71 | 78.74 | 78.42 | 78.02 | 78.40 | 78.00 | 74.24 | 72.15 | | KoSentenceT5 | 77.83 | 80.87 | 79.74 | 80.24 | 79.36 | 80.19 | 79.27 | 72.81 | 70.17 | | | | | | | | | | | | KoSimCSE-BERTSKT | 81.32 | 82.12 | 82.56 | 81.84 | 81.63 | 81.99 | 81.74 | 79.55 | 79.19 | | KoSimCSE-BERT | 83.37 | 83.22 | 83.58 | 83.24 | 83.60 | 83.15 | 83.54 | 83.13 | 83.49 | | KoSimCSE-RoBERTa | 83.65 | 83.60 | 83.77 | 83.54 | 83.76 | 83.55 | 83.77 | 83.55 | 83.64 | | | | | | | | | | | | | KoSimCSE-BERT-multitask | 85.71 | 85.29 | 86.02 | 85.63 | 86.01 | 85.57 | 85.97 | 85.26 | 85.93 | | KoSimCSE-RoBERTa-multitask | 85.77 | 85.08 | 86.12 | 85.84 | 86.12 | 85.83 | 86.12 | 85.03 | 85.99 | - [KoSBERTSKT](https://github.com/BM-K/KoSentenceBERT-SKT) - [KoSimCSE-BERTSKT](https://github.com/BM-K/KoSimCSE-SKT) ## Performance-unsupervised | Model | Average | Cosine Pearson | Cosine Spearman | Euclidean Pearson | Euclidean Spearman | Manhattan Pearson | Manhattan Spearman | Dot Pearson | Dot Spearman | |------------------------|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:|:----:| | KoSRoBERTa-base | N/A | N/A | 48.96 | N/A | N/A | N/A | N/A | N/A | N/A | | KoSRoBERTa-large | N/A | N/A | 51.35 | N/A | N/A | N/A | N/A | N/A | N/A | | | | | | | | | | | | | KoSimCSE-BERT | 74.08 | 74.92 | 73.98 | 74.15 | 74.22 | 74.07 | 74.07 | 74.15 | 73.14 | | KoSimCSE-RoBERTa | 75.27 | 75.93 | 75.00 | 75.28 | 75.01 | 75.17 | 74.83 | 75.95 | 75.01 | | | | | | | | | | | | | KoDiffCSE-RoBERTa | 77.17 | 77.73 | 76.96 | 77.21 | 76.89 | 77.11 | 76.81 | 77.74 | 76.97 | - [Korean-SRoBERTa](https://arxiv.org/abs/2004.03289) ## Downstream tasks - KoSBERT: [Semantic Search](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSBERT#semantic-search), [Clustering](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSBERT#clustering) - KoSimCSE: [Semantic Search](https://github.com/BM-K/Sentence-Embedding-is-all-you-need/tree/main/KoSimCSE#semantic-search), [Clustering](https://github.com/BM-K/Sentence-Embedding-Is-All-You-Need/tree/main/KoSimCSE#clustering) ## License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. Creative Commons License
## References ```bibtex @misc{park2021klue, title={KLUE: Korean Language Understanding Evaluation}, author={Sungjoon Park and Jihyung Moon and Sungdong Kim and Won Ik Cho and Jiyoon Han and Jangwon Park and Chisung Song and Junseong Kim and Yongsook Song and Taehwan Oh and Joohong Lee and Juhyun Oh and Sungwon Lyu and Younghoon Jeong and Inkwon Lee and Sangwoo Seo and Dongjun Lee and Hyunwoo Kim and Myeonghwa Lee and Seongbo Jang and Seungwon Do and Sunkyoung Kim and Kyungtae Lim and Jongwon Lee and Kyumin Park and Jamin Shin and Seonghyun Kim and Lucy Park and Alice Oh and Jung-Woo Ha and Kyunghyun Cho}, year={2021}, eprint={2105.09680}, archivePrefix={arXiv}, primaryClass={cs.CL} } @inproceedings{gao2021simcse, title={{SimCSE}: Simple Contrastive Learning of Sentence Embeddings}, author={Gao, Tianyu and Yao, Xingcheng and Chen, Danqi}, booktitle={Empirical Methods in Natural Language Processing (EMNLP)}, year={2021} } @article{ham2020kornli, title={KorNLI and KorSTS: New Benchmark Datasets for Korean Natural Language Understanding}, author={Ham, Jiyeon and Choe, Yo Joong and Park, Kyubyong and Choi, Ilji and Soh, Hyungjoon}, journal={arXiv preprint arXiv:2004.03289}, year={2020} } @inproceedings{reimers-2019-sentence-bert, title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks", author = "Reimers, Nils and Gurevych, Iryna", booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing", month = "11", year = "2019", publisher = "Association for Computational Linguistics", url = "http://arxiv.org/abs/1908.10084", } @inproceedings{chuang2022diffcse, title={{DiffCSE}: Difference-based Contrastive Learning for Sentence Embeddings}, author={Chuang, Yung-Sung and Dangovski, Rumen and Luo, Hongyin and Zhang, Yang and Chang, Shiyu and Soljacic, Marin and Li, Shang-Wen and Yih, Wen-tau and Kim, Yoon and Glass, James}, booktitle={Annual Conference of the North American Chapter of the Association for Computational Linguistics (NAACL)}, year={2022} } ``` ================================================ FILE: get_model_checkpoint.sh ================================================ #!/bin/bash pip install gdown gdown --folder https://drive.google.com/drive/folders/https://drive.google.com/drive/folders/1orQxudCmdOLvRUFJdWEEK31l7IOVUnWs?usp=sharing -O Checkpoint ================================================ FILE: get_model_dataset.sh ================================================ #!/bin/bash pip install gdown gdown --folder https://drive.google.com/drive/folders/https://drive.google.com/drive/folders/140QpBbBPWXlqsbGZM1SpzhKDLMznq39B?usp=sharing -O Dataset