Upload folder using huggingface_hub (part 34)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +130 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/_functions.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/activation.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/adaptive.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/batchnorm.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/channelshuffle.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/container.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/conv.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/distance.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/dropout.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/flatten.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/fold.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/instancenorm.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/lazy.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear_cross_entropy.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear_cross_entropy_options.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/loss.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/module.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/normalization.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/padding.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/pixelshuffle.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/pooling.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/rnn.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/sparse.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/transformer.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/upsampling.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/utils.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/_functions.py +320 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/activation.py +1917 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/adaptive.py +337 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/batchnorm.py +951 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/channelshuffle.py +62 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/container.py +1045 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/conv.py +1921 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/distance.py +100 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/dropout.py +323 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/flatten.py +136 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/fold.py +335 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/instancenorm.py +492 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/lazy.py +278 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/linear.py +338 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/linear_cross_entropy.py +1480 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/linear_cross_entropy_options.py +316 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/loss.py +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/module.py +0 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/normalization.py +441 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/padding.py +842 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/pixelshuffle.py +127 -0
- .venv/lib/python3.12/site-packages/torch/nn/modules/pooling.py +1554 -0
.gitattributes
CHANGED
|
@@ -594,3 +594,133 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 594 |
.venv/lib/python3.12/site-packages/torch/nested/_internal/__pycache__/ops.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 595 |
.venv/lib/python3.12/site-packages/torch/nn/__pycache__/functional.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 596 |
.venv/lib/python3.12/site-packages/torch/nn/attention/__pycache__/flex_attention.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 594 |
.venv/lib/python3.12/site-packages/torch/nested/_internal/__pycache__/ops.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 595 |
.venv/lib/python3.12/site-packages/torch/nn/__pycache__/functional.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 596 |
.venv/lib/python3.12/site-packages/torch/nn/attention/__pycache__/flex_attention.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 597 |
+
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/loss.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 598 |
+
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/module.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 599 |
+
.venv/lib/python3.12/site-packages/torch/nn/parallel/__pycache__/distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 600 |
+
.venv/lib/python3.12/site-packages/torch/onnx/_internal/torchscript_exporter/__pycache__/symbolic_opset9.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 601 |
+
.venv/lib/python3.12/site-packages/torch/optim/__pycache__/lr_scheduler.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 602 |
+
.venv/lib/python3.12/site-packages/torch/profiler/_cupti/__pycache__/monitor_trace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 603 |
+
.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 604 |
+
.venv/lib/python3.12/site-packages/torch/test/CppSignature_test filter=lfs diff=lfs merge=lfs -text
|
| 605 |
+
.venv/lib/python3.12/site-packages/torch/test/Dict_test filter=lfs diff=lfs merge=lfs -text
|
| 606 |
+
.venv/lib/python3.12/site-packages/torch/test/IListRef_test filter=lfs diff=lfs merge=lfs -text
|
| 607 |
+
.venv/lib/python3.12/site-packages/torch/test/KernelFunction_test filter=lfs diff=lfs merge=lfs -text
|
| 608 |
+
.venv/lib/python3.12/site-packages/torch/test/List_test filter=lfs diff=lfs merge=lfs -text
|
| 609 |
+
.venv/lib/python3.12/site-packages/torch/test/MaybeOwned_test filter=lfs diff=lfs merge=lfs -text
|
| 610 |
+
.venv/lib/python3.12/site-packages/torch/test/StorageUtils_test filter=lfs diff=lfs merge=lfs -text
|
| 611 |
+
.venv/lib/python3.12/site-packages/torch/test/accelerator_graph_test filter=lfs diff=lfs merge=lfs -text
|
| 612 |
+
.venv/lib/python3.12/site-packages/torch/test/apply_utils_test filter=lfs diff=lfs merge=lfs -text
|
| 613 |
+
.venv/lib/python3.12/site-packages/torch/test/atest filter=lfs diff=lfs merge=lfs -text
|
| 614 |
+
.venv/lib/python3.12/site-packages/torch/test/backend_fallback_test filter=lfs diff=lfs merge=lfs -text
|
| 615 |
+
.venv/lib/python3.12/site-packages/torch/test/basic filter=lfs diff=lfs merge=lfs -text
|
| 616 |
+
.venv/lib/python3.12/site-packages/torch/test/broadcast_test filter=lfs diff=lfs merge=lfs -text
|
| 617 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_AllocatorConfig_test filter=lfs diff=lfs merge=lfs -text
|
| 618 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ArrayRef_test filter=lfs diff=lfs merge=lfs -text
|
| 619 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Bitset_test filter=lfs diff=lfs merge=lfs -text
|
| 620 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_CompileTimeFunctionPointer_test filter=lfs diff=lfs merge=lfs -text
|
| 621 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ConstexprCrc_test filter=lfs diff=lfs merge=lfs -text
|
| 622 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_DeadlockDetection_test filter=lfs diff=lfs merge=lfs -text
|
| 623 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_DeviceGuard_test filter=lfs diff=lfs merge=lfs -text
|
| 624 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Device_test filter=lfs diff=lfs merge=lfs -text
|
| 625 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_DispatchKeySet_test filter=lfs diff=lfs merge=lfs -text
|
| 626 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Enumerate_test filter=lfs diff=lfs merge=lfs -text
|
| 627 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Half_test filter=lfs diff=lfs merge=lfs -text
|
| 628 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_InlineDeviceGuard_test filter=lfs diff=lfs merge=lfs -text
|
| 629 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_InlineStreamGuard_test filter=lfs diff=lfs merge=lfs -text
|
| 630 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_IntrusiveList_test filter=lfs diff=lfs merge=lfs -text
|
| 631 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_LeftRight_test filter=lfs diff=lfs merge=lfs -text
|
| 632 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_NetworkFlow_test filter=lfs diff=lfs merge=lfs -text
|
| 633 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Scalar_test filter=lfs diff=lfs merge=lfs -text
|
| 634 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Semaphore_test filter=lfs diff=lfs merge=lfs -text
|
| 635 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_SizesAndStrides_test filter=lfs diff=lfs merge=lfs -text
|
| 636 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_StreamGuard_test filter=lfs diff=lfs merge=lfs -text
|
| 637 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_SymInt_test filter=lfs diff=lfs merge=lfs -text
|
| 638 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_Synchronized_test filter=lfs diff=lfs merge=lfs -text
|
| 639 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ThreadLocalDebugInfo_test filter=lfs diff=lfs merge=lfs -text
|
| 640 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ThreadLocal_test filter=lfs diff=lfs merge=lfs -text
|
| 641 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_TypeIndex_test filter=lfs diff=lfs merge=lfs -text
|
| 642 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_TypeSafeSignMath_test filter=lfs diff=lfs merge=lfs -text
|
| 643 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_WaitCounter_test filter=lfs diff=lfs merge=lfs -text
|
| 644 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_accumulate_test filter=lfs diff=lfs merge=lfs -text
|
| 645 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_bfloat16_test filter=lfs diff=lfs merge=lfs -text
|
| 646 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_bit_cast_test filter=lfs diff=lfs merge=lfs -text
|
| 647 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_complex_math_test filter=lfs diff=lfs merge=lfs -text
|
| 648 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_complex_test filter=lfs diff=lfs merge=lfs -text
|
| 649 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_cow_test filter=lfs diff=lfs merge=lfs -text
|
| 650 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_error_test filter=lfs diff=lfs merge=lfs -text
|
| 651 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_exception_test filter=lfs diff=lfs merge=lfs -text
|
| 652 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_flags_test filter=lfs diff=lfs merge=lfs -text
|
| 653 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_generic_math_test filter=lfs diff=lfs merge=lfs -text
|
| 654 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_intrusive_ptr_benchmark filter=lfs diff=lfs merge=lfs -text
|
| 655 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_intrusive_ptr_test filter=lfs diff=lfs merge=lfs -text
|
| 656 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_irange_test filter=lfs diff=lfs merge=lfs -text
|
| 657 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_lazy_test filter=lfs diff=lfs merge=lfs -text
|
| 658 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_logging_test filter=lfs diff=lfs merge=lfs -text
|
| 659 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_nofatal_test filter=lfs diff=lfs merge=lfs -text
|
| 660 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_optional_test filter=lfs diff=lfs merge=lfs -text
|
| 661 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ordered_preserving_dict_test filter=lfs diff=lfs merge=lfs -text
|
| 662 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_overflows_test filter=lfs diff=lfs merge=lfs -text
|
| 663 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_registry_test filter=lfs diff=lfs merge=lfs -text
|
| 664 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_safe_conv_test filter=lfs diff=lfs merge=lfs -text
|
| 665 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_small_vector_test filter=lfs diff=lfs merge=lfs -text
|
| 666 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_ssize_test filter=lfs diff=lfs merge=lfs -text
|
| 667 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_string_util_test filter=lfs diff=lfs merge=lfs -text
|
| 668 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_string_view_test filter=lfs diff=lfs merge=lfs -text
|
| 669 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_tempfile_test filter=lfs diff=lfs merge=lfs -text
|
| 670 |
+
.venv/lib/python3.12/site-packages/torch/test/c10_typeid_test filter=lfs diff=lfs merge=lfs -text
|
| 671 |
+
.venv/lib/python3.12/site-packages/torch/test/cpu_allocator_test filter=lfs diff=lfs merge=lfs -text
|
| 672 |
+
.venv/lib/python3.12/site-packages/torch/test/cpu_generator_test filter=lfs diff=lfs merge=lfs -text
|
| 673 |
+
.venv/lib/python3.12/site-packages/torch/test/cpu_profiling_allocator_test filter=lfs diff=lfs merge=lfs -text
|
| 674 |
+
.venv/lib/python3.12/site-packages/torch/test/cpu_rng_test filter=lfs diff=lfs merge=lfs -text
|
| 675 |
+
.venv/lib/python3.12/site-packages/torch/test/dlconvertor_test filter=lfs diff=lfs merge=lfs -text
|
| 676 |
+
.venv/lib/python3.12/site-packages/torch/test/extension_backend_test filter=lfs diff=lfs merge=lfs -text
|
| 677 |
+
.venv/lib/python3.12/site-packages/torch/test/half_test filter=lfs diff=lfs merge=lfs -text
|
| 678 |
+
.venv/lib/python3.12/site-packages/torch/test/index_kernel_utils_test filter=lfs diff=lfs merge=lfs -text
|
| 679 |
+
.venv/lib/python3.12/site-packages/torch/test/inline_container_test filter=lfs diff=lfs merge=lfs -text
|
| 680 |
+
.venv/lib/python3.12/site-packages/torch/test/ivalue_test filter=lfs diff=lfs merge=lfs -text
|
| 681 |
+
.venv/lib/python3.12/site-packages/torch/test/kernel_function_legacy_test filter=lfs diff=lfs merge=lfs -text
|
| 682 |
+
.venv/lib/python3.12/site-packages/torch/test/kernel_function_test filter=lfs diff=lfs merge=lfs -text
|
| 683 |
+
.venv/lib/python3.12/site-packages/torch/test/kernel_lambda_legacy_test filter=lfs diff=lfs merge=lfs -text
|
| 684 |
+
.venv/lib/python3.12/site-packages/torch/test/kernel_lambda_test filter=lfs diff=lfs merge=lfs -text
|
| 685 |
+
.venv/lib/python3.12/site-packages/torch/test/kernel_stackbased_test filter=lfs diff=lfs merge=lfs -text
|
| 686 |
+
.venv/lib/python3.12/site-packages/torch/test/lazy_tensor_test filter=lfs diff=lfs merge=lfs -text
|
| 687 |
+
.venv/lib/python3.12/site-packages/torch/test/legacy_vmap_test filter=lfs diff=lfs merge=lfs -text
|
| 688 |
+
.venv/lib/python3.12/site-packages/torch/test/make_boxed_from_unboxed_functor_test filter=lfs diff=lfs merge=lfs -text
|
| 689 |
+
.venv/lib/python3.12/site-packages/torch/test/math_kernel_test filter=lfs diff=lfs merge=lfs -text
|
| 690 |
+
.venv/lib/python3.12/site-packages/torch/test/memory_format_test filter=lfs diff=lfs merge=lfs -text
|
| 691 |
+
.venv/lib/python3.12/site-packages/torch/test/memory_overlapping_test filter=lfs diff=lfs merge=lfs -text
|
| 692 |
+
.venv/lib/python3.12/site-packages/torch/test/mobile_memory_cleanup filter=lfs diff=lfs merge=lfs -text
|
| 693 |
+
.venv/lib/python3.12/site-packages/torch/test/native_test filter=lfs diff=lfs merge=lfs -text
|
| 694 |
+
.venv/lib/python3.12/site-packages/torch/test/op_allowlist_test filter=lfs diff=lfs merge=lfs -text
|
| 695 |
+
.venv/lib/python3.12/site-packages/torch/test/op_registration_test filter=lfs diff=lfs merge=lfs -text
|
| 696 |
+
.venv/lib/python3.12/site-packages/torch/test/operator_name_test filter=lfs diff=lfs merge=lfs -text
|
| 697 |
+
.venv/lib/python3.12/site-packages/torch/test/operators_test filter=lfs diff=lfs merge=lfs -text
|
| 698 |
+
.venv/lib/python3.12/site-packages/torch/test/packedtensoraccessor_test filter=lfs diff=lfs merge=lfs -text
|
| 699 |
+
.venv/lib/python3.12/site-packages/torch/test/pow_test filter=lfs diff=lfs merge=lfs -text
|
| 700 |
+
.venv/lib/python3.12/site-packages/torch/test/quantized_test filter=lfs diff=lfs merge=lfs -text
|
| 701 |
+
.venv/lib/python3.12/site-packages/torch/test/reduce_ops_test filter=lfs diff=lfs merge=lfs -text
|
| 702 |
+
.venv/lib/python3.12/site-packages/torch/test/reportMemoryUsage_test filter=lfs diff=lfs merge=lfs -text
|
| 703 |
+
.venv/lib/python3.12/site-packages/torch/test/scalar_tensor_test filter=lfs diff=lfs merge=lfs -text
|
| 704 |
+
.venv/lib/python3.12/site-packages/torch/test/scalar_test filter=lfs diff=lfs merge=lfs -text
|
| 705 |
+
.venv/lib/python3.12/site-packages/torch/test/stride_properties_test filter=lfs diff=lfs merge=lfs -text
|
| 706 |
+
.venv/lib/python3.12/site-packages/torch/test/tensor_iterator_test filter=lfs diff=lfs merge=lfs -text
|
| 707 |
+
.venv/lib/python3.12/site-packages/torch/test/test_parallel filter=lfs diff=lfs merge=lfs -text
|
| 708 |
+
.venv/lib/python3.12/site-packages/torch/test/thread_init_test filter=lfs diff=lfs merge=lfs -text
|
| 709 |
+
.venv/lib/python3.12/site-packages/torch/test/type_ptr_test filter=lfs diff=lfs merge=lfs -text
|
| 710 |
+
.venv/lib/python3.12/site-packages/torch/test/type_test filter=lfs diff=lfs merge=lfs -text
|
| 711 |
+
.venv/lib/python3.12/site-packages/torch/test/undefined_tensor_test filter=lfs diff=lfs merge=lfs -text
|
| 712 |
+
.venv/lib/python3.12/site-packages/torch/test/verify_api_visibility filter=lfs diff=lfs merge=lfs -text
|
| 713 |
+
.venv/lib/python3.12/site-packages/torch/test/weakref_test filter=lfs diff=lfs merge=lfs -text
|
| 714 |
+
.venv/lib/python3.12/site-packages/torch/test/wrapdim_test filter=lfs diff=lfs merge=lfs -text
|
| 715 |
+
.venv/lib/python3.12/site-packages/torch/test/xla_tensor_test filter=lfs diff=lfs merge=lfs -text
|
| 716 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 717 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_methods_invocations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 718 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_modules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 719 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_nn.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 720 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 721 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 722 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/__pycache__/distributed_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 723 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/dist_autograd_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 724 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 725 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 726 |
+
.venv/lib/python3.12/site-packages/torch/testing/_internal/opinfo/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/_functions.cpython-312.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/activation.cpython-312.pyc
ADDED
|
Binary file (71.8 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/adaptive.cpython-312.pyc
ADDED
|
Binary file (15.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/batchnorm.cpython-312.pyc
ADDED
|
Binary file (41.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/channelshuffle.cpython-312.pyc
ADDED
|
Binary file (2.58 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/container.cpython-312.pyc
ADDED
|
Binary file (50.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/conv.cpython-312.pyc
ADDED
|
Binary file (75.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/distance.cpython-312.pyc
ADDED
|
Binary file (4.71 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/dropout.cpython-312.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/flatten.cpython-312.pyc
ADDED
|
Binary file (5.91 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/fold.cpython-312.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/instancenorm.cpython-312.pyc
ADDED
|
Binary file (24.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/lazy.cpython-312.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear.cpython-312.pyc
ADDED
|
Binary file (14.5 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear_cross_entropy.cpython-312.pyc
ADDED
|
Binary file (52.4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/linear_cross_entropy_options.cpython-312.pyc
ADDED
|
Binary file (9.82 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/loss.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2545030c3ad785f04b63bb6e97c84fed6c397190d088a0f9607478876375d2a3
|
| 3 |
+
size 114133
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/module.cpython-312.pyc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2eea810171cba4fe1110ef06256c9c736c100a416e289567f54aeefb7b63f7cf
|
| 3 |
+
size 130182
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/normalization.cpython-312.pyc
ADDED
|
Binary file (19.3 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/padding.cpython-312.pyc
ADDED
|
Binary file (38 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/pixelshuffle.cpython-312.pyc
ADDED
|
Binary file (5.12 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/pooling.cpython-312.pyc
ADDED
|
Binary file (67.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/rnn.cpython-312.pyc
ADDED
|
Binary file (76.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/sparse.cpython-312.pyc
ADDED
|
Binary file (25.1 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/transformer.cpython-312.pyc
ADDED
|
Binary file (53.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/upsampling.cpython-312.pyc
ADDED
|
Binary file (13.2 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/utils.cpython-312.pyc
ADDED
|
Binary file (3.9 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/_functions.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|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|
| 9 |
+
# pyrefly: ignore [bad-override]
|
| 10 |
+
def forward(
|
| 11 |
+
self,
|
| 12 |
+
input,
|
| 13 |
+
weight,
|
| 14 |
+
bias,
|
| 15 |
+
running_mean,
|
| 16 |
+
running_var,
|
| 17 |
+
eps,
|
| 18 |
+
momentum,
|
| 19 |
+
process_group,
|
| 20 |
+
world_size,
|
| 21 |
+
):
|
| 22 |
+
if not (
|
| 23 |
+
input.is_contiguous(memory_format=torch.channels_last)
|
| 24 |
+
or input.is_contiguous(memory_format=torch.channels_last_3d)
|
| 25 |
+
):
|
| 26 |
+
input = input.contiguous()
|
| 27 |
+
if weight is not None:
|
| 28 |
+
weight = weight.contiguous()
|
| 29 |
+
|
| 30 |
+
size = int(input.numel() // input.size(1))
|
| 31 |
+
if size == 1 and world_size < 2:
|
| 32 |
+
raise ValueError(
|
| 33 |
+
f"Expected more than 1 value per channel when training, got input size {size}"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
num_channels = input.shape[1]
|
| 37 |
+
if input.numel() > 0:
|
| 38 |
+
# calculate mean/invstd for input.
|
| 39 |
+
mean, invstd = torch.batch_norm_stats(input, eps)
|
| 40 |
+
|
| 41 |
+
count = torch.full(
|
| 42 |
+
(1,),
|
| 43 |
+
input.numel() // input.size(1),
|
| 44 |
+
dtype=mean.dtype,
|
| 45 |
+
device=mean.device,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# C, C, 1 -> (2C + 1)
|
| 49 |
+
combined = torch.cat([mean, invstd, count], dim=0)
|
| 50 |
+
else:
|
| 51 |
+
# for empty input, set stats and the count to zero. The stats with
|
| 52 |
+
# zero count will be filtered out later when computing global mean
|
| 53 |
+
# & invstd, but they still needs to participate the all_gather
|
| 54 |
+
# collective communication to unblock other peer processes.
|
| 55 |
+
combined = torch.zeros(
|
| 56 |
+
2 * num_channels + 1, dtype=input.dtype, device=input.device
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
# Use allgather instead of allreduce because count could be different across
|
| 60 |
+
# ranks, simple all reduce op can not give correct results.
|
| 61 |
+
# batch_norm_gather_stats_with_counts calculates global mean & invstd based on
|
| 62 |
+
# all gathered mean, invstd and count.
|
| 63 |
+
# for nccl backend, use the optimized version of all gather.
|
| 64 |
+
# The Gloo backend does not support `all_gather_into_tensor`.
|
| 65 |
+
if process_group._get_backend_name() != "gloo":
|
| 66 |
+
# world_size * (2C + 1)
|
| 67 |
+
combined_size = combined.numel()
|
| 68 |
+
combined_flat = torch.empty(
|
| 69 |
+
1,
|
| 70 |
+
combined_size * world_size,
|
| 71 |
+
dtype=combined.dtype,
|
| 72 |
+
device=combined.device,
|
| 73 |
+
)
|
| 74 |
+
dist.all_gather_single(
|
| 75 |
+
combined_flat, combined, process_group, async_op=False
|
| 76 |
+
)
|
| 77 |
+
combined = torch.reshape(combined_flat, (world_size, combined_size))
|
| 78 |
+
# world_size * (2C + 1) -> world_size * C, world_size * C, world_size * 1
|
| 79 |
+
mean_all, invstd_all, count_all = torch.split(combined, num_channels, dim=1)
|
| 80 |
+
else:
|
| 81 |
+
# world_size * (2C + 1)
|
| 82 |
+
combined_list = [torch.empty_like(combined) for _ in range(world_size)]
|
| 83 |
+
dist.all_gather(combined_list, combined, process_group, async_op=False)
|
| 84 |
+
combined = torch.stack(combined_list, dim=0)
|
| 85 |
+
# world_size * (2C + 1) -> world_size * C, world_size * C, world_size * 1
|
| 86 |
+
mean_all, invstd_all, count_all = torch.split(combined, num_channels, dim=1)
|
| 87 |
+
|
| 88 |
+
if not (torch.cuda.is_available() and torch.cuda.is_current_stream_capturing()):
|
| 89 |
+
# The lines below force a synchronization between CUDA and CPU, because
|
| 90 |
+
# the shape of the result count_all depends on the values in mask tensor.
|
| 91 |
+
# Such synchronizations break CUDA Graph capturing.
|
| 92 |
+
# See https://github.com/pytorch/pytorch/issues/78549
|
| 93 |
+
# FIXME: https://github.com/pytorch/pytorch/issues/78656 describes
|
| 94 |
+
# a better longer-term solution.
|
| 95 |
+
|
| 96 |
+
# remove stats from empty inputs
|
| 97 |
+
mask = count_all.squeeze(-1) >= 1
|
| 98 |
+
count_all = count_all[mask]
|
| 99 |
+
mean_all = mean_all[mask]
|
| 100 |
+
invstd_all = invstd_all[mask]
|
| 101 |
+
|
| 102 |
+
# calculate global mean & invstd
|
| 103 |
+
counts = count_all.view(-1)
|
| 104 |
+
if running_mean is not None and counts.dtype != running_mean.dtype:
|
| 105 |
+
counts = counts.to(running_mean.dtype)
|
| 106 |
+
mean, invstd = torch.batch_norm_gather_stats_with_counts(
|
| 107 |
+
input,
|
| 108 |
+
mean_all,
|
| 109 |
+
invstd_all,
|
| 110 |
+
running_mean,
|
| 111 |
+
running_var,
|
| 112 |
+
momentum,
|
| 113 |
+
eps,
|
| 114 |
+
counts,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
self.save_for_backward(input, weight, mean, invstd, count_all.to(torch.int32))
|
| 118 |
+
self.process_group = process_group
|
| 119 |
+
|
| 120 |
+
# apply element-wise normalization
|
| 121 |
+
if input.numel() > 0:
|
| 122 |
+
return torch.batch_norm_elemt(input, weight, bias, mean, invstd, eps)
|
| 123 |
+
else:
|
| 124 |
+
return torch.empty_like(input)
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
# pyrefly: ignore [bad-override]
|
| 128 |
+
def backward(self, grad_output):
|
| 129 |
+
if not (
|
| 130 |
+
grad_output.is_contiguous(memory_format=torch.channels_last)
|
| 131 |
+
or grad_output.is_contiguous(memory_format=torch.channels_last_3d)
|
| 132 |
+
):
|
| 133 |
+
grad_output = grad_output.contiguous()
|
| 134 |
+
saved_input, weight, mean, invstd, count_tensor = self.saved_tensors
|
| 135 |
+
grad_input = grad_weight = grad_bias = None
|
| 136 |
+
process_group = self.process_group
|
| 137 |
+
|
| 138 |
+
if saved_input.numel() > 0:
|
| 139 |
+
# calculate local stats as well as grad_weight / grad_bias
|
| 140 |
+
(
|
| 141 |
+
sum_dy,
|
| 142 |
+
sum_dy_xmu,
|
| 143 |
+
grad_weight,
|
| 144 |
+
grad_bias,
|
| 145 |
+
) = torch.batch_norm_backward_reduce(
|
| 146 |
+
grad_output,
|
| 147 |
+
saved_input,
|
| 148 |
+
mean,
|
| 149 |
+
invstd,
|
| 150 |
+
weight,
|
| 151 |
+
self.needs_input_grad[0],
|
| 152 |
+
self.needs_input_grad[1],
|
| 153 |
+
self.needs_input_grad[2],
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
if self.needs_input_grad[0]:
|
| 157 |
+
# synchronizing stats used to calculate input gradient.
|
| 158 |
+
num_channels = sum_dy.shape[0]
|
| 159 |
+
combined = torch.cat([sum_dy, sum_dy_xmu], dim=0)
|
| 160 |
+
torch.distributed.all_reduce(
|
| 161 |
+
combined,
|
| 162 |
+
torch.distributed.ReduceOp.SUM,
|
| 163 |
+
process_group,
|
| 164 |
+
async_op=False,
|
| 165 |
+
)
|
| 166 |
+
sum_dy, sum_dy_xmu = torch.split(combined, num_channels)
|
| 167 |
+
|
| 168 |
+
# backward pass for gradient calculation
|
| 169 |
+
if weight is not None and weight.dtype != mean.dtype:
|
| 170 |
+
weight = weight.to(mean.dtype)
|
| 171 |
+
grad_input = torch.batch_norm_backward_elemt(
|
| 172 |
+
grad_output,
|
| 173 |
+
saved_input,
|
| 174 |
+
mean,
|
| 175 |
+
invstd,
|
| 176 |
+
weight,
|
| 177 |
+
sum_dy,
|
| 178 |
+
sum_dy_xmu,
|
| 179 |
+
count_tensor,
|
| 180 |
+
)
|
| 181 |
+
# synchronizing of grad_weight / grad_bias is not needed as distributed
|
| 182 |
+
# training would handle all reduce.
|
| 183 |
+
if weight is None or not self.needs_input_grad[1]:
|
| 184 |
+
grad_weight = None
|
| 185 |
+
|
| 186 |
+
if weight is None or not self.needs_input_grad[2]:
|
| 187 |
+
grad_bias = None
|
| 188 |
+
else:
|
| 189 |
+
# This process got an empty input tensor in the forward pass.
|
| 190 |
+
# Although this process can directly set grad_input as an empty
|
| 191 |
+
# tensor of zeros, it still needs to participate in the collective
|
| 192 |
+
# communication to unblock its peers, as other peer processes might
|
| 193 |
+
# have received non-empty inputs.
|
| 194 |
+
num_channels = saved_input.shape[1]
|
| 195 |
+
if self.needs_input_grad[0]:
|
| 196 |
+
# launch all_reduce to unblock other peer processes
|
| 197 |
+
combined = torch.zeros(
|
| 198 |
+
2 * num_channels, dtype=saved_input.dtype, device=saved_input.device
|
| 199 |
+
)
|
| 200 |
+
torch.distributed.all_reduce(
|
| 201 |
+
combined,
|
| 202 |
+
torch.distributed.ReduceOp.SUM,
|
| 203 |
+
process_group,
|
| 204 |
+
async_op=False,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Leave grad_input, grad_weight and grad_bias as None, which will be
|
| 208 |
+
# interpreted by the autograd engine as Tensors full of zeros.
|
| 209 |
+
|
| 210 |
+
return grad_input, grad_weight, grad_bias, None, None, None, None, None, None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class CrossMapLRN2d(Function):
|
| 214 |
+
@staticmethod
|
| 215 |
+
# pyrefly: ignore [bad-override]
|
| 216 |
+
def forward(ctx, input, size, alpha=1e-4, beta=0.75, k=1):
|
| 217 |
+
ctx.size = size
|
| 218 |
+
ctx.alpha = alpha
|
| 219 |
+
ctx.beta = beta
|
| 220 |
+
ctx.k = k
|
| 221 |
+
ctx.scale = None
|
| 222 |
+
|
| 223 |
+
if input.dim() != 4:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"CrossMapLRN2d: Expected input to be 4D, got {input.dim()}D instead."
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
ctx.scale = ctx.scale or input.new()
|
| 229 |
+
output = input.new()
|
| 230 |
+
channels = input.size(1)
|
| 231 |
+
|
| 232 |
+
output.resize_as_(input)
|
| 233 |
+
ctx.scale.resize_as_(input)
|
| 234 |
+
|
| 235 |
+
# use output storage as temporary buffer
|
| 236 |
+
input_square = output
|
| 237 |
+
torch.pow(input, 2, out=input_square)
|
| 238 |
+
|
| 239 |
+
pre_pad = int((ctx.size - 1) / 2 + 1)
|
| 240 |
+
pre_pad_crop = min(pre_pad, channels)
|
| 241 |
+
|
| 242 |
+
scale_first = ctx.scale.select(1, 0)
|
| 243 |
+
scale_first.zero_()
|
| 244 |
+
# compute first feature map normalization
|
| 245 |
+
for c in range(pre_pad_crop):
|
| 246 |
+
scale_first.add_(input_square.select(1, c))
|
| 247 |
+
|
| 248 |
+
# reuse computations for next feature maps normalization
|
| 249 |
+
# by adding the next feature map and removing the previous
|
| 250 |
+
for c in range(1, channels):
|
| 251 |
+
scale_previous = ctx.scale.select(1, c - 1)
|
| 252 |
+
scale_current = ctx.scale.select(1, c)
|
| 253 |
+
scale_current.copy_(scale_previous)
|
| 254 |
+
if c < channels - pre_pad + 1:
|
| 255 |
+
square_next = input_square.select(1, c + pre_pad - 1)
|
| 256 |
+
scale_current.add_(square_next, alpha=1)
|
| 257 |
+
|
| 258 |
+
if c > pre_pad:
|
| 259 |
+
square_previous = input_square.select(1, c - pre_pad)
|
| 260 |
+
scale_current.add_(square_previous, alpha=-1)
|
| 261 |
+
|
| 262 |
+
ctx.scale.mul_(ctx.alpha / ctx.size).add_(ctx.k)
|
| 263 |
+
|
| 264 |
+
torch.pow(ctx.scale, -ctx.beta, out=output)
|
| 265 |
+
output.mul_(input)
|
| 266 |
+
|
| 267 |
+
ctx.save_for_backward(input, output)
|
| 268 |
+
return output
|
| 269 |
+
|
| 270 |
+
@staticmethod
|
| 271 |
+
# pyrefly: ignore [bad-override]
|
| 272 |
+
def backward(ctx, grad_output):
|
| 273 |
+
input, output = ctx.saved_tensors
|
| 274 |
+
grad_input = grad_output.new()
|
| 275 |
+
|
| 276 |
+
batch_size = input.size(0)
|
| 277 |
+
channels = input.size(1)
|
| 278 |
+
input_height = input.size(2)
|
| 279 |
+
input_width = input.size(3)
|
| 280 |
+
|
| 281 |
+
paddded_ratio = input.new(channels + ctx.size - 1, input_height, input_width)
|
| 282 |
+
accum_ratio = input.new(input_height, input_width)
|
| 283 |
+
|
| 284 |
+
cache_ratio_value = 2 * ctx.alpha * ctx.beta / ctx.size
|
| 285 |
+
inversePrePad = int(ctx.size - (ctx.size - 1) / 2)
|
| 286 |
+
|
| 287 |
+
grad_input.resize_as_(input)
|
| 288 |
+
torch.pow(ctx.scale, -ctx.beta, out=grad_input).mul_(grad_output)
|
| 289 |
+
|
| 290 |
+
paddded_ratio.zero_()
|
| 291 |
+
padded_ratio_center = paddded_ratio.narrow(0, inversePrePad, channels)
|
| 292 |
+
for n in range(batch_size):
|
| 293 |
+
torch.mul(grad_output[n], output[n], out=padded_ratio_center)
|
| 294 |
+
padded_ratio_center.div_(ctx.scale[n])
|
| 295 |
+
torch.sum(
|
| 296 |
+
paddded_ratio.narrow(0, 0, ctx.size - 1),
|
| 297 |
+
0,
|
| 298 |
+
keepdim=False,
|
| 299 |
+
out=accum_ratio,
|
| 300 |
+
)
|
| 301 |
+
for c in range(channels):
|
| 302 |
+
accum_ratio.add_(paddded_ratio[c + ctx.size - 1])
|
| 303 |
+
grad_input[n][c].addcmul_(
|
| 304 |
+
input[n][c], accum_ratio, value=-cache_ratio_value
|
| 305 |
+
)
|
| 306 |
+
accum_ratio.add_(paddded_ratio[c], alpha=-1)
|
| 307 |
+
|
| 308 |
+
return grad_input, None, None, None, None
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class BackwardHookFunction(torch.autograd.Function):
|
| 312 |
+
@staticmethod
|
| 313 |
+
# pyrefly: ignore [bad-override]
|
| 314 |
+
def forward(ctx, *args):
|
| 315 |
+
ctx.mark_non_differentiable(*[arg for arg in args if not arg.requires_grad])
|
| 316 |
+
return args
|
| 317 |
+
|
| 318 |
+
@staticmethod
|
| 319 |
+
def backward(ctx, *args):
|
| 320 |
+
return args
|
.venv/lib/python3.12/site-packages/torch/nn/modules/activation.py
ADDED
|
@@ -0,0 +1,1917 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
|
| 8 |
+
from torch.nn.parameter import Parameter
|
| 9 |
+
|
| 10 |
+
from .linear import NonDynamicallyQuantizableLinear
|
| 11 |
+
from .module import Module
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"Threshold",
|
| 16 |
+
"ReLU",
|
| 17 |
+
"RReLU",
|
| 18 |
+
"Hardtanh",
|
| 19 |
+
"ReLU6",
|
| 20 |
+
"Sigmoid",
|
| 21 |
+
"Hardsigmoid",
|
| 22 |
+
"Tanh",
|
| 23 |
+
"SiLU",
|
| 24 |
+
"Mish",
|
| 25 |
+
"Hardswish",
|
| 26 |
+
"ELU",
|
| 27 |
+
"CELU",
|
| 28 |
+
"SELU",
|
| 29 |
+
"GLU",
|
| 30 |
+
"GELU",
|
| 31 |
+
"Hardshrink",
|
| 32 |
+
"LeakyReLU",
|
| 33 |
+
"LogSigmoid",
|
| 34 |
+
"Softplus",
|
| 35 |
+
"Softshrink",
|
| 36 |
+
"MultiheadAttention",
|
| 37 |
+
"PReLU",
|
| 38 |
+
"Softsign",
|
| 39 |
+
"Tanhshrink",
|
| 40 |
+
"Softmin",
|
| 41 |
+
"Softmax",
|
| 42 |
+
"Softmax2d",
|
| 43 |
+
"LogSoftmax",
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class Threshold(Module):
|
| 48 |
+
r"""Thresholds each element of the input Tensor.
|
| 49 |
+
|
| 50 |
+
Threshold is defined as:
|
| 51 |
+
|
| 52 |
+
.. math::
|
| 53 |
+
y =
|
| 54 |
+
\begin{cases}
|
| 55 |
+
x, &\text{ if } x > \text{threshold} \\
|
| 56 |
+
\text{value}, &\text{ otherwise }
|
| 57 |
+
\end{cases}
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
threshold: The value to threshold at
|
| 61 |
+
value: The value to replace with
|
| 62 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 63 |
+
|
| 64 |
+
Shape:
|
| 65 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 66 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 67 |
+
|
| 68 |
+
.. image:: ../scripts/activation_images/Threshold.png
|
| 69 |
+
|
| 70 |
+
Examples::
|
| 71 |
+
|
| 72 |
+
>>> m = nn.Threshold(0, 0.5)
|
| 73 |
+
>>> input = torch.arange(-3, 3)
|
| 74 |
+
>>> output = m(input)
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
__constants__ = ["threshold", "value", "inplace"]
|
| 78 |
+
|
| 79 |
+
threshold: float
|
| 80 |
+
value: float
|
| 81 |
+
inplace: bool
|
| 82 |
+
|
| 83 |
+
def __init__(self, threshold: float, value: float, inplace: bool = False) -> None:
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.threshold = threshold
|
| 86 |
+
self.value = value
|
| 87 |
+
self.inplace = inplace
|
| 88 |
+
# TODO: check in THNN (if inplace == True, then assert value <= threshold)
|
| 89 |
+
|
| 90 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 91 |
+
"""
|
| 92 |
+
Runs the forward pass.
|
| 93 |
+
"""
|
| 94 |
+
return F.threshold(input, self.threshold, self.value, self.inplace)
|
| 95 |
+
|
| 96 |
+
def extra_repr(self) -> str:
|
| 97 |
+
"""
|
| 98 |
+
Return the extra representation of the module.
|
| 99 |
+
"""
|
| 100 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 101 |
+
return f"threshold={self.threshold}, value={self.value}{inplace_str}"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class ReLU(Module):
|
| 105 |
+
r"""Applies the rectified linear unit function element-wise.
|
| 106 |
+
|
| 107 |
+
:math:`\text{ReLU}(x) = (x)^+ = \max(0, x)`
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 111 |
+
|
| 112 |
+
Shape:
|
| 113 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 114 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 115 |
+
|
| 116 |
+
.. image:: ../scripts/activation_images/ReLU.png
|
| 117 |
+
|
| 118 |
+
Examples::
|
| 119 |
+
|
| 120 |
+
>>> m = nn.ReLU()
|
| 121 |
+
>>> input = torch.randn(2)
|
| 122 |
+
>>> output = m(input)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
An implementation of CReLU - https://arxiv.org/abs/1603.05201
|
| 126 |
+
|
| 127 |
+
>>> m = nn.ReLU()
|
| 128 |
+
>>> input = torch.randn(2).unsqueeze(0)
|
| 129 |
+
>>> output = torch.cat((m(input), m(-input)))
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
__constants__ = ["inplace"]
|
| 133 |
+
inplace: bool
|
| 134 |
+
|
| 135 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.inplace = inplace
|
| 138 |
+
|
| 139 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 140 |
+
"""
|
| 141 |
+
Runs the forward pass.
|
| 142 |
+
"""
|
| 143 |
+
return F.relu(input, inplace=self.inplace)
|
| 144 |
+
|
| 145 |
+
def extra_repr(self) -> str:
|
| 146 |
+
"""
|
| 147 |
+
Return the extra representation of the module.
|
| 148 |
+
"""
|
| 149 |
+
inplace_str = "inplace=True" if self.inplace else ""
|
| 150 |
+
return inplace_str
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class RReLU(Module):
|
| 154 |
+
r"""Applies the randomized leaky rectified linear unit function, element-wise.
|
| 155 |
+
|
| 156 |
+
Method described in the paper:
|
| 157 |
+
`Empirical Evaluation of Rectified Activations in Convolutional Network <https://arxiv.org/abs/1505.00853>`_.
|
| 158 |
+
|
| 159 |
+
The function is defined as:
|
| 160 |
+
|
| 161 |
+
.. math::
|
| 162 |
+
\text{RReLU}(x) =
|
| 163 |
+
\begin{cases}
|
| 164 |
+
x & \text{if } x \geq 0 \\
|
| 165 |
+
ax & \text{ otherwise }
|
| 166 |
+
\end{cases}
|
| 167 |
+
|
| 168 |
+
where :math:`a` is randomly sampled from uniform distribution
|
| 169 |
+
:math:`\mathcal{U}(\text{lower}, \text{upper})` during training while during
|
| 170 |
+
evaluation :math:`a` is fixed with :math:`a = \frac{\text{lower} + \text{upper}}{2}`.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
lower: lower bound of the uniform distribution. Default: :math:`\frac{1}{8}`
|
| 174 |
+
upper: upper bound of the uniform distribution. Default: :math:`\frac{1}{3}`
|
| 175 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 176 |
+
|
| 177 |
+
Shape:
|
| 178 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 179 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 180 |
+
|
| 181 |
+
.. image:: ../scripts/activation_images/RReLU.png
|
| 182 |
+
|
| 183 |
+
Examples::
|
| 184 |
+
|
| 185 |
+
>>> m = nn.RReLU(0.1, 0.3)
|
| 186 |
+
>>> input = torch.randn(2)
|
| 187 |
+
>>> output = m(input)
|
| 188 |
+
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
__constants__ = ["lower", "upper", "inplace"]
|
| 192 |
+
|
| 193 |
+
lower: float
|
| 194 |
+
upper: float
|
| 195 |
+
inplace: bool
|
| 196 |
+
|
| 197 |
+
def __init__(
|
| 198 |
+
self, lower: float = 1.0 / 8, upper: float = 1.0 / 3, inplace: bool = False
|
| 199 |
+
) -> None:
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.lower = lower
|
| 202 |
+
self.upper = upper
|
| 203 |
+
self.inplace = inplace
|
| 204 |
+
|
| 205 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 206 |
+
"""
|
| 207 |
+
Runs the forward pass.
|
| 208 |
+
"""
|
| 209 |
+
return F.rrelu(input, self.lower, self.upper, self.training, self.inplace)
|
| 210 |
+
|
| 211 |
+
def extra_repr(self) -> str:
|
| 212 |
+
"""
|
| 213 |
+
Return the extra representation of the module.
|
| 214 |
+
"""
|
| 215 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 216 |
+
return f"lower={self.lower}, upper={self.upper}{inplace_str}"
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class Hardtanh(Module):
|
| 220 |
+
r"""Applies the HardTanh function element-wise.
|
| 221 |
+
|
| 222 |
+
HardTanh is defined as:
|
| 223 |
+
|
| 224 |
+
.. math::
|
| 225 |
+
\text{HardTanh}(x) = \begin{cases}
|
| 226 |
+
\text{max\_val} & \text{ if } x > \text{ max\_val } \\
|
| 227 |
+
\text{min\_val} & \text{ if } x < \text{ min\_val } \\
|
| 228 |
+
x & \text{ otherwise } \\
|
| 229 |
+
\end{cases}
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
min_val: minimum value of the linear region range. Default: -1
|
| 233 |
+
max_val: maximum value of the linear region range. Default: 1
|
| 234 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 235 |
+
|
| 236 |
+
Keyword arguments :attr:`min_value` and :attr:`max_value`
|
| 237 |
+
have been deprecated in favor of :attr:`min_val` and :attr:`max_val`.
|
| 238 |
+
|
| 239 |
+
Shape:
|
| 240 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 241 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 242 |
+
|
| 243 |
+
.. image:: ../scripts/activation_images/Hardtanh.png
|
| 244 |
+
|
| 245 |
+
Examples::
|
| 246 |
+
|
| 247 |
+
>>> m = nn.Hardtanh(-2, 2)
|
| 248 |
+
>>> input = torch.randn(2)
|
| 249 |
+
>>> output = m(input)
|
| 250 |
+
"""
|
| 251 |
+
|
| 252 |
+
__constants__ = ["min_val", "max_val", "inplace"]
|
| 253 |
+
|
| 254 |
+
min_val: float
|
| 255 |
+
max_val: float
|
| 256 |
+
inplace: bool
|
| 257 |
+
|
| 258 |
+
def __init__(
|
| 259 |
+
self,
|
| 260 |
+
min_val: float = -1.0,
|
| 261 |
+
max_val: float = 1.0,
|
| 262 |
+
inplace: bool = False,
|
| 263 |
+
min_value: float | None = None,
|
| 264 |
+
max_value: float | None = None,
|
| 265 |
+
) -> None:
|
| 266 |
+
super().__init__()
|
| 267 |
+
if min_value is not None:
|
| 268 |
+
warnings.warn(
|
| 269 |
+
"keyword argument `min_value` is deprecated and renamed to `min_val`",
|
| 270 |
+
FutureWarning,
|
| 271 |
+
stacklevel=2,
|
| 272 |
+
)
|
| 273 |
+
min_val = min_value
|
| 274 |
+
if max_value is not None:
|
| 275 |
+
warnings.warn(
|
| 276 |
+
"keyword argument `max_value` is deprecated and renamed to `max_val`",
|
| 277 |
+
FutureWarning,
|
| 278 |
+
stacklevel=2,
|
| 279 |
+
)
|
| 280 |
+
max_val = max_value
|
| 281 |
+
|
| 282 |
+
self.min_val = min_val
|
| 283 |
+
self.max_val = max_val
|
| 284 |
+
self.inplace = inplace
|
| 285 |
+
if self.max_val <= self.min_val:
|
| 286 |
+
raise AssertionError(
|
| 287 |
+
f"max_val ({self.max_val}) must be greater than min_val ({self.min_val})"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 291 |
+
"""
|
| 292 |
+
Runs the forward pass.
|
| 293 |
+
"""
|
| 294 |
+
return F.hardtanh(input, self.min_val, self.max_val, self.inplace)
|
| 295 |
+
|
| 296 |
+
def extra_repr(self) -> str:
|
| 297 |
+
"""
|
| 298 |
+
Return the extra representation of the module.
|
| 299 |
+
"""
|
| 300 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 301 |
+
return f"min_val={self.min_val}, max_val={self.max_val}{inplace_str}"
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
class ReLU6(Hardtanh):
|
| 305 |
+
r"""Applies the ReLU6 function element-wise.
|
| 306 |
+
|
| 307 |
+
.. math::
|
| 308 |
+
\text{ReLU6}(x) = \min(\max(0,x), 6)
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 312 |
+
|
| 313 |
+
Shape:
|
| 314 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 315 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 316 |
+
|
| 317 |
+
.. image:: ../scripts/activation_images/ReLU6.png
|
| 318 |
+
|
| 319 |
+
Examples::
|
| 320 |
+
|
| 321 |
+
>>> m = nn.ReLU6()
|
| 322 |
+
>>> input = torch.randn(2)
|
| 323 |
+
>>> output = m(input)
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 327 |
+
super().__init__(0.0, 6.0, inplace)
|
| 328 |
+
|
| 329 |
+
def extra_repr(self) -> str:
|
| 330 |
+
"""
|
| 331 |
+
Return the extra representation of the module.
|
| 332 |
+
"""
|
| 333 |
+
inplace_str = "inplace=True" if self.inplace else ""
|
| 334 |
+
return inplace_str
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class Sigmoid(Module):
|
| 338 |
+
r"""Applies the Sigmoid function element-wise.
|
| 339 |
+
|
| 340 |
+
.. math::
|
| 341 |
+
\text{Sigmoid}(x) = \sigma(x) = \frac{1}{1 + \exp(-x)}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
Shape:
|
| 345 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 346 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 347 |
+
|
| 348 |
+
.. image:: ../scripts/activation_images/Sigmoid.png
|
| 349 |
+
|
| 350 |
+
Examples::
|
| 351 |
+
|
| 352 |
+
>>> m = nn.Sigmoid()
|
| 353 |
+
>>> input = torch.randn(2)
|
| 354 |
+
>>> output = m(input)
|
| 355 |
+
"""
|
| 356 |
+
|
| 357 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 358 |
+
"""
|
| 359 |
+
Runs the forward pass.
|
| 360 |
+
"""
|
| 361 |
+
return torch.sigmoid(input)
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class Hardsigmoid(Module):
|
| 365 |
+
r"""Applies the Hardsigmoid function element-wise.
|
| 366 |
+
|
| 367 |
+
Hardsigmoid is defined as:
|
| 368 |
+
|
| 369 |
+
.. math::
|
| 370 |
+
\text{Hardsigmoid}(x) = \begin{cases}
|
| 371 |
+
0 & \text{if~} x \le -3, \\
|
| 372 |
+
1 & \text{if~} x \ge +3, \\
|
| 373 |
+
x / 6 + 1 / 2 & \text{otherwise}
|
| 374 |
+
\end{cases}
|
| 375 |
+
|
| 376 |
+
Args:
|
| 377 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 378 |
+
|
| 379 |
+
Shape:
|
| 380 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 381 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 382 |
+
|
| 383 |
+
.. image:: ../scripts/activation_images/Hardsigmoid.png
|
| 384 |
+
|
| 385 |
+
Examples::
|
| 386 |
+
|
| 387 |
+
>>> m = nn.Hardsigmoid()
|
| 388 |
+
>>> input = torch.randn(2)
|
| 389 |
+
>>> output = m(input)
|
| 390 |
+
"""
|
| 391 |
+
|
| 392 |
+
__constants__ = ["inplace"]
|
| 393 |
+
|
| 394 |
+
inplace: bool
|
| 395 |
+
|
| 396 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 397 |
+
super().__init__()
|
| 398 |
+
self.inplace = inplace
|
| 399 |
+
|
| 400 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 401 |
+
"""
|
| 402 |
+
Runs the forward pass.
|
| 403 |
+
"""
|
| 404 |
+
return F.hardsigmoid(input, self.inplace)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class Tanh(Module):
|
| 408 |
+
r"""Applies the Hyperbolic Tangent (Tanh) function element-wise.
|
| 409 |
+
|
| 410 |
+
Tanh is defined as:
|
| 411 |
+
|
| 412 |
+
.. math::
|
| 413 |
+
\text{Tanh}(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)} {\exp(x) + \exp(-x)}
|
| 414 |
+
|
| 415 |
+
Shape:
|
| 416 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 417 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 418 |
+
|
| 419 |
+
.. image:: ../scripts/activation_images/Tanh.png
|
| 420 |
+
|
| 421 |
+
Examples::
|
| 422 |
+
|
| 423 |
+
>>> m = nn.Tanh()
|
| 424 |
+
>>> input = torch.tensor([-2.0, -0.5, 0.0, 0.5, 2.0])
|
| 425 |
+
>>> m(input)
|
| 426 |
+
tensor([-0.9640, -0.4621, 0.0000, 0.4621, 0.9640])
|
| 427 |
+
"""
|
| 428 |
+
|
| 429 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 430 |
+
"""
|
| 431 |
+
Runs the forward pass.
|
| 432 |
+
"""
|
| 433 |
+
return torch.tanh(input)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class SiLU(Module):
|
| 437 |
+
r"""Applies the Sigmoid Linear Unit (SiLU) function, element-wise.
|
| 438 |
+
|
| 439 |
+
The SiLU function is also known as the swish function.
|
| 440 |
+
|
| 441 |
+
.. math::
|
| 442 |
+
\text{silu}(x) = x * \sigma(x), \text{where } \sigma(x) \text{ is the logistic sigmoid.}
|
| 443 |
+
|
| 444 |
+
.. note::
|
| 445 |
+
See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_
|
| 446 |
+
where the SiLU (Sigmoid Linear Unit) was originally coined, and see
|
| 447 |
+
`Sigmoid-Weighted Linear Units for Neural Network Function Approximation
|
| 448 |
+
in Reinforcement Learning <https://arxiv.org/abs/1702.03118>`_ and `Swish:
|
| 449 |
+
a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941v1>`_
|
| 450 |
+
where the SiLU was experimented with later.
|
| 451 |
+
|
| 452 |
+
Shape:
|
| 453 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 454 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 455 |
+
|
| 456 |
+
.. image:: ../scripts/activation_images/SiLU.png
|
| 457 |
+
|
| 458 |
+
Examples::
|
| 459 |
+
|
| 460 |
+
>>> m = nn.SiLU()
|
| 461 |
+
>>> input = torch.randn(2)
|
| 462 |
+
>>> output = m(input)
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
__constants__ = ["inplace"]
|
| 466 |
+
inplace: bool
|
| 467 |
+
|
| 468 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 469 |
+
super().__init__()
|
| 470 |
+
self.inplace = inplace
|
| 471 |
+
|
| 472 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 473 |
+
"""
|
| 474 |
+
Runs the forward pass.
|
| 475 |
+
"""
|
| 476 |
+
return F.silu(input, inplace=self.inplace)
|
| 477 |
+
|
| 478 |
+
def extra_repr(self) -> str:
|
| 479 |
+
"""
|
| 480 |
+
Return the extra representation of the module.
|
| 481 |
+
"""
|
| 482 |
+
inplace_str = "inplace=True" if self.inplace else ""
|
| 483 |
+
return inplace_str
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class Mish(Module):
|
| 487 |
+
r"""Applies the Mish function, element-wise.
|
| 488 |
+
|
| 489 |
+
Mish: A Self Regularized Non-Monotonic Neural Activation Function.
|
| 490 |
+
|
| 491 |
+
.. math::
|
| 492 |
+
\text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
|
| 493 |
+
|
| 494 |
+
.. note::
|
| 495 |
+
See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_
|
| 496 |
+
|
| 497 |
+
Shape:
|
| 498 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 499 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 500 |
+
|
| 501 |
+
.. image:: ../scripts/activation_images/Mish.png
|
| 502 |
+
|
| 503 |
+
Examples::
|
| 504 |
+
|
| 505 |
+
>>> m = nn.Mish()
|
| 506 |
+
>>> input = torch.randn(2)
|
| 507 |
+
>>> output = m(input)
|
| 508 |
+
"""
|
| 509 |
+
|
| 510 |
+
__constants__ = ["inplace"]
|
| 511 |
+
inplace: bool
|
| 512 |
+
|
| 513 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 514 |
+
super().__init__()
|
| 515 |
+
self.inplace = inplace
|
| 516 |
+
|
| 517 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 518 |
+
"""
|
| 519 |
+
Runs the forward pass.
|
| 520 |
+
"""
|
| 521 |
+
return F.mish(input, inplace=self.inplace)
|
| 522 |
+
|
| 523 |
+
def extra_repr(self) -> str:
|
| 524 |
+
"""
|
| 525 |
+
Return the extra representation of the module.
|
| 526 |
+
"""
|
| 527 |
+
inplace_str = "inplace=True" if self.inplace else ""
|
| 528 |
+
return inplace_str
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class Hardswish(Module):
|
| 532 |
+
r"""Applies the Hardswish function, element-wise.
|
| 533 |
+
|
| 534 |
+
Method described in the paper: `Searching for MobileNetV3 <https://arxiv.org/abs/1905.02244>`_.
|
| 535 |
+
|
| 536 |
+
Hardswish is defined as:
|
| 537 |
+
|
| 538 |
+
.. math::
|
| 539 |
+
\text{Hardswish}(x) = \begin{cases}
|
| 540 |
+
0 & \text{if~} x \le -3, \\
|
| 541 |
+
x & \text{if~} x \ge +3, \\
|
| 542 |
+
x \cdot (x + 3) /6 & \text{otherwise}
|
| 543 |
+
\end{cases}
|
| 544 |
+
|
| 545 |
+
Args:
|
| 546 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 547 |
+
|
| 548 |
+
Shape:
|
| 549 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 550 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 551 |
+
|
| 552 |
+
.. image:: ../scripts/activation_images/Hardswish.png
|
| 553 |
+
|
| 554 |
+
Examples::
|
| 555 |
+
|
| 556 |
+
>>> m = nn.Hardswish()
|
| 557 |
+
>>> input = torch.randn(2)
|
| 558 |
+
>>> output = m(input)
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
__constants__ = ["inplace"]
|
| 562 |
+
|
| 563 |
+
inplace: bool
|
| 564 |
+
|
| 565 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 566 |
+
super().__init__()
|
| 567 |
+
self.inplace = inplace
|
| 568 |
+
|
| 569 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 570 |
+
"""
|
| 571 |
+
Runs the forward pass.
|
| 572 |
+
"""
|
| 573 |
+
return F.hardswish(input, self.inplace)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
class ELU(Module):
|
| 577 |
+
r"""Applies the Exponential Linear Unit (ELU) function, element-wise.
|
| 578 |
+
|
| 579 |
+
Method described in the paper: `Fast and Accurate Deep Network Learning by Exponential Linear
|
| 580 |
+
Units (ELUs) <https://arxiv.org/abs/1511.07289>`__.
|
| 581 |
+
|
| 582 |
+
ELU is defined as:
|
| 583 |
+
|
| 584 |
+
.. math::
|
| 585 |
+
\text{ELU}(x) = \begin{cases}
|
| 586 |
+
x, & \text{ if } x > 0\\
|
| 587 |
+
\alpha * (\exp(x) - 1), & \text{ if } x \leq 0
|
| 588 |
+
\end{cases}
|
| 589 |
+
|
| 590 |
+
Args:
|
| 591 |
+
alpha: the :math:`\alpha` value for the ELU formulation. Default: 1.0
|
| 592 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 593 |
+
|
| 594 |
+
Shape:
|
| 595 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 596 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 597 |
+
|
| 598 |
+
.. image:: ../scripts/activation_images/ELU.png
|
| 599 |
+
|
| 600 |
+
Examples::
|
| 601 |
+
|
| 602 |
+
>>> m = nn.ELU()
|
| 603 |
+
>>> input = torch.randn(2)
|
| 604 |
+
>>> output = m(input)
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
__constants__ = ["alpha", "inplace"]
|
| 608 |
+
alpha: float
|
| 609 |
+
inplace: bool
|
| 610 |
+
|
| 611 |
+
def __init__(self, alpha: float = 1.0, inplace: bool = False) -> None:
|
| 612 |
+
super().__init__()
|
| 613 |
+
self.alpha = alpha
|
| 614 |
+
self.inplace = inplace
|
| 615 |
+
|
| 616 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 617 |
+
"""
|
| 618 |
+
Runs the forward pass.
|
| 619 |
+
"""
|
| 620 |
+
return F.elu(input, self.alpha, self.inplace)
|
| 621 |
+
|
| 622 |
+
def extra_repr(self) -> str:
|
| 623 |
+
"""
|
| 624 |
+
Return the extra representation of the module.
|
| 625 |
+
"""
|
| 626 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 627 |
+
return f"alpha={self.alpha}{inplace_str}"
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
class CELU(Module):
|
| 631 |
+
r"""Applies the CELU function element-wise.
|
| 632 |
+
|
| 633 |
+
.. math::
|
| 634 |
+
\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x/\alpha) - 1))
|
| 635 |
+
|
| 636 |
+
More details can be found in the paper `Continuously Differentiable Exponential Linear Units`_ .
|
| 637 |
+
|
| 638 |
+
Args:
|
| 639 |
+
alpha: the :math:`\alpha` value for the CELU formulation. Default: 1.0
|
| 640 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 641 |
+
|
| 642 |
+
Shape:
|
| 643 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 644 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 645 |
+
|
| 646 |
+
.. image:: ../scripts/activation_images/CELU.png
|
| 647 |
+
|
| 648 |
+
Examples::
|
| 649 |
+
|
| 650 |
+
>>> m = nn.CELU()
|
| 651 |
+
>>> input = torch.randn(2)
|
| 652 |
+
>>> output = m(input)
|
| 653 |
+
|
| 654 |
+
.. _`Continuously Differentiable Exponential Linear Units`:
|
| 655 |
+
https://arxiv.org/abs/1704.07483
|
| 656 |
+
"""
|
| 657 |
+
|
| 658 |
+
__constants__ = ["alpha", "inplace"]
|
| 659 |
+
alpha: float
|
| 660 |
+
inplace: bool
|
| 661 |
+
|
| 662 |
+
def __init__(self, alpha: float = 1.0, inplace: bool = False) -> None:
|
| 663 |
+
super().__init__()
|
| 664 |
+
self.alpha = alpha
|
| 665 |
+
self.inplace = inplace
|
| 666 |
+
|
| 667 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 668 |
+
"""
|
| 669 |
+
Runs the forward pass.
|
| 670 |
+
"""
|
| 671 |
+
return F.celu(input, self.alpha, self.inplace)
|
| 672 |
+
|
| 673 |
+
def extra_repr(self) -> str:
|
| 674 |
+
"""
|
| 675 |
+
Return the extra representation of the module.
|
| 676 |
+
"""
|
| 677 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 678 |
+
return f"alpha={self.alpha}{inplace_str}"
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
class SELU(Module):
|
| 682 |
+
r"""Applies the SELU function element-wise.
|
| 683 |
+
|
| 684 |
+
.. math::
|
| 685 |
+
\text{SELU}(x) = \text{scale} * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))
|
| 686 |
+
|
| 687 |
+
with :math:`\alpha = 1.6732632423543772848170429916717` and
|
| 688 |
+
:math:`\text{scale} = 1.0507009873554804934193349852946`.
|
| 689 |
+
|
| 690 |
+
.. warning::
|
| 691 |
+
When using ``kaiming_normal`` or ``kaiming_normal_`` for initialisation,
|
| 692 |
+
``nonlinearity='linear'`` should be used instead of ``nonlinearity='selu'``
|
| 693 |
+
in order to get `Self-Normalizing Neural Networks`_.
|
| 694 |
+
See :func:`torch.nn.init.calculate_gain` for more information.
|
| 695 |
+
|
| 696 |
+
More details can be found in the paper `Self-Normalizing Neural Networks`_ .
|
| 697 |
+
|
| 698 |
+
Args:
|
| 699 |
+
inplace (bool, optional): can optionally do the operation in-place. Default: ``False``
|
| 700 |
+
|
| 701 |
+
Shape:
|
| 702 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 703 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 704 |
+
|
| 705 |
+
.. image:: ../scripts/activation_images/SELU.png
|
| 706 |
+
|
| 707 |
+
Examples::
|
| 708 |
+
|
| 709 |
+
>>> m = nn.SELU()
|
| 710 |
+
>>> input = torch.randn(2)
|
| 711 |
+
>>> output = m(input)
|
| 712 |
+
|
| 713 |
+
.. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515
|
| 714 |
+
"""
|
| 715 |
+
|
| 716 |
+
__constants__ = ["inplace"]
|
| 717 |
+
inplace: bool
|
| 718 |
+
|
| 719 |
+
def __init__(self, inplace: bool = False) -> None:
|
| 720 |
+
super().__init__()
|
| 721 |
+
self.inplace = inplace
|
| 722 |
+
|
| 723 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 724 |
+
"""
|
| 725 |
+
Runs the forward pass.
|
| 726 |
+
"""
|
| 727 |
+
return F.selu(input, self.inplace)
|
| 728 |
+
|
| 729 |
+
def extra_repr(self) -> str:
|
| 730 |
+
"""
|
| 731 |
+
Return the extra representation of the module.
|
| 732 |
+
"""
|
| 733 |
+
inplace_str = "inplace=True" if self.inplace else ""
|
| 734 |
+
return inplace_str
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
class GLU(Module):
|
| 738 |
+
r"""Applies the gated linear unit function.
|
| 739 |
+
|
| 740 |
+
:math:`{GLU}(a, b)= a \otimes \sigma(b)` where :math:`a` is the first half
|
| 741 |
+
of the input matrices and :math:`b` is the second half.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
dim (int): the dimension on which to split the input. Default: -1
|
| 745 |
+
|
| 746 |
+
Shape:
|
| 747 |
+
- Input: :math:`(\ast_1, N, \ast_2)` where `*` means, any number of additional
|
| 748 |
+
dimensions
|
| 749 |
+
- Output: :math:`(\ast_1, M, \ast_2)` where :math:`M=N/2`
|
| 750 |
+
|
| 751 |
+
Examples::
|
| 752 |
+
|
| 753 |
+
>>> m = nn.GLU()
|
| 754 |
+
>>> input = torch.randn(4, 2)
|
| 755 |
+
>>> output = m(input)
|
| 756 |
+
"""
|
| 757 |
+
|
| 758 |
+
__constants__ = ["dim"]
|
| 759 |
+
dim: int
|
| 760 |
+
|
| 761 |
+
def __init__(self, dim: int = -1) -> None:
|
| 762 |
+
super().__init__()
|
| 763 |
+
self.dim = dim
|
| 764 |
+
|
| 765 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 766 |
+
"""
|
| 767 |
+
Runs the forward pass.
|
| 768 |
+
"""
|
| 769 |
+
return F.glu(input, self.dim)
|
| 770 |
+
|
| 771 |
+
def extra_repr(self) -> str:
|
| 772 |
+
"""
|
| 773 |
+
Return the extra representation of the module.
|
| 774 |
+
"""
|
| 775 |
+
return f"dim={self.dim}"
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
class GELU(Module):
|
| 779 |
+
r"""Applies the Gaussian Error Linear Units function.
|
| 780 |
+
|
| 781 |
+
.. math:: \text{GELU}(x) = x * \Phi(x)
|
| 782 |
+
|
| 783 |
+
where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
|
| 784 |
+
|
| 785 |
+
When the approximate argument is 'tanh', Gelu is estimated with:
|
| 786 |
+
|
| 787 |
+
.. math:: \text{GELU}(x) = 0.5 * x * (1 + \text{Tanh}(\sqrt{2 / \pi} * (x + 0.044715 * x^3)))
|
| 788 |
+
|
| 789 |
+
Args:
|
| 790 |
+
approximate (str, optional): the gelu approximation algorithm to use:
|
| 791 |
+
``'none'`` | ``'tanh'``. Default: ``'none'``
|
| 792 |
+
|
| 793 |
+
Shape:
|
| 794 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 795 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 796 |
+
|
| 797 |
+
.. image:: ../scripts/activation_images/GELU.png
|
| 798 |
+
|
| 799 |
+
Examples::
|
| 800 |
+
|
| 801 |
+
>>> m = nn.GELU()
|
| 802 |
+
>>> input = torch.randn(2)
|
| 803 |
+
>>> output = m(input)
|
| 804 |
+
"""
|
| 805 |
+
|
| 806 |
+
__constants__ = ["approximate"]
|
| 807 |
+
approximate: str
|
| 808 |
+
|
| 809 |
+
def __init__(self, approximate: str = "none") -> None:
|
| 810 |
+
super().__init__()
|
| 811 |
+
self.approximate = approximate
|
| 812 |
+
|
| 813 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 814 |
+
"""
|
| 815 |
+
Runs the forward pass.
|
| 816 |
+
"""
|
| 817 |
+
return F.gelu(input, approximate=self.approximate)
|
| 818 |
+
|
| 819 |
+
def extra_repr(self) -> str:
|
| 820 |
+
"""
|
| 821 |
+
Return the extra representation of the module.
|
| 822 |
+
"""
|
| 823 |
+
return f"approximate={repr(self.approximate)}"
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
class Hardshrink(Module):
|
| 827 |
+
r"""Applies the Hard Shrinkage (Hardshrink) function element-wise.
|
| 828 |
+
|
| 829 |
+
Hardshrink is defined as:
|
| 830 |
+
|
| 831 |
+
.. math::
|
| 832 |
+
\text{HardShrink}(x) =
|
| 833 |
+
\begin{cases}
|
| 834 |
+
x, & \text{ if } x > \lambda \\
|
| 835 |
+
x, & \text{ if } x < -\lambda \\
|
| 836 |
+
0, & \text{ otherwise }
|
| 837 |
+
\end{cases}
|
| 838 |
+
|
| 839 |
+
Args:
|
| 840 |
+
lambd: the :math:`\lambda` value for the Hardshrink formulation. Default: 0.5
|
| 841 |
+
|
| 842 |
+
Shape:
|
| 843 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 844 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 845 |
+
|
| 846 |
+
.. image:: ../scripts/activation_images/Hardshrink.png
|
| 847 |
+
|
| 848 |
+
Examples::
|
| 849 |
+
|
| 850 |
+
>>> m = nn.Hardshrink()
|
| 851 |
+
>>> input = torch.randn(2)
|
| 852 |
+
>>> output = m(input)
|
| 853 |
+
"""
|
| 854 |
+
|
| 855 |
+
__constants__ = ["lambd"]
|
| 856 |
+
lambd: float
|
| 857 |
+
|
| 858 |
+
def __init__(self, lambd: float = 0.5) -> None:
|
| 859 |
+
super().__init__()
|
| 860 |
+
self.lambd = lambd
|
| 861 |
+
|
| 862 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 863 |
+
"""
|
| 864 |
+
Run forward pass.
|
| 865 |
+
"""
|
| 866 |
+
return F.hardshrink(input, self.lambd)
|
| 867 |
+
|
| 868 |
+
def extra_repr(self) -> str:
|
| 869 |
+
"""
|
| 870 |
+
Return the extra representation of the module.
|
| 871 |
+
"""
|
| 872 |
+
return f"{self.lambd}"
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
class LeakyReLU(Module):
|
| 876 |
+
r"""Applies the LeakyReLU function element-wise.
|
| 877 |
+
|
| 878 |
+
.. math::
|
| 879 |
+
\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
or
|
| 883 |
+
|
| 884 |
+
.. math::
|
| 885 |
+
\text{LeakyReLU}(x) =
|
| 886 |
+
\begin{cases}
|
| 887 |
+
x, & \text{ if } x \geq 0 \\
|
| 888 |
+
\text{negative\_slope} \times x, & \text{ otherwise }
|
| 889 |
+
\end{cases}
|
| 890 |
+
|
| 891 |
+
Args:
|
| 892 |
+
negative_slope: Controls the angle of the negative slope (which is used for
|
| 893 |
+
negative input values). Default: 1e-2
|
| 894 |
+
inplace: can optionally do the operation in-place. Default: ``False``
|
| 895 |
+
|
| 896 |
+
Shape:
|
| 897 |
+
- Input: :math:`(*)` where `*` means, any number of additional
|
| 898 |
+
dimensions
|
| 899 |
+
- Output: :math:`(*)`, same shape as the input
|
| 900 |
+
|
| 901 |
+
.. image:: ../scripts/activation_images/LeakyReLU.png
|
| 902 |
+
|
| 903 |
+
Examples::
|
| 904 |
+
|
| 905 |
+
>>> m = nn.LeakyReLU(0.1)
|
| 906 |
+
>>> input = torch.randn(2)
|
| 907 |
+
>>> output = m(input)
|
| 908 |
+
"""
|
| 909 |
+
|
| 910 |
+
__constants__ = ["inplace", "negative_slope"]
|
| 911 |
+
inplace: bool
|
| 912 |
+
negative_slope: float
|
| 913 |
+
|
| 914 |
+
def __init__(self, negative_slope: float = 1e-2, inplace: bool = False) -> None:
|
| 915 |
+
super().__init__()
|
| 916 |
+
self.negative_slope = negative_slope
|
| 917 |
+
self.inplace = inplace
|
| 918 |
+
|
| 919 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 920 |
+
"""
|
| 921 |
+
Run forward pass.
|
| 922 |
+
"""
|
| 923 |
+
return F.leaky_relu(input, self.negative_slope, self.inplace)
|
| 924 |
+
|
| 925 |
+
def extra_repr(self) -> str:
|
| 926 |
+
"""
|
| 927 |
+
Return the extra representation of the module.
|
| 928 |
+
"""
|
| 929 |
+
inplace_str = ", inplace=True" if self.inplace else ""
|
| 930 |
+
return f"negative_slope={self.negative_slope}{inplace_str}"
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
class LogSigmoid(Module):
|
| 934 |
+
r"""Applies the Logsigmoid function element-wise.
|
| 935 |
+
|
| 936 |
+
.. math::
|
| 937 |
+
\text{LogSigmoid}(x) = \log\left(\frac{ 1 }{ 1 + \exp(-x)}\right)
|
| 938 |
+
|
| 939 |
+
Shape:
|
| 940 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 941 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 942 |
+
|
| 943 |
+
.. image:: ../scripts/activation_images/LogSigmoid.png
|
| 944 |
+
|
| 945 |
+
Examples::
|
| 946 |
+
|
| 947 |
+
>>> m = nn.LogSigmoid()
|
| 948 |
+
>>> input = torch.randn(2)
|
| 949 |
+
>>> output = m(input)
|
| 950 |
+
"""
|
| 951 |
+
|
| 952 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 953 |
+
"""
|
| 954 |
+
Run forward pass.
|
| 955 |
+
"""
|
| 956 |
+
return F.logsigmoid(input)
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
class Softplus(Module):
|
| 960 |
+
r"""Applies the Softplus function element-wise.
|
| 961 |
+
|
| 962 |
+
.. math::
|
| 963 |
+
\text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))
|
| 964 |
+
|
| 965 |
+
SoftPlus is a smooth approximation to the ReLU function and can be used
|
| 966 |
+
to constrain the output of a machine to always be positive.
|
| 967 |
+
|
| 968 |
+
For numerical stability the implementation reverts to the linear function
|
| 969 |
+
when :math:`input \times \beta > threshold`.
|
| 970 |
+
|
| 971 |
+
Args:
|
| 972 |
+
beta: the :math:`\beta` value for the Softplus formulation. Default: 1
|
| 973 |
+
threshold: values above this revert to a linear function. Default: 20
|
| 974 |
+
|
| 975 |
+
Shape:
|
| 976 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 977 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 978 |
+
|
| 979 |
+
.. image:: ../scripts/activation_images/Softplus.png
|
| 980 |
+
|
| 981 |
+
Examples::
|
| 982 |
+
|
| 983 |
+
>>> m = nn.Softplus()
|
| 984 |
+
>>> input = torch.randn(2)
|
| 985 |
+
>>> output = m(input)
|
| 986 |
+
"""
|
| 987 |
+
|
| 988 |
+
__constants__ = ["beta", "threshold"]
|
| 989 |
+
beta: float
|
| 990 |
+
threshold: float
|
| 991 |
+
|
| 992 |
+
def __init__(self, beta: float = 1.0, threshold: float = 20.0) -> None:
|
| 993 |
+
super().__init__()
|
| 994 |
+
self.beta = beta
|
| 995 |
+
self.threshold = threshold
|
| 996 |
+
|
| 997 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 998 |
+
"""
|
| 999 |
+
Run forward pass.
|
| 1000 |
+
"""
|
| 1001 |
+
return F.softplus(input, self.beta, self.threshold)
|
| 1002 |
+
|
| 1003 |
+
def extra_repr(self) -> str:
|
| 1004 |
+
"""
|
| 1005 |
+
Return the extra representation of the module.
|
| 1006 |
+
"""
|
| 1007 |
+
return f"beta={self.beta}, threshold={self.threshold}"
|
| 1008 |
+
|
| 1009 |
+
|
| 1010 |
+
class Softshrink(Module):
|
| 1011 |
+
r"""Applies the soft shrinkage function element-wise.
|
| 1012 |
+
|
| 1013 |
+
.. math::
|
| 1014 |
+
\text{SoftShrinkage}(x) =
|
| 1015 |
+
\begin{cases}
|
| 1016 |
+
x - \lambda, & \text{ if } x > \lambda \\
|
| 1017 |
+
x + \lambda, & \text{ if } x < -\lambda \\
|
| 1018 |
+
0, & \text{ otherwise }
|
| 1019 |
+
\end{cases}
|
| 1020 |
+
|
| 1021 |
+
Args:
|
| 1022 |
+
lambd: the :math:`\lambda` (must be no less than zero) value for the Softshrink formulation. Default: 0.5
|
| 1023 |
+
|
| 1024 |
+
Shape:
|
| 1025 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 1026 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 1027 |
+
|
| 1028 |
+
.. image:: ../scripts/activation_images/Softshrink.png
|
| 1029 |
+
|
| 1030 |
+
Examples::
|
| 1031 |
+
|
| 1032 |
+
>>> m = nn.Softshrink()
|
| 1033 |
+
>>> input = torch.randn(2)
|
| 1034 |
+
>>> output = m(input)
|
| 1035 |
+
"""
|
| 1036 |
+
|
| 1037 |
+
__constants__ = ["lambd"]
|
| 1038 |
+
lambd: float
|
| 1039 |
+
|
| 1040 |
+
def __init__(self, lambd: float = 0.5) -> None:
|
| 1041 |
+
super().__init__()
|
| 1042 |
+
self.lambd = lambd
|
| 1043 |
+
|
| 1044 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1045 |
+
"""
|
| 1046 |
+
Run forward pass.
|
| 1047 |
+
"""
|
| 1048 |
+
return F.softshrink(input, self.lambd)
|
| 1049 |
+
|
| 1050 |
+
def extra_repr(self) -> str:
|
| 1051 |
+
"""
|
| 1052 |
+
Return the extra representation of the module.
|
| 1053 |
+
"""
|
| 1054 |
+
return str(self.lambd)
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def _check_arg_device(x: torch.Tensor | None) -> bool:
|
| 1058 |
+
if x is not None:
|
| 1059 |
+
return x.device.type in [
|
| 1060 |
+
"cpu",
|
| 1061 |
+
"cuda",
|
| 1062 |
+
torch.utils.backend_registration._privateuse1_backend_name,
|
| 1063 |
+
]
|
| 1064 |
+
return True
|
| 1065 |
+
|
| 1066 |
+
|
| 1067 |
+
def _arg_requires_grad(x: torch.Tensor | None) -> bool:
|
| 1068 |
+
if x is not None:
|
| 1069 |
+
return x.requires_grad
|
| 1070 |
+
return False
|
| 1071 |
+
|
| 1072 |
+
|
| 1073 |
+
def _is_make_fx_tracing():
|
| 1074 |
+
if not torch.jit.is_scripting():
|
| 1075 |
+
torch_dispatch_mode_stack = (
|
| 1076 |
+
torch.utils._python_dispatch._get_current_dispatch_mode_stack()
|
| 1077 |
+
)
|
| 1078 |
+
# this can be triggered when dynamo inlining the module too.
|
| 1079 |
+
return (
|
| 1080 |
+
any(
|
| 1081 |
+
type(x) is torch.fx.experimental.proxy_tensor.ProxyTorchDispatchMode
|
| 1082 |
+
for x in torch_dispatch_mode_stack
|
| 1083 |
+
)
|
| 1084 |
+
or torch.compiler.is_exporting()
|
| 1085 |
+
)
|
| 1086 |
+
else:
|
| 1087 |
+
return False
|
| 1088 |
+
|
| 1089 |
+
|
| 1090 |
+
class MultiheadAttention(Module):
|
| 1091 |
+
r"""Allows the model to jointly attend to information from different representation subspaces.
|
| 1092 |
+
|
| 1093 |
+
This MultiheadAttention layer implements the original architecture described
|
| 1094 |
+
in the `Attention Is All You Need <https://arxiv.org/abs/1706.03762>`_ paper. The
|
| 1095 |
+
intent of this layer is as a reference implementation for foundational understanding
|
| 1096 |
+
and thus it contains only limited features relative to newer architectures.
|
| 1097 |
+
Given the fast pace of innovation in transformer-like architectures, we recommend
|
| 1098 |
+
exploring this `tutorial <https://pytorch.org/tutorials/intermediate/transformer_building_blocks.html>`_
|
| 1099 |
+
to build efficient layers from building blocks in core or using higher
|
| 1100 |
+
level libraries from the `PyTorch Ecosystem <https://landscape.pytorch.org/>`_.
|
| 1101 |
+
|
| 1102 |
+
Multi-Head Attention is defined as:
|
| 1103 |
+
|
| 1104 |
+
.. math::
|
| 1105 |
+
\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1,\dots,\text{head}_h)W^O
|
| 1106 |
+
|
| 1107 |
+
where :math:`\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)`.
|
| 1108 |
+
|
| 1109 |
+
``nn.MultiheadAttention`` will use the optimized implementations of
|
| 1110 |
+
``scaled_dot_product_attention()`` when possible.
|
| 1111 |
+
|
| 1112 |
+
In addition to support for the new ``scaled_dot_product_attention()``
|
| 1113 |
+
function, for speeding up Inference, MHA will use
|
| 1114 |
+
fastpath inference with support for Nested Tensors, iff:
|
| 1115 |
+
|
| 1116 |
+
- self attention is being computed (i.e., ``query``, ``key``, and ``value`` are the same tensor).
|
| 1117 |
+
- inputs are batched (3D) with ``batch_first==True``
|
| 1118 |
+
- Either autograd is disabled (using ``torch.inference_mode`` or ``torch.no_grad``) or no tensor argument ``requires_grad``
|
| 1119 |
+
- training is disabled (using ``.eval()``)
|
| 1120 |
+
- ``add_bias_kv`` is ``False``
|
| 1121 |
+
- ``add_zero_attn`` is ``False``
|
| 1122 |
+
- ``kdim`` and ``vdim`` are equal to ``embed_dim``
|
| 1123 |
+
- if a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ is passed, neither ``key_padding_mask``
|
| 1124 |
+
nor ``attn_mask`` is passed
|
| 1125 |
+
- autocast is disabled
|
| 1126 |
+
|
| 1127 |
+
If the optimized inference fastpath implementation is in use, a
|
| 1128 |
+
`NestedTensor <https://pytorch.org/docs/stable/nested.html>`_ can be passed for
|
| 1129 |
+
``query``/``key``/``value`` to represent padding more efficiently than using a
|
| 1130 |
+
padding mask. In this case, a `NestedTensor <https://pytorch.org/docs/stable/nested.html>`_
|
| 1131 |
+
will be returned, and an additional speedup proportional to the fraction of the input
|
| 1132 |
+
that is padding can be expected.
|
| 1133 |
+
|
| 1134 |
+
Args:
|
| 1135 |
+
embed_dim: Total dimension of the model.
|
| 1136 |
+
num_heads: Number of parallel attention heads. Note that ``embed_dim`` will be split
|
| 1137 |
+
across ``num_heads`` (i.e. each head will have dimension ``embed_dim // num_heads``).
|
| 1138 |
+
dropout: Dropout probability on ``attn_output_weights``. Default: ``0.0`` (no dropout).
|
| 1139 |
+
bias: If specified, adds bias to input / output projection layers. Default: ``True``.
|
| 1140 |
+
add_bias_kv: If specified, adds bias to the key and value sequences at dim=0. Default: ``False``.
|
| 1141 |
+
add_zero_attn: If specified, adds a new batch of zeros to the key and value sequences at dim=1.
|
| 1142 |
+
Default: ``False``.
|
| 1143 |
+
kdim: Total number of features for keys. Default: ``None`` (uses ``kdim=embed_dim``).
|
| 1144 |
+
vdim: Total number of features for values. Default: ``None`` (uses ``vdim=embed_dim``).
|
| 1145 |
+
batch_first: If ``True``, then the input and output tensors are provided
|
| 1146 |
+
as (batch, seq, feature). Default: ``False`` (seq, batch, feature).
|
| 1147 |
+
|
| 1148 |
+
Examples::
|
| 1149 |
+
|
| 1150 |
+
>>> # xdoctest: +SKIP
|
| 1151 |
+
>>> multihead_attn = nn.MultiheadAttention(embed_dim, num_heads)
|
| 1152 |
+
>>> attn_output, attn_output_weights = multihead_attn(query, key, value)
|
| 1153 |
+
|
| 1154 |
+
.. _`FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness`:
|
| 1155 |
+
https://arxiv.org/abs/2205.14135
|
| 1156 |
+
|
| 1157 |
+
"""
|
| 1158 |
+
|
| 1159 |
+
__constants__ = ["batch_first"]
|
| 1160 |
+
bias_k: torch.Tensor | None
|
| 1161 |
+
bias_v: torch.Tensor | None
|
| 1162 |
+
|
| 1163 |
+
def __init__(
|
| 1164 |
+
self,
|
| 1165 |
+
embed_dim,
|
| 1166 |
+
num_heads,
|
| 1167 |
+
dropout=0.0,
|
| 1168 |
+
bias=True,
|
| 1169 |
+
add_bias_kv=False,
|
| 1170 |
+
add_zero_attn=False,
|
| 1171 |
+
kdim=None,
|
| 1172 |
+
vdim=None,
|
| 1173 |
+
batch_first=False,
|
| 1174 |
+
device=None,
|
| 1175 |
+
dtype=None,
|
| 1176 |
+
) -> None:
|
| 1177 |
+
if embed_dim <= 0 or num_heads <= 0:
|
| 1178 |
+
raise ValueError(
|
| 1179 |
+
f"embed_dim and num_heads must be greater than 0,"
|
| 1180 |
+
f" got embed_dim={embed_dim} and num_heads={num_heads} instead"
|
| 1181 |
+
)
|
| 1182 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1183 |
+
super().__init__()
|
| 1184 |
+
self.embed_dim = embed_dim
|
| 1185 |
+
self.kdim = kdim if kdim is not None else embed_dim
|
| 1186 |
+
self.vdim = vdim if vdim is not None else embed_dim
|
| 1187 |
+
self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
| 1188 |
+
|
| 1189 |
+
self.num_heads = num_heads
|
| 1190 |
+
self.dropout = dropout
|
| 1191 |
+
self.batch_first = batch_first
|
| 1192 |
+
self.head_dim = embed_dim // num_heads
|
| 1193 |
+
if self.head_dim * num_heads != self.embed_dim:
|
| 1194 |
+
raise AssertionError("embed_dim must be divisible by num_heads")
|
| 1195 |
+
|
| 1196 |
+
if not self._qkv_same_embed_dim:
|
| 1197 |
+
self.q_proj_weight = Parameter(
|
| 1198 |
+
torch.empty((embed_dim, embed_dim), **factory_kwargs)
|
| 1199 |
+
)
|
| 1200 |
+
self.k_proj_weight = Parameter(
|
| 1201 |
+
torch.empty((embed_dim, self.kdim), **factory_kwargs)
|
| 1202 |
+
)
|
| 1203 |
+
self.v_proj_weight = Parameter(
|
| 1204 |
+
torch.empty((embed_dim, self.vdim), **factory_kwargs)
|
| 1205 |
+
)
|
| 1206 |
+
self.register_parameter("in_proj_weight", None)
|
| 1207 |
+
else:
|
| 1208 |
+
self.in_proj_weight = Parameter(
|
| 1209 |
+
torch.empty((3 * embed_dim, embed_dim), **factory_kwargs)
|
| 1210 |
+
)
|
| 1211 |
+
self.register_parameter("q_proj_weight", None)
|
| 1212 |
+
self.register_parameter("k_proj_weight", None)
|
| 1213 |
+
self.register_parameter("v_proj_weight", None)
|
| 1214 |
+
|
| 1215 |
+
if bias:
|
| 1216 |
+
self.in_proj_bias = Parameter(torch.empty(3 * embed_dim, **factory_kwargs))
|
| 1217 |
+
else:
|
| 1218 |
+
self.register_parameter("in_proj_bias", None)
|
| 1219 |
+
self.out_proj = NonDynamicallyQuantizableLinear(
|
| 1220 |
+
embed_dim, embed_dim, bias=bias, **factory_kwargs
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
if add_bias_kv:
|
| 1224 |
+
self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
| 1225 |
+
self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs))
|
| 1226 |
+
else:
|
| 1227 |
+
self.bias_k = self.bias_v = None
|
| 1228 |
+
|
| 1229 |
+
self.add_zero_attn = add_zero_attn
|
| 1230 |
+
|
| 1231 |
+
self._reset_parameters()
|
| 1232 |
+
|
| 1233 |
+
def _reset_parameters(self) -> None:
|
| 1234 |
+
if self._qkv_same_embed_dim:
|
| 1235 |
+
xavier_uniform_(self.in_proj_weight)
|
| 1236 |
+
else:
|
| 1237 |
+
xavier_uniform_(self.q_proj_weight)
|
| 1238 |
+
xavier_uniform_(self.k_proj_weight)
|
| 1239 |
+
xavier_uniform_(self.v_proj_weight)
|
| 1240 |
+
|
| 1241 |
+
if self.in_proj_bias is not None:
|
| 1242 |
+
constant_(self.in_proj_bias, 0.0)
|
| 1243 |
+
constant_(self.out_proj.bias, 0.0)
|
| 1244 |
+
if self.bias_k is not None:
|
| 1245 |
+
xavier_normal_(self.bias_k)
|
| 1246 |
+
if self.bias_v is not None:
|
| 1247 |
+
xavier_normal_(self.bias_v)
|
| 1248 |
+
|
| 1249 |
+
def __setstate__(self, state):
|
| 1250 |
+
# Support loading old MultiheadAttention checkpoints generated by v1.1.0
|
| 1251 |
+
if "_qkv_same_embed_dim" not in state:
|
| 1252 |
+
state["_qkv_same_embed_dim"] = True
|
| 1253 |
+
|
| 1254 |
+
super().__setstate__(state)
|
| 1255 |
+
|
| 1256 |
+
def forward(
|
| 1257 |
+
self,
|
| 1258 |
+
query: Tensor,
|
| 1259 |
+
key: Tensor,
|
| 1260 |
+
value: Tensor,
|
| 1261 |
+
key_padding_mask: Tensor | None = None,
|
| 1262 |
+
need_weights: bool = True,
|
| 1263 |
+
attn_mask: Tensor | None = None,
|
| 1264 |
+
average_attn_weights: bool = True,
|
| 1265 |
+
is_causal: bool = False,
|
| 1266 |
+
) -> tuple[Tensor, Tensor | None]:
|
| 1267 |
+
r"""Compute attention outputs using query, key, and value embeddings.
|
| 1268 |
+
|
| 1269 |
+
Supports optional parameters for padding, masks and attention weights.
|
| 1270 |
+
|
| 1271 |
+
Args:
|
| 1272 |
+
query: Query embeddings of shape :math:`(L, E_q)` for unbatched input, :math:`(L, N, E_q)` when ``batch_first=False``
|
| 1273 |
+
or :math:`(N, L, E_q)` when ``batch_first=True``, where :math:`L` is the target sequence length,
|
| 1274 |
+
:math:`N` is the batch size, and :math:`E_q` is the query embedding dimension ``embed_dim``.
|
| 1275 |
+
Queries are compared against key-value pairs to produce the output.
|
| 1276 |
+
See "Attention Is All You Need" for more details.
|
| 1277 |
+
key: Key embeddings of shape :math:`(S, E_k)` for unbatched input, :math:`(S, N, E_k)` when ``batch_first=False``
|
| 1278 |
+
or :math:`(N, S, E_k)` when ``batch_first=True``, where :math:`S` is the source sequence length,
|
| 1279 |
+
:math:`N` is the batch size, and :math:`E_k` is the key embedding dimension ``kdim``.
|
| 1280 |
+
See "Attention Is All You Need" for more details.
|
| 1281 |
+
value: Value embeddings of shape :math:`(S, E_v)` for unbatched input, :math:`(S, N, E_v)` when
|
| 1282 |
+
``batch_first=False`` or :math:`(N, S, E_v)` when ``batch_first=True``, where :math:`S` is the source
|
| 1283 |
+
sequence length, :math:`N` is the batch size, and :math:`E_v` is the value embedding dimension ``vdim``.
|
| 1284 |
+
See "Attention Is All You Need" for more details.
|
| 1285 |
+
key_padding_mask: If specified, a mask of shape :math:`(N, S)` indicating which elements within ``key``
|
| 1286 |
+
to ignore for the purpose of attention (i.e. treat as "padding"). For unbatched `query`, shape should be :math:`(S)`.
|
| 1287 |
+
Binary and float masks are supported.
|
| 1288 |
+
For a binary mask, a ``True`` value indicates that the corresponding ``key`` value will be ignored for
|
| 1289 |
+
the purpose of attention. For a float mask, it will be directly added to the corresponding ``key`` value.
|
| 1290 |
+
need_weights: If specified, returns ``attn_output_weights`` in addition to ``attn_outputs``.
|
| 1291 |
+
Set ``need_weights=False`` to use the optimized ``scaled_dot_product_attention``
|
| 1292 |
+
and achieve the best performance for MHA.
|
| 1293 |
+
Default: ``True``.
|
| 1294 |
+
attn_mask: If specified, a 2D or 3D mask preventing attention to certain positions. Must be of shape
|
| 1295 |
+
:math:`(L, S)` or :math:`(N\cdot\text{num\_heads}, L, S)`, where :math:`N` is the batch size,
|
| 1296 |
+
:math:`L` is the target sequence length, and :math:`S` is the source sequence length. A 2D mask will be
|
| 1297 |
+
broadcasted across the batch while a 3D mask allows for a different mask for each entry in the batch.
|
| 1298 |
+
Binary and float masks are supported. For a binary mask, a ``True`` value indicates that the
|
| 1299 |
+
corresponding position is not allowed to attend. For a float mask, the mask values will be added to
|
| 1300 |
+
the attention weight.
|
| 1301 |
+
If both attn_mask and key_padding_mask are supplied, their types should match.
|
| 1302 |
+
average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across
|
| 1303 |
+
heads. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an
|
| 1304 |
+
effect when ``need_weights=True``. Default: ``True`` (i.e. average weights across heads)
|
| 1305 |
+
is_causal: If specified, applies a causal mask as attention mask.
|
| 1306 |
+
Default: ``False``.
|
| 1307 |
+
Warning:
|
| 1308 |
+
``is_causal`` provides a hint that ``attn_mask`` is the
|
| 1309 |
+
causal mask. Providing incorrect hints can result in
|
| 1310 |
+
incorrect execution, including forward and backward
|
| 1311 |
+
compatibility.
|
| 1312 |
+
|
| 1313 |
+
Outputs:
|
| 1314 |
+
- **attn_output** - Attention outputs of shape :math:`(L, E)` when input is unbatched,
|
| 1315 |
+
:math:`(L, N, E)` when ``batch_first=False`` or :math:`(N, L, E)` when ``batch_first=True``,
|
| 1316 |
+
where :math:`L` is the target sequence length, :math:`N` is the batch size, and :math:`E` is the
|
| 1317 |
+
embedding dimension ``embed_dim``.
|
| 1318 |
+
- **attn_output_weights** - Only returned when ``need_weights=True``. If ``average_attn_weights=True``,
|
| 1319 |
+
returns attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
|
| 1320 |
+
:math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
|
| 1321 |
+
:math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
|
| 1322 |
+
head of shape :math:`(\text{num\_heads}, L, S)` when input is unbatched or :math:`(N, \text{num\_heads}, L, S)`.
|
| 1323 |
+
|
| 1324 |
+
.. note::
|
| 1325 |
+
`batch_first` argument is ignored for unbatched inputs.
|
| 1326 |
+
"""
|
| 1327 |
+
why_not_fast_path = ""
|
| 1328 |
+
if (
|
| 1329 |
+
(attn_mask is not None and torch.is_floating_point(attn_mask))
|
| 1330 |
+
or (key_padding_mask is not None)
|
| 1331 |
+
and torch.is_floating_point(key_padding_mask)
|
| 1332 |
+
):
|
| 1333 |
+
why_not_fast_path = "floating-point masks are not supported for fast path."
|
| 1334 |
+
|
| 1335 |
+
is_batched = query.dim() == 3
|
| 1336 |
+
|
| 1337 |
+
key_padding_mask = F._canonical_mask(
|
| 1338 |
+
mask=key_padding_mask,
|
| 1339 |
+
mask_name="key_padding_mask",
|
| 1340 |
+
other_type=F._none_or_dtype(attn_mask),
|
| 1341 |
+
other_name="attn_mask",
|
| 1342 |
+
target_type=query.dtype,
|
| 1343 |
+
)
|
| 1344 |
+
|
| 1345 |
+
attn_mask = F._canonical_mask(
|
| 1346 |
+
mask=attn_mask,
|
| 1347 |
+
mask_name="attn_mask",
|
| 1348 |
+
other_type=None,
|
| 1349 |
+
other_name="",
|
| 1350 |
+
target_type=query.dtype,
|
| 1351 |
+
check_other=False,
|
| 1352 |
+
)
|
| 1353 |
+
|
| 1354 |
+
is_fastpath_enabled = torch.backends.mha.get_fastpath_enabled()
|
| 1355 |
+
|
| 1356 |
+
if not is_fastpath_enabled:
|
| 1357 |
+
why_not_fast_path = "torch.backends.mha.get_fastpath_enabled() was not True"
|
| 1358 |
+
elif not is_batched:
|
| 1359 |
+
why_not_fast_path = (
|
| 1360 |
+
f"input not batched; expected query.dim() of 3 but got {query.dim()}"
|
| 1361 |
+
)
|
| 1362 |
+
elif query is not key or key is not value:
|
| 1363 |
+
# When lifting this restriction, don't forget to either
|
| 1364 |
+
# enforce that the dtypes all match or test cases where
|
| 1365 |
+
# they don't!
|
| 1366 |
+
why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
|
| 1367 |
+
elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
|
| 1368 |
+
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
|
| 1369 |
+
elif self.in_proj_weight is None:
|
| 1370 |
+
why_not_fast_path = "in_proj_weight was None"
|
| 1371 |
+
elif query.dtype != self.in_proj_weight.dtype:
|
| 1372 |
+
# this case will fail anyway, but at least they'll get a useful error message.
|
| 1373 |
+
why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
|
| 1374 |
+
elif self.training:
|
| 1375 |
+
why_not_fast_path = "training is enabled"
|
| 1376 |
+
elif (self.num_heads % 2) != 0:
|
| 1377 |
+
why_not_fast_path = "self.num_heads is not even"
|
| 1378 |
+
elif not self.batch_first:
|
| 1379 |
+
why_not_fast_path = "batch_first was not True"
|
| 1380 |
+
elif self.bias_k is not None:
|
| 1381 |
+
why_not_fast_path = "self.bias_k was not None"
|
| 1382 |
+
elif self.bias_v is not None:
|
| 1383 |
+
why_not_fast_path = "self.bias_v was not None"
|
| 1384 |
+
elif self.add_zero_attn:
|
| 1385 |
+
why_not_fast_path = "add_zero_attn was enabled"
|
| 1386 |
+
elif not self._qkv_same_embed_dim:
|
| 1387 |
+
why_not_fast_path = "_qkv_same_embed_dim was not True"
|
| 1388 |
+
elif query.is_nested and (
|
| 1389 |
+
key_padding_mask is not None or attn_mask is not None
|
| 1390 |
+
):
|
| 1391 |
+
why_not_fast_path = (
|
| 1392 |
+
"supplying both src_key_padding_mask and src_mask at the same time \
|
| 1393 |
+
is not supported with NestedTensor input"
|
| 1394 |
+
)
|
| 1395 |
+
elif torch.is_autocast_enabled():
|
| 1396 |
+
why_not_fast_path = "autocast is enabled"
|
| 1397 |
+
|
| 1398 |
+
fast_path_blocked_by_tracing = False
|
| 1399 |
+
if not why_not_fast_path:
|
| 1400 |
+
tensor_args = (
|
| 1401 |
+
query,
|
| 1402 |
+
key,
|
| 1403 |
+
value,
|
| 1404 |
+
self.in_proj_weight,
|
| 1405 |
+
self.in_proj_bias,
|
| 1406 |
+
self.out_proj.weight,
|
| 1407 |
+
self.out_proj.bias,
|
| 1408 |
+
)
|
| 1409 |
+
# We have to use list comprehensions below because TorchScript does not support
|
| 1410 |
+
# generator expressions.
|
| 1411 |
+
if torch.overrides.has_torch_function(tensor_args):
|
| 1412 |
+
why_not_fast_path = "some Tensor argument has_torch_function"
|
| 1413 |
+
elif not all(_check_arg_device(x) for x in tensor_args):
|
| 1414 |
+
why_not_fast_path = (
|
| 1415 |
+
"some Tensor argument's device is neither one of "
|
| 1416 |
+
f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}"
|
| 1417 |
+
)
|
| 1418 |
+
elif torch.is_grad_enabled() and any(
|
| 1419 |
+
_arg_requires_grad(x) for x in tensor_args
|
| 1420 |
+
):
|
| 1421 |
+
why_not_fast_path = (
|
| 1422 |
+
"grad is enabled and at least one of query or the "
|
| 1423 |
+
"input/output projection weights or biases requires_grad"
|
| 1424 |
+
)
|
| 1425 |
+
elif _is_make_fx_tracing():
|
| 1426 |
+
why_not_fast_path = "we are running make_fx tracing"
|
| 1427 |
+
fast_path_blocked_by_tracing = True
|
| 1428 |
+
if not why_not_fast_path:
|
| 1429 |
+
merged_mask, mask_type = self.merge_masks(
|
| 1430 |
+
attn_mask, key_padding_mask, query
|
| 1431 |
+
)
|
| 1432 |
+
|
| 1433 |
+
if self.in_proj_bias is not None and self.in_proj_weight is not None:
|
| 1434 |
+
return torch._native_multi_head_attention(
|
| 1435 |
+
query,
|
| 1436 |
+
key,
|
| 1437 |
+
value,
|
| 1438 |
+
self.embed_dim,
|
| 1439 |
+
self.num_heads,
|
| 1440 |
+
self.in_proj_weight,
|
| 1441 |
+
self.in_proj_bias,
|
| 1442 |
+
self.out_proj.weight,
|
| 1443 |
+
self.out_proj.bias,
|
| 1444 |
+
merged_mask,
|
| 1445 |
+
need_weights,
|
| 1446 |
+
average_attn_weights,
|
| 1447 |
+
mask_type,
|
| 1448 |
+
)
|
| 1449 |
+
|
| 1450 |
+
any_nested = query.is_nested or key.is_nested or value.is_nested
|
| 1451 |
+
if any_nested:
|
| 1452 |
+
raise AssertionError(
|
| 1453 |
+
"MultiheadAttention does not support NestedTensor outside of its fast path. "
|
| 1454 |
+
+ f"The fast path was not hit because {why_not_fast_path}"
|
| 1455 |
+
)
|
| 1456 |
+
|
| 1457 |
+
if self.batch_first and is_batched:
|
| 1458 |
+
# make sure that the transpose op does not affect the "is" property
|
| 1459 |
+
if key is value:
|
| 1460 |
+
if query is key:
|
| 1461 |
+
query = key = value = query.transpose(1, 0)
|
| 1462 |
+
else:
|
| 1463 |
+
query, key = (x.transpose(1, 0) for x in (query, key))
|
| 1464 |
+
value = key
|
| 1465 |
+
else:
|
| 1466 |
+
query, key, value = (x.transpose(1, 0) for x in (query, key, value))
|
| 1467 |
+
|
| 1468 |
+
if not self._qkv_same_embed_dim:
|
| 1469 |
+
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
| 1470 |
+
query,
|
| 1471 |
+
key,
|
| 1472 |
+
value,
|
| 1473 |
+
self.embed_dim,
|
| 1474 |
+
self.num_heads,
|
| 1475 |
+
self.in_proj_weight,
|
| 1476 |
+
self.in_proj_bias,
|
| 1477 |
+
self.bias_k,
|
| 1478 |
+
self.bias_v,
|
| 1479 |
+
self.add_zero_attn,
|
| 1480 |
+
self.dropout,
|
| 1481 |
+
self.out_proj.weight,
|
| 1482 |
+
self.out_proj.bias,
|
| 1483 |
+
training=self.training,
|
| 1484 |
+
key_padding_mask=key_padding_mask,
|
| 1485 |
+
need_weights=need_weights,
|
| 1486 |
+
attn_mask=attn_mask,
|
| 1487 |
+
use_separate_proj_weight=True,
|
| 1488 |
+
q_proj_weight=self.q_proj_weight,
|
| 1489 |
+
k_proj_weight=self.k_proj_weight,
|
| 1490 |
+
v_proj_weight=self.v_proj_weight,
|
| 1491 |
+
average_attn_weights=average_attn_weights,
|
| 1492 |
+
is_causal=is_causal,
|
| 1493 |
+
)
|
| 1494 |
+
else:
|
| 1495 |
+
attn_output, attn_output_weights = F.multi_head_attention_forward(
|
| 1496 |
+
query,
|
| 1497 |
+
key,
|
| 1498 |
+
value,
|
| 1499 |
+
self.embed_dim,
|
| 1500 |
+
self.num_heads,
|
| 1501 |
+
self.in_proj_weight,
|
| 1502 |
+
self.in_proj_bias,
|
| 1503 |
+
self.bias_k,
|
| 1504 |
+
self.bias_v,
|
| 1505 |
+
self.add_zero_attn,
|
| 1506 |
+
self.dropout,
|
| 1507 |
+
self.out_proj.weight,
|
| 1508 |
+
self.out_proj.bias,
|
| 1509 |
+
training=self.training,
|
| 1510 |
+
key_padding_mask=key_padding_mask,
|
| 1511 |
+
need_weights=need_weights,
|
| 1512 |
+
attn_mask=attn_mask,
|
| 1513 |
+
average_attn_weights=average_attn_weights,
|
| 1514 |
+
is_causal=is_causal,
|
| 1515 |
+
)
|
| 1516 |
+
if self.batch_first and is_batched:
|
| 1517 |
+
attn_output = attn_output.transpose(1, 0)
|
| 1518 |
+
if fast_path_blocked_by_tracing:
|
| 1519 |
+
# Keep the traced slowpath layout aligned with eager fastpath.
|
| 1520 |
+
attn_output = attn_output.contiguous()
|
| 1521 |
+
return attn_output, attn_output_weights
|
| 1522 |
+
else:
|
| 1523 |
+
return attn_output, attn_output_weights
|
| 1524 |
+
|
| 1525 |
+
def merge_masks(
|
| 1526 |
+
self,
|
| 1527 |
+
attn_mask: Tensor | None,
|
| 1528 |
+
key_padding_mask: Tensor | None,
|
| 1529 |
+
query: Tensor,
|
| 1530 |
+
) -> tuple[Tensor | None, int | None]:
|
| 1531 |
+
r"""Determine mask type and combine masks if necessary.
|
| 1532 |
+
|
| 1533 |
+
If only one mask is provided, that mask
|
| 1534 |
+
and the corresponding mask type will be returned. If both masks are provided, they will be both
|
| 1535 |
+
expanded to shape ``(batch_size, num_heads, seq_len, seq_len)``, combined with logical ``or``
|
| 1536 |
+
and mask type 2 will be returned
|
| 1537 |
+
Args:
|
| 1538 |
+
attn_mask: attention mask of shape ``(seq_len, seq_len)``, mask type 0
|
| 1539 |
+
key_padding_mask: padding mask of shape ``(batch_size, seq_len)``, mask type 1
|
| 1540 |
+
query: query embeddings of shape ``(batch_size, seq_len, embed_dim)``
|
| 1541 |
+
Returns:
|
| 1542 |
+
merged_mask: merged mask
|
| 1543 |
+
mask_type: merged mask type (0, 1, or 2)
|
| 1544 |
+
"""
|
| 1545 |
+
mask_type: int | None = None
|
| 1546 |
+
merged_mask: Tensor | None = None
|
| 1547 |
+
|
| 1548 |
+
if key_padding_mask is not None:
|
| 1549 |
+
mask_type = 1
|
| 1550 |
+
merged_mask = key_padding_mask
|
| 1551 |
+
|
| 1552 |
+
if attn_mask is not None:
|
| 1553 |
+
# In this branch query can't be a nested tensor, so it has a shape
|
| 1554 |
+
batch_size, seq_len, _ = query.shape
|
| 1555 |
+
mask_type = 2
|
| 1556 |
+
|
| 1557 |
+
# Always expands attn_mask to 4D
|
| 1558 |
+
if attn_mask.dim() == 3:
|
| 1559 |
+
attn_mask_expanded = attn_mask.view(batch_size, -1, seq_len, seq_len)
|
| 1560 |
+
else: # attn_mask.dim() == 2:
|
| 1561 |
+
attn_mask_expanded = attn_mask.view(1, 1, seq_len, seq_len).expand(
|
| 1562 |
+
batch_size, self.num_heads, -1, -1
|
| 1563 |
+
)
|
| 1564 |
+
merged_mask = attn_mask_expanded
|
| 1565 |
+
|
| 1566 |
+
if key_padding_mask is not None:
|
| 1567 |
+
key_padding_mask_expanded = key_padding_mask.view(
|
| 1568 |
+
batch_size, 1, 1, seq_len
|
| 1569 |
+
).expand(-1, self.num_heads, -1, -1)
|
| 1570 |
+
merged_mask = attn_mask_expanded + key_padding_mask_expanded
|
| 1571 |
+
|
| 1572 |
+
# no attn_mask and no key_padding_mask, returns None, None
|
| 1573 |
+
return merged_mask, mask_type
|
| 1574 |
+
|
| 1575 |
+
|
| 1576 |
+
class PReLU(Module):
|
| 1577 |
+
r"""Applies the element-wise PReLU function.
|
| 1578 |
+
|
| 1579 |
+
.. math::
|
| 1580 |
+
\text{PReLU}(x) = \max(0,x) + a * \min(0,x)
|
| 1581 |
+
|
| 1582 |
+
or
|
| 1583 |
+
|
| 1584 |
+
.. math::
|
| 1585 |
+
\text{PReLU}(x) =
|
| 1586 |
+
\begin{cases}
|
| 1587 |
+
x, & \text{ if } x \ge 0 \\
|
| 1588 |
+
ax, & \text{ otherwise }
|
| 1589 |
+
\end{cases}
|
| 1590 |
+
|
| 1591 |
+
Here :math:`a` is a learnable parameter. When called without arguments, `nn.PReLU()` uses a single
|
| 1592 |
+
parameter :math:`a` across all input channels. If called with `nn.PReLU(nChannels)`,
|
| 1593 |
+
a separate :math:`a` is used for each input channel.
|
| 1594 |
+
|
| 1595 |
+
|
| 1596 |
+
.. note::
|
| 1597 |
+
weight decay should not be used when learning :math:`a` for good performance.
|
| 1598 |
+
|
| 1599 |
+
.. note::
|
| 1600 |
+
Channel dim is the 2nd dim of input. When input has dims < 2, then there is
|
| 1601 |
+
no channel dim and the number of channels = 1.
|
| 1602 |
+
|
| 1603 |
+
Args:
|
| 1604 |
+
num_parameters (int): number of :math:`a` to learn.
|
| 1605 |
+
Although it takes an int as input, there is only two values are legitimate:
|
| 1606 |
+
1, or the number of channels at input. Default: 1
|
| 1607 |
+
init (float): the initial value of :math:`a`. Default: 0.25
|
| 1608 |
+
|
| 1609 |
+
Shape:
|
| 1610 |
+
- Input: :math:`( *)` where `*` means, any number of additional
|
| 1611 |
+
dimensions.
|
| 1612 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 1613 |
+
|
| 1614 |
+
Attributes:
|
| 1615 |
+
weight (Tensor): the learnable weights of shape (:attr:`num_parameters`).
|
| 1616 |
+
|
| 1617 |
+
.. image:: ../scripts/activation_images/PReLU.png
|
| 1618 |
+
|
| 1619 |
+
Examples::
|
| 1620 |
+
|
| 1621 |
+
>>> m = nn.PReLU()
|
| 1622 |
+
>>> input = torch.randn(2)
|
| 1623 |
+
>>> output = m(input)
|
| 1624 |
+
"""
|
| 1625 |
+
|
| 1626 |
+
__constants__ = ["num_parameters"]
|
| 1627 |
+
num_parameters: int
|
| 1628 |
+
|
| 1629 |
+
def __init__(
|
| 1630 |
+
self, num_parameters: int = 1, init: float = 0.25, device=None, dtype=None
|
| 1631 |
+
) -> None:
|
| 1632 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1633 |
+
self.num_parameters = num_parameters
|
| 1634 |
+
super().__init__()
|
| 1635 |
+
self.init = init
|
| 1636 |
+
self.weight = Parameter(torch.empty(num_parameters, **factory_kwargs))
|
| 1637 |
+
self.reset_parameters()
|
| 1638 |
+
|
| 1639 |
+
def reset_parameters(self) -> None:
|
| 1640 |
+
"""
|
| 1641 |
+
Resets parameters based on their initialization used in ``__init__``.
|
| 1642 |
+
"""
|
| 1643 |
+
torch.nn.init.constant_(self.weight, self.init)
|
| 1644 |
+
|
| 1645 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1646 |
+
"""
|
| 1647 |
+
Runs the forward pass.
|
| 1648 |
+
"""
|
| 1649 |
+
return F.prelu(input, self.weight)
|
| 1650 |
+
|
| 1651 |
+
def extra_repr(self) -> str:
|
| 1652 |
+
"""
|
| 1653 |
+
Return the extra representation of the module.
|
| 1654 |
+
"""
|
| 1655 |
+
return f"num_parameters={self.num_parameters}"
|
| 1656 |
+
|
| 1657 |
+
|
| 1658 |
+
class Softsign(Module):
|
| 1659 |
+
r"""Applies the element-wise Softsign function.
|
| 1660 |
+
|
| 1661 |
+
.. math::
|
| 1662 |
+
\text{SoftSign}(x) = \frac{x}{ 1 + |x|}
|
| 1663 |
+
|
| 1664 |
+
Shape:
|
| 1665 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 1666 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 1667 |
+
|
| 1668 |
+
.. image:: ../scripts/activation_images/Softsign.png
|
| 1669 |
+
|
| 1670 |
+
Examples::
|
| 1671 |
+
|
| 1672 |
+
>>> m = nn.Softsign()
|
| 1673 |
+
>>> input = torch.randn(2)
|
| 1674 |
+
>>> output = m(input)
|
| 1675 |
+
"""
|
| 1676 |
+
|
| 1677 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1678 |
+
"""
|
| 1679 |
+
Runs the forward pass.
|
| 1680 |
+
"""
|
| 1681 |
+
return F.softsign(input)
|
| 1682 |
+
|
| 1683 |
+
|
| 1684 |
+
class Tanhshrink(Module):
|
| 1685 |
+
r"""Applies the element-wise Tanhshrink function.
|
| 1686 |
+
|
| 1687 |
+
.. math::
|
| 1688 |
+
\text{Tanhshrink}(x) = x - \tanh(x)
|
| 1689 |
+
|
| 1690 |
+
Shape:
|
| 1691 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 1692 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 1693 |
+
|
| 1694 |
+
.. image:: ../scripts/activation_images/Tanhshrink.png
|
| 1695 |
+
|
| 1696 |
+
Examples::
|
| 1697 |
+
|
| 1698 |
+
>>> m = nn.Tanhshrink()
|
| 1699 |
+
>>> input = torch.randn(2)
|
| 1700 |
+
>>> output = m(input)
|
| 1701 |
+
"""
|
| 1702 |
+
|
| 1703 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1704 |
+
"""
|
| 1705 |
+
Runs the forward pass.
|
| 1706 |
+
"""
|
| 1707 |
+
return F.tanhshrink(input)
|
| 1708 |
+
|
| 1709 |
+
|
| 1710 |
+
class Softmin(Module):
|
| 1711 |
+
r"""Applies the Softmin function to an n-dimensional input Tensor.
|
| 1712 |
+
|
| 1713 |
+
Rescales them so that the elements of the n-dimensional output Tensor
|
| 1714 |
+
lie in the range `[0, 1]` and sum to 1.
|
| 1715 |
+
|
| 1716 |
+
Softmin is defined as:
|
| 1717 |
+
|
| 1718 |
+
.. math::
|
| 1719 |
+
\text{Softmin}(x_{i}) = \frac{\exp(-x_i)}{\sum_j \exp(-x_j)}
|
| 1720 |
+
|
| 1721 |
+
Shape:
|
| 1722 |
+
- Input: :math:`(*)` where `*` means, any number of additional
|
| 1723 |
+
dimensions
|
| 1724 |
+
- Output: :math:`(*)`, same shape as the input
|
| 1725 |
+
|
| 1726 |
+
Args:
|
| 1727 |
+
dim (int): A dimension along which Softmin will be computed (so every slice
|
| 1728 |
+
along dim will sum to 1).
|
| 1729 |
+
|
| 1730 |
+
Returns:
|
| 1731 |
+
a Tensor of the same dimension and shape as the input, with
|
| 1732 |
+
values in the range [0, 1]
|
| 1733 |
+
|
| 1734 |
+
Examples::
|
| 1735 |
+
|
| 1736 |
+
>>> m = nn.Softmin(dim=1)
|
| 1737 |
+
>>> input = torch.randn(2, 3)
|
| 1738 |
+
>>> output = m(input)
|
| 1739 |
+
"""
|
| 1740 |
+
|
| 1741 |
+
__constants__ = ["dim"]
|
| 1742 |
+
dim: int | None
|
| 1743 |
+
|
| 1744 |
+
def __init__(self, dim: int | None = None) -> None:
|
| 1745 |
+
super().__init__()
|
| 1746 |
+
self.dim = dim
|
| 1747 |
+
|
| 1748 |
+
def __setstate__(self, state):
|
| 1749 |
+
super().__setstate__(state)
|
| 1750 |
+
if not hasattr(self, "dim"):
|
| 1751 |
+
self.dim = None
|
| 1752 |
+
|
| 1753 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1754 |
+
"""
|
| 1755 |
+
Runs the forward pass.
|
| 1756 |
+
"""
|
| 1757 |
+
return F.softmin(input, self.dim, _stacklevel=5)
|
| 1758 |
+
|
| 1759 |
+
def extra_repr(self) -> str:
|
| 1760 |
+
"""
|
| 1761 |
+
Return the extra representation of the module.
|
| 1762 |
+
"""
|
| 1763 |
+
return f"dim={self.dim}"
|
| 1764 |
+
|
| 1765 |
+
|
| 1766 |
+
class Softmax(Module):
|
| 1767 |
+
r"""Applies the Softmax function to an n-dimensional input Tensor.
|
| 1768 |
+
|
| 1769 |
+
Rescales them so that the elements of the n-dimensional output Tensor
|
| 1770 |
+
lie in the range [0,1] and sum to 1.
|
| 1771 |
+
|
| 1772 |
+
Softmax is defined as:
|
| 1773 |
+
|
| 1774 |
+
.. math::
|
| 1775 |
+
\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}
|
| 1776 |
+
|
| 1777 |
+
When the input Tensor is a sparse tensor then the unspecified
|
| 1778 |
+
values are treated as ``-inf``.
|
| 1779 |
+
|
| 1780 |
+
Shape:
|
| 1781 |
+
- Input: :math:`(*)` where `*` means, any number of additional
|
| 1782 |
+
dimensions
|
| 1783 |
+
- Output: :math:`(*)`, same shape as the input
|
| 1784 |
+
|
| 1785 |
+
Returns:
|
| 1786 |
+
a Tensor of the same dimension and shape as the input with
|
| 1787 |
+
values in the range [0, 1]
|
| 1788 |
+
|
| 1789 |
+
Args:
|
| 1790 |
+
dim (int): A dimension along which Softmax will be computed (so every slice
|
| 1791 |
+
along dim will sum to 1).
|
| 1792 |
+
|
| 1793 |
+
.. note::
|
| 1794 |
+
This module doesn't work directly with NLLLoss,
|
| 1795 |
+
which expects the Log to be computed between the Softmax and itself.
|
| 1796 |
+
Use `LogSoftmax` instead (it's faster and has better numerical properties).
|
| 1797 |
+
|
| 1798 |
+
Examples::
|
| 1799 |
+
|
| 1800 |
+
>>> m = nn.Softmax(dim=1)
|
| 1801 |
+
>>> input = torch.randn(2, 3)
|
| 1802 |
+
>>> output = m(input)
|
| 1803 |
+
|
| 1804 |
+
"""
|
| 1805 |
+
|
| 1806 |
+
__constants__ = ["dim"]
|
| 1807 |
+
dim: int | None
|
| 1808 |
+
|
| 1809 |
+
def __init__(self, dim: int | None = None) -> None:
|
| 1810 |
+
if dim is not None and (not isinstance(dim, int) or isinstance(dim, bool)):
|
| 1811 |
+
raise TypeError(f"dim must be an int or None, got {type(dim)}")
|
| 1812 |
+
super().__init__()
|
| 1813 |
+
self.dim = dim
|
| 1814 |
+
|
| 1815 |
+
def __setstate__(self, state):
|
| 1816 |
+
super().__setstate__(state)
|
| 1817 |
+
if not hasattr(self, "dim"):
|
| 1818 |
+
self.dim = None
|
| 1819 |
+
|
| 1820 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1821 |
+
"""
|
| 1822 |
+
Runs the forward pass.
|
| 1823 |
+
"""
|
| 1824 |
+
return F.softmax(input, self.dim, _stacklevel=5)
|
| 1825 |
+
|
| 1826 |
+
def extra_repr(self) -> str:
|
| 1827 |
+
"""
|
| 1828 |
+
Return the extra representation of the module.
|
| 1829 |
+
"""
|
| 1830 |
+
return f"dim={self.dim}"
|
| 1831 |
+
|
| 1832 |
+
|
| 1833 |
+
class Softmax2d(Module):
|
| 1834 |
+
r"""Applies SoftMax over features to each spatial location.
|
| 1835 |
+
|
| 1836 |
+
When given an image of ``Channels x Height x Width``, it will
|
| 1837 |
+
apply `Softmax` to each location :math:`(Channels, h_i, w_j)`
|
| 1838 |
+
|
| 1839 |
+
Shape:
|
| 1840 |
+
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`.
|
| 1841 |
+
- Output: :math:`(N, C, H, W)` or :math:`(C, H, W)` (same shape as input)
|
| 1842 |
+
|
| 1843 |
+
Returns:
|
| 1844 |
+
a Tensor of the same dimension and shape as the input with
|
| 1845 |
+
values in the range [0, 1]
|
| 1846 |
+
|
| 1847 |
+
Examples::
|
| 1848 |
+
|
| 1849 |
+
>>> m = nn.Softmax2d()
|
| 1850 |
+
>>> # you softmax over the 2nd dimension
|
| 1851 |
+
>>> input = torch.randn(2, 3, 12, 13)
|
| 1852 |
+
>>> output = m(input)
|
| 1853 |
+
"""
|
| 1854 |
+
|
| 1855 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1856 |
+
"""
|
| 1857 |
+
Runs the forward pass.
|
| 1858 |
+
"""
|
| 1859 |
+
if input.dim() not in (3, 4):
|
| 1860 |
+
raise ValueError(
|
| 1861 |
+
f"Softmax2d: expected input to be 3D or 4D, got {input.dim()}D instead"
|
| 1862 |
+
)
|
| 1863 |
+
return F.softmax(input, -3, _stacklevel=5)
|
| 1864 |
+
|
| 1865 |
+
|
| 1866 |
+
class LogSoftmax(Module):
|
| 1867 |
+
r"""Applies the :math:`\log(\text{Softmax}(x))` function to an n-dimensional input Tensor.
|
| 1868 |
+
|
| 1869 |
+
The LogSoftmax formulation can be simplified as:
|
| 1870 |
+
|
| 1871 |
+
.. math::
|
| 1872 |
+
\text{LogSoftmax}(x_{i}) = \log\left(\frac{\exp(x_i) }{ \sum_j \exp(x_j)} \right)
|
| 1873 |
+
|
| 1874 |
+
Shape:
|
| 1875 |
+
- Input: :math:`(*)` where `*` means, any number of additional
|
| 1876 |
+
dimensions
|
| 1877 |
+
- Output: :math:`(*)`, same shape as the input
|
| 1878 |
+
|
| 1879 |
+
Args:
|
| 1880 |
+
dim (int): A dimension along which LogSoftmax will be computed.
|
| 1881 |
+
|
| 1882 |
+
Returns:
|
| 1883 |
+
a Tensor of the same dimension and shape as the input with
|
| 1884 |
+
values in the range [-inf, 0)
|
| 1885 |
+
|
| 1886 |
+
Examples::
|
| 1887 |
+
|
| 1888 |
+
>>> m = nn.LogSoftmax(dim=1)
|
| 1889 |
+
>>> input = torch.randn(2, 3)
|
| 1890 |
+
>>> output = m(input)
|
| 1891 |
+
"""
|
| 1892 |
+
|
| 1893 |
+
__constants__ = ["dim"]
|
| 1894 |
+
dim: int | None
|
| 1895 |
+
|
| 1896 |
+
def __init__(self, dim: int | None = None) -> None:
|
| 1897 |
+
if dim is not None and (not isinstance(dim, int) or isinstance(dim, bool)):
|
| 1898 |
+
raise TypeError(f"dim must be an int or None, got {type(dim)}")
|
| 1899 |
+
super().__init__()
|
| 1900 |
+
self.dim = dim
|
| 1901 |
+
|
| 1902 |
+
def __setstate__(self, state):
|
| 1903 |
+
super().__setstate__(state)
|
| 1904 |
+
if not hasattr(self, "dim"):
|
| 1905 |
+
self.dim = None
|
| 1906 |
+
|
| 1907 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1908 |
+
"""
|
| 1909 |
+
Runs the forward pass.
|
| 1910 |
+
"""
|
| 1911 |
+
return F.log_softmax(input, self.dim, _stacklevel=5)
|
| 1912 |
+
|
| 1913 |
+
def extra_repr(self) -> str:
|
| 1914 |
+
"""
|
| 1915 |
+
Return the extra representation of the module.
|
| 1916 |
+
"""
|
| 1917 |
+
return f"dim={self.dim}"
|
.venv/lib/python3.12/site-packages/torch/nn/modules/adaptive.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 4 |
+
from collections import namedtuple
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from torch import Tensor
|
| 10 |
+
|
| 11 |
+
from .container import ModuleList, Sequential
|
| 12 |
+
from .linear import Linear
|
| 13 |
+
from .module import Module
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = ["AdaptiveLogSoftmaxWithLoss"]
|
| 17 |
+
|
| 18 |
+
_ASMoutput = namedtuple("_ASMoutput", ["output", "loss"])
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AdaptiveLogSoftmaxWithLoss(Module):
|
| 22 |
+
(
|
| 23 |
+
"""Efficient softmax approximation.
|
| 24 |
+
|
| 25 |
+
As described in
|
| 26 |
+
`Efficient softmax approximation for GPUs by Edouard Grave, Armand Joulin,
|
| 27 |
+
Moustapha Ciss\u00e9, David Grangier, and Herv\u00e9 J\u00e9gou
|
| 28 |
+
<https://arxiv.org/abs/1609.04309>`__.
|
| 29 |
+
"""
|
| 30 |
+
r"""
|
| 31 |
+
Adaptive softmax is an approximate strategy for training models with large
|
| 32 |
+
output spaces. It is most effective when the label distribution is highly
|
| 33 |
+
imbalanced, for example in natural language modelling, where the word
|
| 34 |
+
frequency distribution approximately follows the `Zipf's law`_.
|
| 35 |
+
|
| 36 |
+
Adaptive softmax partitions the labels into several clusters, according to
|
| 37 |
+
their frequency. These clusters may contain different number of targets
|
| 38 |
+
each.
|
| 39 |
+
Additionally, clusters containing less frequent labels assign lower
|
| 40 |
+
dimensional embeddings to those labels, which speeds up the computation.
|
| 41 |
+
For each minibatch, only clusters for which at least one target is
|
| 42 |
+
present are evaluated.
|
| 43 |
+
|
| 44 |
+
The idea is that the clusters which are accessed frequently
|
| 45 |
+
(like the first one, containing most frequent labels), should also be cheap
|
| 46 |
+
to compute -- that is, contain a small number of assigned labels.
|
| 47 |
+
|
| 48 |
+
We highly recommend taking a look at the original paper for more details.
|
| 49 |
+
|
| 50 |
+
* :attr:`cutoffs` should be an ordered Sequence of integers sorted
|
| 51 |
+
in the increasing order.
|
| 52 |
+
It controls number of clusters and the partitioning of targets into
|
| 53 |
+
clusters. For example setting ``cutoffs = [10, 100, 1000]``
|
| 54 |
+
means that first `10` targets will be assigned
|
| 55 |
+
to the 'head' of the adaptive softmax, targets `11, 12, ..., 100` will be
|
| 56 |
+
assigned to the first cluster, and targets `101, 102, ..., 1000` will be
|
| 57 |
+
assigned to the second cluster, while targets
|
| 58 |
+
`1001, 1002, ..., n_classes - 1` will be assigned
|
| 59 |
+
to the last, third cluster.
|
| 60 |
+
|
| 61 |
+
* :attr:`div_value` is used to compute the size of each additional cluster,
|
| 62 |
+
which is given as
|
| 63 |
+
:math:`\left\lfloor\frac{\texttt{in\_features}}{\texttt{div\_value}^{idx}}\right\rfloor`,
|
| 64 |
+
where :math:`idx` is the cluster index (with clusters
|
| 65 |
+
for less frequent words having larger indices,
|
| 66 |
+
and indices starting from :math:`1`).
|
| 67 |
+
|
| 68 |
+
* :attr:`head_bias` if set to True, adds a bias term to the 'head' of the
|
| 69 |
+
adaptive softmax. See paper for details. Set to False in the official
|
| 70 |
+
implementation.
|
| 71 |
+
|
| 72 |
+
.. warning::
|
| 73 |
+
Labels passed as inputs to this module should be sorted according to
|
| 74 |
+
their frequency. This means that the most frequent label should be
|
| 75 |
+
represented by the index `0`, and the least frequent
|
| 76 |
+
label should be represented by the index `n_classes - 1`.
|
| 77 |
+
|
| 78 |
+
.. note::
|
| 79 |
+
This module returns a ``NamedTuple`` with ``output``
|
| 80 |
+
and ``loss`` fields. See further documentation for details.
|
| 81 |
+
|
| 82 |
+
.. note::
|
| 83 |
+
To compute log-probabilities for all classes, the ``log_prob``
|
| 84 |
+
method can be used.
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
in_features (int): Number of features in the input tensor
|
| 88 |
+
n_classes (int): Number of classes in the dataset
|
| 89 |
+
cutoffs (Sequence): Cutoffs used to assign targets to their buckets
|
| 90 |
+
div_value (float, optional): value used as an exponent to compute sizes
|
| 91 |
+
of the clusters. Default: 4.0
|
| 92 |
+
head_bias (bool, optional): If ``True``, adds a bias term to the 'head' of the
|
| 93 |
+
adaptive softmax. Default: ``False``
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
``NamedTuple`` with ``output`` and ``loss`` fields:
|
| 97 |
+
* **output** is a Tensor of size ``N`` containing computed target
|
| 98 |
+
log probabilities for each example
|
| 99 |
+
* **loss** is a Scalar representing the computed negative
|
| 100 |
+
log likelihood loss
|
| 101 |
+
|
| 102 |
+
Shape:
|
| 103 |
+
- input: :math:`(N, \texttt{in\_features})` or :math:`(\texttt{in\_features})`
|
| 104 |
+
- target: :math:`(N)` or :math:`()` where each value satisfies :math:`0 <= \texttt{target[i]} <= \texttt{n\_classes}`
|
| 105 |
+
- output1: :math:`(N)` or :math:`()`
|
| 106 |
+
- output2: ``Scalar``
|
| 107 |
+
|
| 108 |
+
.. _Zipf's law: https://en.wikipedia.org/wiki/Zipf%27s_law
|
| 109 |
+
"""
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
in_features: int
|
| 113 |
+
n_classes: int
|
| 114 |
+
cutoffs: list[int]
|
| 115 |
+
div_value: float
|
| 116 |
+
head_bias: bool
|
| 117 |
+
head: Linear
|
| 118 |
+
tail: ModuleList
|
| 119 |
+
|
| 120 |
+
def __init__(
|
| 121 |
+
self,
|
| 122 |
+
in_features: int,
|
| 123 |
+
n_classes: int,
|
| 124 |
+
cutoffs: Sequence[int],
|
| 125 |
+
div_value: float = 4.0,
|
| 126 |
+
head_bias: bool = False,
|
| 127 |
+
device=None,
|
| 128 |
+
dtype=None,
|
| 129 |
+
) -> None:
|
| 130 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 131 |
+
super().__init__()
|
| 132 |
+
|
| 133 |
+
cutoffs = list(cutoffs)
|
| 134 |
+
|
| 135 |
+
if len(cutoffs) == 0:
|
| 136 |
+
raise ValueError("cutoffs should be a sequence of length larger than 0")
|
| 137 |
+
|
| 138 |
+
if (
|
| 139 |
+
(cutoffs != sorted(cutoffs))
|
| 140 |
+
or (min(cutoffs) <= 0)
|
| 141 |
+
or (max(cutoffs) > (n_classes - 1))
|
| 142 |
+
or (len(set(cutoffs)) != len(cutoffs))
|
| 143 |
+
or any(int(c) != c for c in cutoffs)
|
| 144 |
+
):
|
| 145 |
+
raise ValueError(
|
| 146 |
+
"cutoffs should be a sequence of unique, positive "
|
| 147 |
+
"integers sorted in an increasing order, where "
|
| 148 |
+
"each value is between 1 and n_classes-1"
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
self.in_features = in_features
|
| 152 |
+
self.n_classes = n_classes
|
| 153 |
+
self.cutoffs = cutoffs + [n_classes]
|
| 154 |
+
self.div_value = div_value
|
| 155 |
+
self.head_bias = head_bias
|
| 156 |
+
|
| 157 |
+
self.shortlist_size = self.cutoffs[0]
|
| 158 |
+
self.n_clusters = len(self.cutoffs) - 1
|
| 159 |
+
self.head_size = self.shortlist_size + self.n_clusters
|
| 160 |
+
|
| 161 |
+
self.head = Linear(
|
| 162 |
+
self.in_features, self.head_size, bias=self.head_bias, **factory_kwargs
|
| 163 |
+
)
|
| 164 |
+
self.tail = ModuleList()
|
| 165 |
+
|
| 166 |
+
for i in range(self.n_clusters):
|
| 167 |
+
hsz = int(self.in_features // (self.div_value ** (i + 1)))
|
| 168 |
+
osz = self.cutoffs[i + 1] - self.cutoffs[i]
|
| 169 |
+
|
| 170 |
+
projection = Sequential(
|
| 171 |
+
Linear(self.in_features, hsz, bias=False, **factory_kwargs),
|
| 172 |
+
Linear(hsz, osz, bias=False, **factory_kwargs),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
self.tail.append(projection)
|
| 176 |
+
|
| 177 |
+
def reset_parameters(self) -> None:
|
| 178 |
+
"""
|
| 179 |
+
Resets parameters based on their initialization used in ``__init__``.
|
| 180 |
+
"""
|
| 181 |
+
self.head.reset_parameters()
|
| 182 |
+
for i2h, h2o in self.tail: # type: ignore[misc]
|
| 183 |
+
i2h.reset_parameters() # type: ignore[has-type]
|
| 184 |
+
h2o.reset_parameters() # type: ignore[has-type]
|
| 185 |
+
|
| 186 |
+
def forward(self, input_: Tensor, target_: Tensor) -> _ASMoutput:
|
| 187 |
+
"""
|
| 188 |
+
Runs the forward pass.
|
| 189 |
+
"""
|
| 190 |
+
targ_dim = target_.dim()
|
| 191 |
+
|
| 192 |
+
if targ_dim == 1:
|
| 193 |
+
if input_.size(0) != target_.size(0):
|
| 194 |
+
raise RuntimeError(
|
| 195 |
+
"Input and target should have the same size in the batch dimension."
|
| 196 |
+
)
|
| 197 |
+
if input_.dim() != 2:
|
| 198 |
+
raise RuntimeError(
|
| 199 |
+
f"1D target tensor expects 2D input tensors, "
|
| 200 |
+
f"but found inputs with size {input_.size()}"
|
| 201 |
+
)
|
| 202 |
+
elif targ_dim == 0:
|
| 203 |
+
if input_.dim() != 1:
|
| 204 |
+
raise RuntimeError(
|
| 205 |
+
f"0D target tensor expects 1D input tensors, "
|
| 206 |
+
f"but found inputs with size {input_.size()}"
|
| 207 |
+
)
|
| 208 |
+
else:
|
| 209 |
+
raise RuntimeError(
|
| 210 |
+
"0D or 1D target tensor expected, multi-target not supported"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
is_batched = targ_dim > 0
|
| 214 |
+
input = input_ if is_batched else input_.unsqueeze(0)
|
| 215 |
+
target = target_ if is_batched else target_.unsqueeze(0)
|
| 216 |
+
|
| 217 |
+
used_rows = 0
|
| 218 |
+
batch_size = target.size(0)
|
| 219 |
+
|
| 220 |
+
output = input.new_zeros(batch_size)
|
| 221 |
+
gather_inds = target.new_empty(batch_size)
|
| 222 |
+
|
| 223 |
+
cutoff_values = [0] + self.cutoffs
|
| 224 |
+
for i in range(len(cutoff_values) - 1):
|
| 225 |
+
low_idx = cutoff_values[i]
|
| 226 |
+
high_idx = cutoff_values[i + 1]
|
| 227 |
+
|
| 228 |
+
target_mask = (target >= low_idx) & (target < high_idx)
|
| 229 |
+
row_indices = target_mask.nonzero().squeeze()
|
| 230 |
+
|
| 231 |
+
if row_indices.numel() == 0:
|
| 232 |
+
continue
|
| 233 |
+
|
| 234 |
+
if i == 0:
|
| 235 |
+
gather_inds.index_copy_(0, row_indices, target[target_mask])
|
| 236 |
+
|
| 237 |
+
else:
|
| 238 |
+
relative_target = target[target_mask] - low_idx
|
| 239 |
+
input_subset = input.index_select(0, row_indices)
|
| 240 |
+
|
| 241 |
+
cluster_output = self.tail[i - 1](input_subset)
|
| 242 |
+
cluster_index = self.shortlist_size + i - 1
|
| 243 |
+
|
| 244 |
+
gather_inds.index_fill_(0, row_indices, cluster_index)
|
| 245 |
+
cluster_logprob = F.log_softmax(cluster_output, dim=1)
|
| 246 |
+
local_logprob = cluster_logprob.gather(1, relative_target.unsqueeze(1))
|
| 247 |
+
output.index_copy_(0, row_indices, local_logprob.squeeze(1))
|
| 248 |
+
|
| 249 |
+
used_rows += row_indices.numel()
|
| 250 |
+
|
| 251 |
+
if used_rows != batch_size:
|
| 252 |
+
raise RuntimeError(
|
| 253 |
+
f"Target values should be in [0, {self.n_classes - 1}], "
|
| 254 |
+
f"but values in range [{target.min().item()}, {target.max().item()}] "
|
| 255 |
+
"were found. "
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
head_output = self.head(input)
|
| 259 |
+
head_logprob = F.log_softmax(head_output, dim=1)
|
| 260 |
+
output += head_logprob.gather(1, gather_inds.unsqueeze(1)).squeeze()
|
| 261 |
+
loss = (-output).mean()
|
| 262 |
+
|
| 263 |
+
if not is_batched:
|
| 264 |
+
output = output.squeeze(0)
|
| 265 |
+
|
| 266 |
+
return _ASMoutput(output, loss)
|
| 267 |
+
|
| 268 |
+
def _get_full_log_prob(self, input, head_output):
|
| 269 |
+
"""Given input tensor, and output of ``self.head``, compute the log of the full distribution."""
|
| 270 |
+
out = input.new_empty((head_output.size(0), self.n_classes))
|
| 271 |
+
head_logprob = F.log_softmax(head_output, dim=1)
|
| 272 |
+
|
| 273 |
+
out[:, : self.shortlist_size] = head_logprob[:, : self.shortlist_size]
|
| 274 |
+
|
| 275 |
+
for i, (start_idx, stop_idx) in enumerate(itertools.pairwise(self.cutoffs)):
|
| 276 |
+
cluster_output = self.tail[i](input)
|
| 277 |
+
cluster_logprob = F.log_softmax(cluster_output, dim=1)
|
| 278 |
+
output_logprob = cluster_logprob + head_logprob[
|
| 279 |
+
:, self.shortlist_size + i
|
| 280 |
+
].unsqueeze(1)
|
| 281 |
+
|
| 282 |
+
out[:, start_idx:stop_idx] = output_logprob
|
| 283 |
+
|
| 284 |
+
return out
|
| 285 |
+
|
| 286 |
+
def log_prob(self, input: Tensor) -> Tensor:
|
| 287 |
+
r"""Compute log probabilities for all :math:`\texttt{n\_classes}`.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
input (Tensor): a minibatch of examples
|
| 291 |
+
|
| 292 |
+
Returns:
|
| 293 |
+
log-probabilities for each class :math:`c`
|
| 294 |
+
in range :math:`0 <= c <= \texttt{n\_classes}`, where :math:`\texttt{n\_classes}` is a
|
| 295 |
+
parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.
|
| 296 |
+
|
| 297 |
+
Shape:
|
| 298 |
+
- Input: :math:`(N, \texttt{in\_features})`
|
| 299 |
+
- Output: :math:`(N, \texttt{n\_classes})`
|
| 300 |
+
|
| 301 |
+
"""
|
| 302 |
+
head_output = self.head(input)
|
| 303 |
+
return self._get_full_log_prob(input, head_output)
|
| 304 |
+
|
| 305 |
+
def predict(self, input: Tensor) -> Tensor:
|
| 306 |
+
r"""Return the class with the highest probability for each example in the input minibatch.
|
| 307 |
+
|
| 308 |
+
This is equivalent to ``self.log_prob(input).argmax(dim=1)``, but is more efficient in some cases.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
input (Tensor): a minibatch of examples
|
| 312 |
+
|
| 313 |
+
Returns:
|
| 314 |
+
output (Tensor): a class with the highest probability for each example
|
| 315 |
+
|
| 316 |
+
Shape:
|
| 317 |
+
- Input: :math:`(N, \texttt{in\_features})`
|
| 318 |
+
- Output: :math:`(N)`
|
| 319 |
+
"""
|
| 320 |
+
head_output = self.head(input)
|
| 321 |
+
output = torch.argmax(head_output, dim=1)
|
| 322 |
+
not_in_shortlist = output >= self.shortlist_size
|
| 323 |
+
all_in_shortlist = not (not_in_shortlist.any())
|
| 324 |
+
|
| 325 |
+
if all_in_shortlist:
|
| 326 |
+
return output
|
| 327 |
+
|
| 328 |
+
elif not_in_shortlist.all():
|
| 329 |
+
log_prob = self._get_full_log_prob(input, head_output)
|
| 330 |
+
return torch.argmax(log_prob, dim=1)
|
| 331 |
+
|
| 332 |
+
else:
|
| 333 |
+
log_prob = self._get_full_log_prob(
|
| 334 |
+
input[not_in_shortlist], head_output[not_in_shortlist]
|
| 335 |
+
)
|
| 336 |
+
output[not_in_shortlist] = torch.argmax(log_prob, dim=1)
|
| 337 |
+
return output
|
.venv/lib/python3.12/site-packages/torch/nn/modules/batchnorm.py
ADDED
|
@@ -0,0 +1,951 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.nn import functional as F, init
|
| 7 |
+
from torch.nn.parameter import Parameter, UninitializedBuffer, UninitializedParameter
|
| 8 |
+
|
| 9 |
+
from ._functions import SyncBatchNorm as sync_batch_norm
|
| 10 |
+
from .lazy import LazyModuleMixin
|
| 11 |
+
from .module import Module
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"BatchNorm1d",
|
| 16 |
+
"LazyBatchNorm1d",
|
| 17 |
+
"BatchNorm2d",
|
| 18 |
+
"LazyBatchNorm2d",
|
| 19 |
+
"BatchNorm3d",
|
| 20 |
+
"LazyBatchNorm3d",
|
| 21 |
+
"SyncBatchNorm",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class _NormBase(Module):
|
| 26 |
+
"""Common base of _InstanceNorm and _BatchNorm."""
|
| 27 |
+
|
| 28 |
+
_version = 2
|
| 29 |
+
__constants__ = ["track_running_stats", "momentum", "eps", "num_features", "affine"]
|
| 30 |
+
num_features: int
|
| 31 |
+
eps: float
|
| 32 |
+
momentum: float | None
|
| 33 |
+
affine: bool
|
| 34 |
+
track_running_stats: bool
|
| 35 |
+
# WARNING: weight and bias purposely not defined here.
|
| 36 |
+
# See https://github.com/pytorch/pytorch/issues/39670
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
num_features: int,
|
| 41 |
+
eps: float = 1e-5,
|
| 42 |
+
momentum: float | None = 0.1,
|
| 43 |
+
affine: bool = True,
|
| 44 |
+
track_running_stats: bool = True,
|
| 45 |
+
device=None,
|
| 46 |
+
dtype=None,
|
| 47 |
+
*,
|
| 48 |
+
bias: bool = True,
|
| 49 |
+
) -> None:
|
| 50 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.num_features = num_features
|
| 53 |
+
self.eps = eps
|
| 54 |
+
self.momentum = momentum
|
| 55 |
+
self.affine = affine
|
| 56 |
+
self.track_running_stats = track_running_stats
|
| 57 |
+
if self.affine:
|
| 58 |
+
self.weight = Parameter(torch.empty(num_features, **factory_kwargs))
|
| 59 |
+
if bias:
|
| 60 |
+
self.bias = Parameter(torch.empty(num_features, **factory_kwargs))
|
| 61 |
+
else:
|
| 62 |
+
self.register_parameter("bias", None)
|
| 63 |
+
else:
|
| 64 |
+
self.register_parameter("weight", None)
|
| 65 |
+
self.register_parameter("bias", None)
|
| 66 |
+
if self.track_running_stats:
|
| 67 |
+
self.register_buffer(
|
| 68 |
+
"running_mean", torch.zeros(num_features, **factory_kwargs)
|
| 69 |
+
)
|
| 70 |
+
self.register_buffer(
|
| 71 |
+
"running_var", torch.ones(num_features, **factory_kwargs)
|
| 72 |
+
)
|
| 73 |
+
self.running_mean: Tensor | None
|
| 74 |
+
self.running_var: Tensor | None
|
| 75 |
+
self.register_buffer(
|
| 76 |
+
"num_batches_tracked",
|
| 77 |
+
torch.tensor(
|
| 78 |
+
0,
|
| 79 |
+
dtype=torch.long,
|
| 80 |
+
# pyrefly: ignore [bad-argument-type]
|
| 81 |
+
**{k: v for k, v in factory_kwargs.items() if k != "dtype"},
|
| 82 |
+
),
|
| 83 |
+
)
|
| 84 |
+
self.num_batches_tracked: Tensor | None
|
| 85 |
+
else:
|
| 86 |
+
self.register_buffer("running_mean", None)
|
| 87 |
+
self.register_buffer("running_var", None)
|
| 88 |
+
self.register_buffer("num_batches_tracked", None)
|
| 89 |
+
self.reset_parameters()
|
| 90 |
+
|
| 91 |
+
def reset_running_stats(self) -> None:
|
| 92 |
+
if self.track_running_stats:
|
| 93 |
+
# running_mean/running_var/num_batches... are registered at runtime depending
|
| 94 |
+
# if self.track_running_stats is on
|
| 95 |
+
self.running_mean.zero_() # type: ignore[union-attr]
|
| 96 |
+
self.running_var.fill_(1) # type: ignore[union-attr]
|
| 97 |
+
self.num_batches_tracked.zero_() # type: ignore[union-attr,operator]
|
| 98 |
+
|
| 99 |
+
def reset_parameters(self) -> None:
|
| 100 |
+
self.reset_running_stats()
|
| 101 |
+
if self.affine:
|
| 102 |
+
init.ones_(self.weight)
|
| 103 |
+
if self.bias is not None:
|
| 104 |
+
init.zeros_(self.bias)
|
| 105 |
+
|
| 106 |
+
def _check_input_dim(self, input):
|
| 107 |
+
raise NotImplementedError
|
| 108 |
+
|
| 109 |
+
def extra_repr(self):
|
| 110 |
+
return (
|
| 111 |
+
"{num_features}, eps={eps}, momentum={momentum}, affine={affine}, "
|
| 112 |
+
"bias={use_bias}, track_running_stats={track_running_stats}".format(
|
| 113 |
+
**self.__dict__, use_bias=self.bias is not None
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def _load_from_state_dict(
|
| 118 |
+
self,
|
| 119 |
+
state_dict,
|
| 120 |
+
prefix,
|
| 121 |
+
local_metadata,
|
| 122 |
+
strict,
|
| 123 |
+
missing_keys,
|
| 124 |
+
unexpected_keys,
|
| 125 |
+
error_msgs,
|
| 126 |
+
) -> None:
|
| 127 |
+
version = local_metadata.get("version", None)
|
| 128 |
+
|
| 129 |
+
if (version is None or version < 2) and self.track_running_stats:
|
| 130 |
+
# at version 2: added num_batches_tracked buffer
|
| 131 |
+
# this should have a default value of 0
|
| 132 |
+
num_batches_tracked_key = prefix + "num_batches_tracked"
|
| 133 |
+
if num_batches_tracked_key not in state_dict:
|
| 134 |
+
state_dict[num_batches_tracked_key] = (
|
| 135 |
+
self.num_batches_tracked
|
| 136 |
+
if self.num_batches_tracked is not None
|
| 137 |
+
and self.num_batches_tracked.device != torch.device("meta")
|
| 138 |
+
else torch.tensor(0, dtype=torch.long)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
super()._load_from_state_dict(
|
| 142 |
+
state_dict,
|
| 143 |
+
prefix,
|
| 144 |
+
local_metadata,
|
| 145 |
+
strict,
|
| 146 |
+
missing_keys,
|
| 147 |
+
unexpected_keys,
|
| 148 |
+
error_msgs,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class _BatchNorm(_NormBase):
|
| 153 |
+
def __init__(
|
| 154 |
+
self,
|
| 155 |
+
num_features: int,
|
| 156 |
+
eps: float = 1e-5,
|
| 157 |
+
momentum: float | None = 0.1,
|
| 158 |
+
affine: bool = True,
|
| 159 |
+
track_running_stats: bool = True,
|
| 160 |
+
device=None,
|
| 161 |
+
dtype=None,
|
| 162 |
+
*,
|
| 163 |
+
bias: bool = True,
|
| 164 |
+
) -> None:
|
| 165 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 166 |
+
super().__init__(
|
| 167 |
+
num_features,
|
| 168 |
+
eps,
|
| 169 |
+
momentum,
|
| 170 |
+
affine,
|
| 171 |
+
track_running_stats,
|
| 172 |
+
**factory_kwargs,
|
| 173 |
+
bias=bias,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 177 |
+
self._check_input_dim(input)
|
| 178 |
+
|
| 179 |
+
# exponential_average_factor is set to self.momentum
|
| 180 |
+
# (when it is available) only so that it gets updated
|
| 181 |
+
# in ONNX graph when this node is exported to ONNX.
|
| 182 |
+
if self.momentum is None:
|
| 183 |
+
exponential_average_factor = 0.0
|
| 184 |
+
else:
|
| 185 |
+
exponential_average_factor = self.momentum
|
| 186 |
+
|
| 187 |
+
if self.training and self.track_running_stats:
|
| 188 |
+
# TODO: if statement only here to tell the jit to skip emitting this when it is None
|
| 189 |
+
if self.num_batches_tracked is not None: # type: ignore[has-type]
|
| 190 |
+
self.num_batches_tracked.add_(1) # type: ignore[has-type]
|
| 191 |
+
if self.momentum is None: # use cumulative moving average
|
| 192 |
+
exponential_average_factor = 1.0 / float(self.num_batches_tracked)
|
| 193 |
+
else: # use exponential moving average
|
| 194 |
+
exponential_average_factor = self.momentum
|
| 195 |
+
|
| 196 |
+
r"""
|
| 197 |
+
Decide whether the mini-batch stats should be used for normalization rather than the buffers.
|
| 198 |
+
Mini-batch stats are used in training mode, and in eval mode when buffers are None.
|
| 199 |
+
"""
|
| 200 |
+
if self.training:
|
| 201 |
+
bn_training = True
|
| 202 |
+
else:
|
| 203 |
+
bn_training = (self.running_mean is None) and (self.running_var is None)
|
| 204 |
+
|
| 205 |
+
r"""
|
| 206 |
+
Buffers are only updated if they are to be tracked and we are in training mode. Thus they only need to be
|
| 207 |
+
passed when the update should occur (i.e. in training mode when they are tracked), or when buffer stats are
|
| 208 |
+
used for normalization (i.e. in eval mode when buffers are not None).
|
| 209 |
+
"""
|
| 210 |
+
return F.batch_norm(
|
| 211 |
+
input,
|
| 212 |
+
# If buffers are not to be tracked, ensure that they won't be updated
|
| 213 |
+
(
|
| 214 |
+
self.running_mean
|
| 215 |
+
if not self.training or self.track_running_stats
|
| 216 |
+
else None
|
| 217 |
+
),
|
| 218 |
+
self.running_var if not self.training or self.track_running_stats else None,
|
| 219 |
+
self.weight,
|
| 220 |
+
self.bias,
|
| 221 |
+
bn_training,
|
| 222 |
+
exponential_average_factor,
|
| 223 |
+
self.eps,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class _LazyNormBase(LazyModuleMixin, _NormBase):
|
| 228 |
+
weight: UninitializedParameter # type: ignore[assignment]
|
| 229 |
+
bias: UninitializedParameter # type: ignore[assignment]
|
| 230 |
+
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
eps=1e-5,
|
| 234 |
+
momentum=0.1,
|
| 235 |
+
affine=True,
|
| 236 |
+
track_running_stats=True,
|
| 237 |
+
device=None,
|
| 238 |
+
dtype=None,
|
| 239 |
+
*,
|
| 240 |
+
bias=True,
|
| 241 |
+
) -> None:
|
| 242 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 243 |
+
# pyrefly: ignore [bad-argument-type]
|
| 244 |
+
super().__init__(
|
| 245 |
+
# affine, bias and track_running_stats are hardcoded to False to
|
| 246 |
+
# avoid creating tensors that will soon be overwritten.
|
| 247 |
+
0,
|
| 248 |
+
eps,
|
| 249 |
+
momentum,
|
| 250 |
+
False,
|
| 251 |
+
False,
|
| 252 |
+
**factory_kwargs,
|
| 253 |
+
bias=False,
|
| 254 |
+
)
|
| 255 |
+
self.affine = affine
|
| 256 |
+
self.track_running_stats = track_running_stats
|
| 257 |
+
if self.affine:
|
| 258 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 259 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 260 |
+
if bias:
|
| 261 |
+
# pyrefly: ignore # bad-argument-type
|
| 262 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 263 |
+
if self.track_running_stats:
|
| 264 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 265 |
+
self.running_mean = UninitializedBuffer(**factory_kwargs)
|
| 266 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 267 |
+
self.running_var = UninitializedBuffer(**factory_kwargs)
|
| 268 |
+
self.num_batches_tracked = torch.tensor(
|
| 269 |
+
0,
|
| 270 |
+
dtype=torch.long,
|
| 271 |
+
# pyrefly: ignore [bad-argument-type]
|
| 272 |
+
**{k: v for k, v in factory_kwargs.items() if k != "dtype"},
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
def reset_parameters(self) -> None:
|
| 276 |
+
# pyrefly: ignore [bad-argument-type]
|
| 277 |
+
if not self.has_uninitialized_params() and self.num_features != 0:
|
| 278 |
+
super().reset_parameters()
|
| 279 |
+
|
| 280 |
+
def initialize_parameters(self, input) -> None: # type: ignore[override]
|
| 281 |
+
# pyrefly: ignore [bad-argument-type]
|
| 282 |
+
if self.has_uninitialized_params():
|
| 283 |
+
self.num_features = input.shape[1]
|
| 284 |
+
if self.affine:
|
| 285 |
+
if not isinstance(self.weight, UninitializedParameter):
|
| 286 |
+
raise AssertionError(
|
| 287 |
+
"self.weight must be an UninitializedParameter"
|
| 288 |
+
)
|
| 289 |
+
self.weight.materialize((self.num_features,))
|
| 290 |
+
if self.bias is not None:
|
| 291 |
+
if not isinstance(self.bias, UninitializedParameter):
|
| 292 |
+
raise AssertionError(
|
| 293 |
+
"self.bias must be an UninitializedParameter"
|
| 294 |
+
)
|
| 295 |
+
self.bias.materialize((self.num_features,))
|
| 296 |
+
if self.track_running_stats:
|
| 297 |
+
self.running_mean.materialize( # type:ignore[union-attr]
|
| 298 |
+
(self.num_features,)
|
| 299 |
+
)
|
| 300 |
+
self.running_var.materialize( # type:ignore[union-attr]
|
| 301 |
+
(self.num_features,)
|
| 302 |
+
)
|
| 303 |
+
self.reset_parameters()
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class BatchNorm1d(_BatchNorm):
|
| 307 |
+
r"""Applies Batch Normalization over a 2D or 3D input.
|
| 308 |
+
|
| 309 |
+
Method described in the paper
|
| 310 |
+
`Batch Normalization: Accelerating Deep Network Training by Reducing
|
| 311 |
+
Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .
|
| 312 |
+
|
| 313 |
+
.. math::
|
| 314 |
+
|
| 315 |
+
y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 316 |
+
|
| 317 |
+
The mean and standard-deviation are calculated per-dimension over
|
| 318 |
+
the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 319 |
+
of size `C` (where `C` is the number of features or channels of the input). By default, the
|
| 320 |
+
elements of :math:`\gamma` are set to 1 and the elements of :math:`\beta` are set to 0.
|
| 321 |
+
At train time in the forward pass, the variance is calculated via the biased estimator,
|
| 322 |
+
equivalent to ``torch.var(input, correction=0)``. However, the value stored in the
|
| 323 |
+
moving average of the variance is calculated via the unbiased estimator, equivalent to
|
| 324 |
+
``torch.var(input, correction=1)``.
|
| 325 |
+
|
| 326 |
+
Also by default, during training this layer keeps running estimates of its
|
| 327 |
+
computed mean and variance, which are then used for normalization during
|
| 328 |
+
evaluation. The running estimates are kept with a default :attr:`momentum`
|
| 329 |
+
of 0.1.
|
| 330 |
+
|
| 331 |
+
If :attr:`track_running_stats` is set to ``False``, this layer then does not
|
| 332 |
+
keep running estimates, and batch statistics are instead used during
|
| 333 |
+
evaluation time as well.
|
| 334 |
+
|
| 335 |
+
.. note::
|
| 336 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 337 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 338 |
+
update rule for running statistics here is
|
| 339 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 340 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 341 |
+
new observed value.
|
| 342 |
+
|
| 343 |
+
Because the Batch Normalization is done over the `C` dimension, computing statistics
|
| 344 |
+
on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization.
|
| 345 |
+
|
| 346 |
+
Args:
|
| 347 |
+
num_features: number of features or channels :math:`C` of the input
|
| 348 |
+
eps: a value added to the denominator for numerical stability.
|
| 349 |
+
Default: 1e-5
|
| 350 |
+
momentum: the value used for the running_mean and running_var
|
| 351 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 352 |
+
(i.e. simple average). Default: 0.1
|
| 353 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 354 |
+
learnable affine parameters. Default: ``True``
|
| 355 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 356 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 357 |
+
this module does not track such statistics, and initializes statistics
|
| 358 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 359 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 360 |
+
in both training and eval modes. Default: ``True``
|
| 361 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 362 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 363 |
+
|
| 364 |
+
Shape:
|
| 365 |
+
- Input: :math:`(N, C)` or :math:`(N, C, L)`, where :math:`N` is the batch size,
|
| 366 |
+
:math:`C` is the number of features or channels, and :math:`L` is the sequence length
|
| 367 |
+
- Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input)
|
| 368 |
+
|
| 369 |
+
Examples::
|
| 370 |
+
|
| 371 |
+
>>> # With Learnable Parameters
|
| 372 |
+
>>> m = nn.BatchNorm1d(100)
|
| 373 |
+
>>> # Without Learnable Parameters
|
| 374 |
+
>>> m = nn.BatchNorm1d(100, affine=False)
|
| 375 |
+
>>> input = torch.randn(20, 100)
|
| 376 |
+
>>> output = m(input)
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
def _check_input_dim(self, input) -> None:
|
| 380 |
+
if input.dim() != 2 and input.dim() != 3:
|
| 381 |
+
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
class LazyBatchNorm1d(_LazyNormBase, _BatchNorm):
|
| 385 |
+
r"""A :class:`torch.nn.BatchNorm1d` module with lazy initialization.
|
| 386 |
+
|
| 387 |
+
Lazy initialization based on the ``num_features`` argument of the :class:`BatchNorm1d` that is inferred
|
| 388 |
+
from the ``input.size(1)``.
|
| 389 |
+
The attributes that will be lazily initialized are `weight`, `bias`,
|
| 390 |
+
`running_mean` and `running_var`.
|
| 391 |
+
|
| 392 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 393 |
+
on lazy modules and their limitations.
|
| 394 |
+
|
| 395 |
+
Args:
|
| 396 |
+
eps: a value added to the denominator for numerical stability.
|
| 397 |
+
Default: 1e-5
|
| 398 |
+
momentum: the value used for the running_mean and running_var
|
| 399 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 400 |
+
(i.e. simple average). Default: 0.1
|
| 401 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 402 |
+
learnable affine parameters. Default: ``True``
|
| 403 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 404 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 405 |
+
this module does not track such statistics, and initializes statistics
|
| 406 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 407 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 408 |
+
in both training and eval modes. Default: ``True``
|
| 409 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 410 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 411 |
+
"""
|
| 412 |
+
|
| 413 |
+
cls_to_become = BatchNorm1d # type: ignore[assignment]
|
| 414 |
+
|
| 415 |
+
def _check_input_dim(self, input) -> None:
|
| 416 |
+
if input.dim() != 2 and input.dim() != 3:
|
| 417 |
+
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class BatchNorm2d(_BatchNorm):
|
| 421 |
+
r"""Applies Batch Normalization over a 4D input.
|
| 422 |
+
|
| 423 |
+
4D is a mini-batch of 2D inputs
|
| 424 |
+
with additional channel dimension. Method described in the paper
|
| 425 |
+
`Batch Normalization: Accelerating Deep Network Training by Reducing
|
| 426 |
+
Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .
|
| 427 |
+
|
| 428 |
+
.. math::
|
| 429 |
+
|
| 430 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 431 |
+
|
| 432 |
+
The mean and standard-deviation are calculated per-dimension over
|
| 433 |
+
the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 434 |
+
of size `C` (where `C` is the input size). By default, the elements of :math:`\gamma` are set
|
| 435 |
+
to 1 and the elements of :math:`\beta` are set to 0. At train time in the forward pass, the
|
| 436 |
+
standard-deviation is calculated via the biased estimator, equivalent to
|
| 437 |
+
``torch.var(input, correction=0)``. However, the value stored in the moving average of the
|
| 438 |
+
standard-deviation is calculated via the unbiased estimator, equivalent to
|
| 439 |
+
``torch.var(input, correction=1)``.
|
| 440 |
+
|
| 441 |
+
Also by default, during training this layer keeps running estimates of its
|
| 442 |
+
computed mean and variance, which are then used for normalization during
|
| 443 |
+
evaluation. The running estimates are kept with a default :attr:`momentum`
|
| 444 |
+
of 0.1.
|
| 445 |
+
|
| 446 |
+
If :attr:`track_running_stats` is set to ``False``, this layer then does not
|
| 447 |
+
keep running estimates, and batch statistics are instead used during
|
| 448 |
+
evaluation time as well.
|
| 449 |
+
|
| 450 |
+
.. note::
|
| 451 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 452 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 453 |
+
update rule for running statistics here is
|
| 454 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 455 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 456 |
+
new observed value.
|
| 457 |
+
|
| 458 |
+
Because the Batch Normalization is done over the `C` dimension, computing statistics
|
| 459 |
+
on `(N, H, W)` slices, it's common terminology to call this Spatial Batch Normalization.
|
| 460 |
+
|
| 461 |
+
Args:
|
| 462 |
+
num_features: :math:`C` from an expected input of size
|
| 463 |
+
:math:`(N, C, H, W)`
|
| 464 |
+
eps: a value added to the denominator for numerical stability.
|
| 465 |
+
Default: 1e-5
|
| 466 |
+
momentum: the value used for the running_mean and running_var
|
| 467 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 468 |
+
(i.e. simple average). Default: 0.1
|
| 469 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 470 |
+
learnable affine parameters. Default: ``True``
|
| 471 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 472 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 473 |
+
this module does not track such statistics, and initializes statistics
|
| 474 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 475 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 476 |
+
in both training and eval modes. Default: ``True``
|
| 477 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 478 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 479 |
+
|
| 480 |
+
Shape:
|
| 481 |
+
- Input: :math:`(N, C, H, W)`
|
| 482 |
+
- Output: :math:`(N, C, H, W)` (same shape as input)
|
| 483 |
+
|
| 484 |
+
Examples::
|
| 485 |
+
|
| 486 |
+
>>> # With Learnable Parameters
|
| 487 |
+
>>> m = nn.BatchNorm2d(100)
|
| 488 |
+
>>> # Without Learnable Parameters
|
| 489 |
+
>>> m = nn.BatchNorm2d(100, affine=False)
|
| 490 |
+
>>> input = torch.randn(20, 100, 35, 45)
|
| 491 |
+
>>> output = m(input)
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
def _check_input_dim(self, input) -> None:
|
| 495 |
+
if input.dim() != 4:
|
| 496 |
+
raise ValueError(f"expected 4D input (got {input.dim()}D input)")
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
class LazyBatchNorm2d(_LazyNormBase, _BatchNorm):
|
| 500 |
+
r"""A :class:`torch.nn.BatchNorm2d` module with lazy initialization.
|
| 501 |
+
|
| 502 |
+
Lazy initialization is done for the ``num_features`` argument of the :class:`BatchNorm2d` that is inferred
|
| 503 |
+
from the ``input.size(1)``.
|
| 504 |
+
The attributes that will be lazily initialized are `weight`, `bias`,
|
| 505 |
+
`running_mean` and `running_var`.
|
| 506 |
+
|
| 507 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 508 |
+
on lazy modules and their limitations.
|
| 509 |
+
|
| 510 |
+
Args:
|
| 511 |
+
eps: a value added to the denominator for numerical stability.
|
| 512 |
+
Default: 1e-5
|
| 513 |
+
momentum: the value used for the running_mean and running_var
|
| 514 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 515 |
+
(i.e. simple average). Default: 0.1
|
| 516 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 517 |
+
learnable affine parameters. Default: ``True``
|
| 518 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 519 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 520 |
+
this module does not track such statistics, and initializes statistics
|
| 521 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 522 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 523 |
+
in both training and eval modes. Default: ``True``
|
| 524 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 525 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
cls_to_become = BatchNorm2d # type: ignore[assignment]
|
| 529 |
+
|
| 530 |
+
def _check_input_dim(self, input) -> None:
|
| 531 |
+
if input.dim() != 4:
|
| 532 |
+
raise ValueError(f"expected 4D input (got {input.dim()}D input)")
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class BatchNorm3d(_BatchNorm):
|
| 536 |
+
r"""Applies Batch Normalization over a 5D input.
|
| 537 |
+
|
| 538 |
+
5D is a mini-batch of 3D inputs with additional channel dimension as described in the paper
|
| 539 |
+
`Batch Normalization: Accelerating Deep Network Training by Reducing
|
| 540 |
+
Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .
|
| 541 |
+
|
| 542 |
+
.. math::
|
| 543 |
+
|
| 544 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 545 |
+
|
| 546 |
+
The mean and standard-deviation are calculated per-dimension over
|
| 547 |
+
the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 548 |
+
of size `C` (where `C` is the input size). By default, the elements of :math:`\gamma` are set
|
| 549 |
+
to 1 and the elements of :math:`\beta` are set to 0. At train time in the forward pass, the
|
| 550 |
+
standard-deviation is calculated via the biased estimator, equivalent to
|
| 551 |
+
``torch.var(input, correction=0)``. However, the value stored in the moving average of the
|
| 552 |
+
standard-deviation is calculated via the unbiased estimator, equivalent to
|
| 553 |
+
``torch.var(input, correction=1)``.
|
| 554 |
+
|
| 555 |
+
Also by default, during training this layer keeps running estimates of its
|
| 556 |
+
computed mean and variance, which are then used for normalization during
|
| 557 |
+
evaluation. The running estimates are kept with a default :attr:`momentum`
|
| 558 |
+
of 0.1.
|
| 559 |
+
|
| 560 |
+
If :attr:`track_running_stats` is set to ``False``, this layer then does not
|
| 561 |
+
keep running estimates, and batch statistics are instead used during
|
| 562 |
+
evaluation time as well.
|
| 563 |
+
|
| 564 |
+
.. note::
|
| 565 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 566 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 567 |
+
update rule for running statistics here is
|
| 568 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 569 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 570 |
+
new observed value.
|
| 571 |
+
|
| 572 |
+
Because the Batch Normalization is done over the `C` dimension, computing statistics
|
| 573 |
+
on `(N, D, H, W)` slices, it's common terminology to call this Volumetric Batch Normalization
|
| 574 |
+
or Spatio-temporal Batch Normalization.
|
| 575 |
+
|
| 576 |
+
Args:
|
| 577 |
+
num_features: :math:`C` from an expected input of size
|
| 578 |
+
:math:`(N, C, D, H, W)`
|
| 579 |
+
eps: a value added to the denominator for numerical stability.
|
| 580 |
+
Default: 1e-5
|
| 581 |
+
momentum: the value used for the running_mean and running_var
|
| 582 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 583 |
+
(i.e. simple average). Default: 0.1
|
| 584 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 585 |
+
learnable affine parameters. Default: ``True``
|
| 586 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 587 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 588 |
+
this module does not track such statistics, and initializes statistics
|
| 589 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 590 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 591 |
+
in both training and eval modes. Default: ``True``
|
| 592 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 593 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 594 |
+
|
| 595 |
+
Shape:
|
| 596 |
+
- Input: :math:`(N, C, D, H, W)`
|
| 597 |
+
- Output: :math:`(N, C, D, H, W)` (same shape as input)
|
| 598 |
+
|
| 599 |
+
Examples::
|
| 600 |
+
|
| 601 |
+
>>> # With Learnable Parameters
|
| 602 |
+
>>> m = nn.BatchNorm3d(100)
|
| 603 |
+
>>> # Without Learnable Parameters
|
| 604 |
+
>>> m = nn.BatchNorm3d(100, affine=False)
|
| 605 |
+
>>> input = torch.randn(20, 100, 35, 45, 10)
|
| 606 |
+
>>> output = m(input)
|
| 607 |
+
"""
|
| 608 |
+
|
| 609 |
+
def _check_input_dim(self, input) -> None:
|
| 610 |
+
if input.dim() != 5:
|
| 611 |
+
raise ValueError(f"expected 5D input (got {input.dim()}D input)")
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
class LazyBatchNorm3d(_LazyNormBase, _BatchNorm):
|
| 615 |
+
r"""A :class:`torch.nn.BatchNorm3d` module with lazy initialization.
|
| 616 |
+
|
| 617 |
+
Lazy initialization is done for the ``num_features`` argument of the :class:`BatchNorm3d` that is inferred
|
| 618 |
+
from the ``input.size(1)``.
|
| 619 |
+
The attributes that will be lazily initialized are `weight`, `bias`,
|
| 620 |
+
`running_mean` and `running_var`.
|
| 621 |
+
|
| 622 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 623 |
+
on lazy modules and their limitations.
|
| 624 |
+
|
| 625 |
+
Args:
|
| 626 |
+
eps: a value added to the denominator for numerical stability.
|
| 627 |
+
Default: 1e-5
|
| 628 |
+
momentum: the value used for the running_mean and running_var
|
| 629 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 630 |
+
(i.e. simple average). Default: 0.1
|
| 631 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 632 |
+
learnable affine parameters. Default: ``True``
|
| 633 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 634 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 635 |
+
this module does not track such statistics, and initializes statistics
|
| 636 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 637 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 638 |
+
in both training and eval modes. Default: ``True``
|
| 639 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 640 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 641 |
+
"""
|
| 642 |
+
|
| 643 |
+
cls_to_become = BatchNorm3d # type: ignore[assignment]
|
| 644 |
+
|
| 645 |
+
def _check_input_dim(self, input) -> None:
|
| 646 |
+
if input.dim() != 5:
|
| 647 |
+
raise ValueError(f"expected 5D input (got {input.dim()}D input)")
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
class SyncBatchNorm(_BatchNorm):
|
| 651 |
+
r"""Applies Batch Normalization over a N-Dimensional input.
|
| 652 |
+
|
| 653 |
+
The N-D input is a mini-batch of [N-2]D inputs with additional channel dimension as described in the paper
|
| 654 |
+
`Batch Normalization: Accelerating Deep Network Training by Reducing
|
| 655 |
+
Internal Covariate Shift <https://arxiv.org/abs/1502.03167>`__ .
|
| 656 |
+
|
| 657 |
+
.. math::
|
| 658 |
+
|
| 659 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 660 |
+
|
| 661 |
+
The mean and standard-deviation are calculated per-dimension over all
|
| 662 |
+
mini-batches of the same process groups. :math:`\gamma` and :math:`\beta`
|
| 663 |
+
are learnable parameter vectors of size `C` (where `C` is the input size).
|
| 664 |
+
By default, the elements of :math:`\gamma` are sampled from
|
| 665 |
+
:math:`\mathcal{U}(0, 1)` and the elements of :math:`\beta` are set to 0.
|
| 666 |
+
The standard-deviation is calculated via the biased estimator, equivalent to
|
| 667 |
+
`torch.var(input, correction=0)`.
|
| 668 |
+
|
| 669 |
+
Also by default, during training this layer keeps running estimates of its
|
| 670 |
+
computed mean and variance, which are then used for normalization during
|
| 671 |
+
evaluation. The running estimates are kept with a default :attr:`momentum`
|
| 672 |
+
of 0.1.
|
| 673 |
+
|
| 674 |
+
If :attr:`track_running_stats` is set to ``False``, this layer then does not
|
| 675 |
+
keep running estimates, and batch statistics are instead used during
|
| 676 |
+
evaluation time as well.
|
| 677 |
+
|
| 678 |
+
.. note::
|
| 679 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 680 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 681 |
+
update rule for running statistics here is
|
| 682 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 683 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 684 |
+
new observed value.
|
| 685 |
+
|
| 686 |
+
Because the Batch Normalization is done for each channel in the ``C`` dimension, computing
|
| 687 |
+
statistics on ``(N, +)`` slices, it's common terminology to call this Volumetric Batch
|
| 688 |
+
Normalization or Spatio-temporal Batch Normalization.
|
| 689 |
+
|
| 690 |
+
Currently :class:`SyncBatchNorm` only supports
|
| 691 |
+
:class:`~torch.nn.DistributedDataParallel` (DDP) with single GPU per process. Use
|
| 692 |
+
:meth:`torch.nn.SyncBatchNorm.convert_sync_batchnorm()` to convert
|
| 693 |
+
:attr:`BatchNorm*D` layer to :class:`SyncBatchNorm` before wrapping
|
| 694 |
+
Network with DDP.
|
| 695 |
+
|
| 696 |
+
Args:
|
| 697 |
+
num_features: :math:`C` from an expected input of size
|
| 698 |
+
:math:`(N, C, +)`
|
| 699 |
+
eps: a value added to the denominator for numerical stability.
|
| 700 |
+
Default: ``1e-5``
|
| 701 |
+
momentum: the value used for the running_mean and running_var
|
| 702 |
+
computation. Can be set to ``None`` for cumulative moving average
|
| 703 |
+
(i.e. simple average). Default: 0.1
|
| 704 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 705 |
+
learnable affine parameters. Default: ``True``
|
| 706 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 707 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 708 |
+
this module does not track such statistics, and initializes statistics
|
| 709 |
+
buffers :attr:`running_mean` and :attr:`running_var` as ``None``.
|
| 710 |
+
When these buffers are ``None``, this module always uses batch statistics.
|
| 711 |
+
in both training and eval modes. Default: ``True``
|
| 712 |
+
process_group: synchronization of stats happen within each process group
|
| 713 |
+
individually. Default behavior is synchronization across the whole
|
| 714 |
+
world
|
| 715 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 716 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 717 |
+
|
| 718 |
+
Shape:
|
| 719 |
+
- Input: :math:`(N, C, +)`
|
| 720 |
+
- Output: :math:`(N, C, +)` (same shape as input)
|
| 721 |
+
|
| 722 |
+
.. note::
|
| 723 |
+
Synchronization of batchnorm statistics occurs only while training, i.e.
|
| 724 |
+
synchronization is disabled when ``model.eval()`` is set or if
|
| 725 |
+
``self.training`` is otherwise ``False``.
|
| 726 |
+
|
| 727 |
+
Examples::
|
| 728 |
+
|
| 729 |
+
>>> # xdoctest: +SKIP
|
| 730 |
+
>>> # With Learnable Parameters
|
| 731 |
+
>>> m = nn.SyncBatchNorm(100)
|
| 732 |
+
>>> # creating process group (optional)
|
| 733 |
+
>>> # ranks is a list of int identifying rank ids.
|
| 734 |
+
>>> ranks = list(range(8))
|
| 735 |
+
>>> r1, r2 = ranks[:4], ranks[4:]
|
| 736 |
+
>>> # Note: every rank calls into new_group for every
|
| 737 |
+
>>> # process group created, even if that rank is not
|
| 738 |
+
>>> # part of the group.
|
| 739 |
+
>>> process_groups = [torch.distributed.new_group(pids) for pids in [r1, r2]]
|
| 740 |
+
>>> process_group = process_groups[0 if dist.get_rank() <= 3 else 1]
|
| 741 |
+
>>> # Without Learnable Parameters
|
| 742 |
+
>>> m = nn.BatchNorm3d(100, affine=False, process_group=process_group)
|
| 743 |
+
>>> input = torch.randn(20, 100, 35, 45, 10)
|
| 744 |
+
>>> output = m(input)
|
| 745 |
+
|
| 746 |
+
>>> # network is nn.BatchNorm layer
|
| 747 |
+
>>> sync_bn_network = nn.SyncBatchNorm.convert_sync_batchnorm(network, process_group)
|
| 748 |
+
>>> # only single gpu per process is currently supported
|
| 749 |
+
>>> ddp_sync_bn_network = torch.nn.parallel.DistributedDataParallel(
|
| 750 |
+
>>> sync_bn_network,
|
| 751 |
+
>>> device_ids=[args.local_rank],
|
| 752 |
+
>>> output_device=args.local_rank)
|
| 753 |
+
"""
|
| 754 |
+
|
| 755 |
+
def __init__(
|
| 756 |
+
self,
|
| 757 |
+
num_features: int,
|
| 758 |
+
eps: float = 1e-5,
|
| 759 |
+
momentum: float | None = 0.1,
|
| 760 |
+
affine: bool = True,
|
| 761 |
+
track_running_stats: bool = True,
|
| 762 |
+
process_group: Any | None = None,
|
| 763 |
+
device=None,
|
| 764 |
+
dtype=None,
|
| 765 |
+
*,
|
| 766 |
+
bias: bool = True,
|
| 767 |
+
) -> None:
|
| 768 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 769 |
+
super().__init__(
|
| 770 |
+
num_features,
|
| 771 |
+
eps,
|
| 772 |
+
momentum,
|
| 773 |
+
affine,
|
| 774 |
+
track_running_stats,
|
| 775 |
+
**factory_kwargs,
|
| 776 |
+
bias=bias,
|
| 777 |
+
)
|
| 778 |
+
self.process_group = process_group
|
| 779 |
+
|
| 780 |
+
def _check_input_dim(self, input) -> None:
|
| 781 |
+
if input.dim() < 2:
|
| 782 |
+
raise ValueError(f"expected at least 2D input (got {input.dim()}D input)")
|
| 783 |
+
|
| 784 |
+
def _check_non_zero_input_channels(self, input) -> None:
|
| 785 |
+
if input.size(1) == 0:
|
| 786 |
+
raise ValueError(
|
| 787 |
+
"SyncBatchNorm number of input channels should be non-zero"
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 791 |
+
"""
|
| 792 |
+
Runs the forward pass.
|
| 793 |
+
"""
|
| 794 |
+
self._check_input_dim(input)
|
| 795 |
+
self._check_non_zero_input_channels(input)
|
| 796 |
+
|
| 797 |
+
# exponential_average_factor is set to self.momentum
|
| 798 |
+
# (when it is available) only so that it gets updated
|
| 799 |
+
# in ONNX graph when this node is exported to ONNX.
|
| 800 |
+
if self.momentum is None:
|
| 801 |
+
exponential_average_factor = 0.0
|
| 802 |
+
else:
|
| 803 |
+
exponential_average_factor = self.momentum
|
| 804 |
+
|
| 805 |
+
if self.training and self.track_running_stats:
|
| 806 |
+
if self.num_batches_tracked is None:
|
| 807 |
+
raise AssertionError("num_batches_tracked must not be None")
|
| 808 |
+
self.num_batches_tracked.add_(1)
|
| 809 |
+
if self.momentum is None: # use cumulative moving average
|
| 810 |
+
exponential_average_factor = 1.0 / self.num_batches_tracked.item()
|
| 811 |
+
else: # use exponential moving average
|
| 812 |
+
exponential_average_factor = self.momentum
|
| 813 |
+
|
| 814 |
+
r"""
|
| 815 |
+
Decide whether the mini-batch stats should be used for normalization rather than the buffers.
|
| 816 |
+
Mini-batch stats are used in training mode, and in eval mode when buffers are None.
|
| 817 |
+
"""
|
| 818 |
+
if self.training:
|
| 819 |
+
bn_training = True
|
| 820 |
+
else:
|
| 821 |
+
bn_training = (self.running_mean is None) and (self.running_var is None)
|
| 822 |
+
|
| 823 |
+
r"""
|
| 824 |
+
Buffers are only updated if they are to be tracked and we are in training mode. Thus they only need to be
|
| 825 |
+
passed when the update should occur (i.e. in training mode when they are tracked), or when buffer stats are
|
| 826 |
+
used for normalization (i.e. in eval mode when buffers are not None).
|
| 827 |
+
"""
|
| 828 |
+
# If buffers are not to be tracked, ensure that they won't be updated
|
| 829 |
+
running_mean = (
|
| 830 |
+
self.running_mean if not self.training or self.track_running_stats else None
|
| 831 |
+
)
|
| 832 |
+
running_var = (
|
| 833 |
+
self.running_var if not self.training or self.track_running_stats else None
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
# Don't sync batchnorm stats in inference mode (model.eval()).
|
| 837 |
+
need_sync = (
|
| 838 |
+
bn_training
|
| 839 |
+
and self.training
|
| 840 |
+
and torch.distributed.is_available()
|
| 841 |
+
and torch.distributed.is_initialized()
|
| 842 |
+
)
|
| 843 |
+
if need_sync:
|
| 844 |
+
# currently only GPU/PrivateUse1 input is supported
|
| 845 |
+
if input.device.type not in [
|
| 846 |
+
"cuda",
|
| 847 |
+
"hpu",
|
| 848 |
+
"xpu",
|
| 849 |
+
torch._C._get_privateuse1_backend_name(),
|
| 850 |
+
]:
|
| 851 |
+
raise ValueError(
|
| 852 |
+
"SyncBatchNorm expected input tensor to be on GPU or XPU or "
|
| 853 |
+
f"{torch._C._get_privateuse1_backend_name()}"
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
process_group = torch.distributed.group.WORLD
|
| 857 |
+
if self.process_group:
|
| 858 |
+
process_group = self.process_group
|
| 859 |
+
world_size = torch.distributed.get_world_size(process_group)
|
| 860 |
+
need_sync = world_size > 1
|
| 861 |
+
|
| 862 |
+
# fallback to framework BN when synchronization is not necessary
|
| 863 |
+
if not need_sync:
|
| 864 |
+
return F.batch_norm(
|
| 865 |
+
input,
|
| 866 |
+
running_mean,
|
| 867 |
+
running_var,
|
| 868 |
+
self.weight,
|
| 869 |
+
self.bias,
|
| 870 |
+
bn_training,
|
| 871 |
+
exponential_average_factor,
|
| 872 |
+
self.eps,
|
| 873 |
+
)
|
| 874 |
+
else:
|
| 875 |
+
if not bn_training:
|
| 876 |
+
raise AssertionError("bn_training must be True")
|
| 877 |
+
return sync_batch_norm.apply(
|
| 878 |
+
input,
|
| 879 |
+
self.weight,
|
| 880 |
+
self.bias,
|
| 881 |
+
running_mean,
|
| 882 |
+
running_var,
|
| 883 |
+
self.eps,
|
| 884 |
+
exponential_average_factor,
|
| 885 |
+
process_group, # type: ignore[possibly-undefined]
|
| 886 |
+
world_size, # type: ignore[possibly-undefined]
|
| 887 |
+
)
|
| 888 |
+
|
| 889 |
+
@classmethod
|
| 890 |
+
def convert_sync_batchnorm(cls, module, process_group=None):
|
| 891 |
+
r"""Converts all :attr:`BatchNorm*D` layers in the model to :class:`torch.nn.SyncBatchNorm` layers.
|
| 892 |
+
|
| 893 |
+
Args:
|
| 894 |
+
module (nn.Module): module containing one or more :attr:`BatchNorm*D` layers
|
| 895 |
+
process_group (optional): process group to scope synchronization,
|
| 896 |
+
default is the whole world
|
| 897 |
+
|
| 898 |
+
Returns:
|
| 899 |
+
The original :attr:`module` with the converted :class:`torch.nn.SyncBatchNorm`
|
| 900 |
+
layers. If the original :attr:`module` is a :attr:`BatchNorm*D` layer,
|
| 901 |
+
a new :class:`torch.nn.SyncBatchNorm` layer object will be returned
|
| 902 |
+
instead.
|
| 903 |
+
|
| 904 |
+
Example::
|
| 905 |
+
|
| 906 |
+
>>> # Network with nn.BatchNorm layer
|
| 907 |
+
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
|
| 908 |
+
>>> module = torch.nn.Sequential(
|
| 909 |
+
>>> torch.nn.Linear(20, 100),
|
| 910 |
+
>>> torch.nn.BatchNorm1d(100),
|
| 911 |
+
>>> ).cuda()
|
| 912 |
+
>>> # creating process group (optional)
|
| 913 |
+
>>> # ranks is a list of int identifying rank ids.
|
| 914 |
+
>>> ranks = list(range(8))
|
| 915 |
+
>>> r1, r2 = ranks[:4], ranks[4:]
|
| 916 |
+
>>> # Note: every rank calls into new_group for every
|
| 917 |
+
>>> # process group created, even if that rank is not
|
| 918 |
+
>>> # part of the group.
|
| 919 |
+
>>> # xdoctest: +SKIP("distributed")
|
| 920 |
+
>>> process_groups = [torch.distributed.new_group(pids) for pids in [r1, r2]]
|
| 921 |
+
>>> process_group = process_groups[0 if dist.get_rank() <= 3 else 1]
|
| 922 |
+
>>> sync_bn_module = torch.nn.SyncBatchNorm.convert_sync_batchnorm(module, process_group)
|
| 923 |
+
|
| 924 |
+
"""
|
| 925 |
+
module_output = module
|
| 926 |
+
if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
|
| 927 |
+
module_output = torch.nn.SyncBatchNorm(
|
| 928 |
+
module.num_features,
|
| 929 |
+
module.eps,
|
| 930 |
+
module.momentum,
|
| 931 |
+
module.affine,
|
| 932 |
+
module.track_running_stats,
|
| 933 |
+
process_group,
|
| 934 |
+
bias=module.bias is not None,
|
| 935 |
+
)
|
| 936 |
+
if module.affine:
|
| 937 |
+
with torch.no_grad():
|
| 938 |
+
module_output.weight = module.weight
|
| 939 |
+
module_output.bias = module.bias
|
| 940 |
+
module_output.running_mean = module.running_mean
|
| 941 |
+
module_output.running_var = module.running_var
|
| 942 |
+
module_output.num_batches_tracked = module.num_batches_tracked
|
| 943 |
+
module_output.training = module.training
|
| 944 |
+
if hasattr(module, "qconfig"):
|
| 945 |
+
module_output.qconfig = module.qconfig
|
| 946 |
+
for name, child in module.named_children():
|
| 947 |
+
module_output.add_module(
|
| 948 |
+
name, cls.convert_sync_batchnorm(child, process_group)
|
| 949 |
+
)
|
| 950 |
+
del module
|
| 951 |
+
return module_output
|
.venv/lib/python3.12/site-packages/torch/nn/modules/channelshuffle.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
|
| 4 |
+
from .module import Module
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["ChannelShuffle"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ChannelShuffle(Module):
|
| 11 |
+
r"""Divides and rearranges the channels in a tensor.
|
| 12 |
+
|
| 13 |
+
This operation divides the channels in a tensor of shape :math:`(N, C, *)`
|
| 14 |
+
into g groups as :math:`(N, \frac{C}{g}, g, *)` and shuffles them,
|
| 15 |
+
while retaining the original tensor shape in the final output.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
groups (int): number of groups to divide channels in.
|
| 19 |
+
|
| 20 |
+
Examples::
|
| 21 |
+
|
| 22 |
+
>>> channel_shuffle = nn.ChannelShuffle(2)
|
| 23 |
+
>>> input = torch.arange(1, 17, dtype=torch.float32).view(1, 4, 2, 2)
|
| 24 |
+
>>> input
|
| 25 |
+
tensor([[[[ 1., 2.],
|
| 26 |
+
[ 3., 4.]],
|
| 27 |
+
[[ 5., 6.],
|
| 28 |
+
[ 7., 8.]],
|
| 29 |
+
[[ 9., 10.],
|
| 30 |
+
[11., 12.]],
|
| 31 |
+
[[13., 14.],
|
| 32 |
+
[15., 16.]]]])
|
| 33 |
+
>>> output = channel_shuffle(input)
|
| 34 |
+
>>> output
|
| 35 |
+
tensor([[[[ 1., 2.],
|
| 36 |
+
[ 3., 4.]],
|
| 37 |
+
[[ 9., 10.],
|
| 38 |
+
[11., 12.]],
|
| 39 |
+
[[ 5., 6.],
|
| 40 |
+
[ 7., 8.]],
|
| 41 |
+
[[13., 14.],
|
| 42 |
+
[15., 16.]]]])
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
__constants__ = ["groups"]
|
| 46 |
+
groups: int
|
| 47 |
+
|
| 48 |
+
def __init__(self, groups: int) -> None:
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.groups = groups
|
| 51 |
+
|
| 52 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 53 |
+
"""
|
| 54 |
+
Runs the forward pass.
|
| 55 |
+
"""
|
| 56 |
+
return F.channel_shuffle(input, self.groups)
|
| 57 |
+
|
| 58 |
+
def extra_repr(self) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Return the extra representation of the module.
|
| 61 |
+
"""
|
| 62 |
+
return f"groups={self.groups}"
|
.venv/lib/python3.12/site-packages/torch/nn/modules/container.py
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import operator
|
| 5 |
+
from collections import abc as container_abcs, OrderedDict
|
| 6 |
+
from itertools import chain, islice
|
| 7 |
+
from typing import Any, overload, TYPE_CHECKING, TypeVar
|
| 8 |
+
from typing_extensions import deprecated, Self
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch._jit_internal import _copy_to_script_wrapper
|
| 12 |
+
from torch.nn.parameter import Parameter
|
| 13 |
+
|
| 14 |
+
from .module import Module
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from collections.abc import Iterable, Iterator, Mapping
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
"Container",
|
| 23 |
+
"Sequential",
|
| 24 |
+
"ModuleList",
|
| 25 |
+
"ModuleDict",
|
| 26 |
+
"ParameterList",
|
| 27 |
+
"ParameterDict",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
T = TypeVar("T", bound=Module)
|
| 31 |
+
_V = TypeVar("_V")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Copied from torch.nn.modules.module, required for a custom __repr__ for ModuleList
|
| 35 |
+
def _addindent(s_, numSpaces):
|
| 36 |
+
s = s_.split("\n")
|
| 37 |
+
# don't do anything for single-line stuff
|
| 38 |
+
if len(s) == 1:
|
| 39 |
+
return s_
|
| 40 |
+
first = s.pop(0)
|
| 41 |
+
s = [(numSpaces * " ") + line for line in s]
|
| 42 |
+
s = "\n".join(s)
|
| 43 |
+
s = first + "\n" + s
|
| 44 |
+
return s
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@deprecated(
|
| 48 |
+
"`nn.Container` is deprecated. "
|
| 49 |
+
"All of its functionality is now implemented in `nn.Module`. Subclass that instead.",
|
| 50 |
+
category=FutureWarning,
|
| 51 |
+
)
|
| 52 |
+
class Container(Module):
|
| 53 |
+
def __init__(self, **kwargs: Any) -> None:
|
| 54 |
+
super().__init__()
|
| 55 |
+
for key, value in kwargs.items():
|
| 56 |
+
self.add_module(key, value)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Sequential(Module):
|
| 60 |
+
r"""A sequential container.
|
| 61 |
+
|
| 62 |
+
Modules will be added to it in the order they are passed in the
|
| 63 |
+
constructor. Alternatively, an ``OrderedDict`` of modules can be
|
| 64 |
+
passed in. The ``forward()`` method of ``Sequential`` accepts any
|
| 65 |
+
input and forwards it to the first module it contains. It then
|
| 66 |
+
"chains" outputs to inputs sequentially for each subsequent module,
|
| 67 |
+
finally returning the output of the last module.
|
| 68 |
+
|
| 69 |
+
The value a ``Sequential`` provides over manually calling a sequence
|
| 70 |
+
of modules is that it allows treating the whole container as a
|
| 71 |
+
single module, such that performing a transformation on the
|
| 72 |
+
``Sequential`` applies to each of the modules it stores (which are
|
| 73 |
+
each a registered submodule of the ``Sequential``).
|
| 74 |
+
|
| 75 |
+
What's the difference between a ``Sequential`` and a
|
| 76 |
+
:class:`torch.nn.ModuleList`? A ``ModuleList`` is exactly what it
|
| 77 |
+
sounds like--a list for storing ``Module`` s! On the other hand,
|
| 78 |
+
the layers in a ``Sequential`` are connected in a cascading way.
|
| 79 |
+
|
| 80 |
+
Example::
|
| 81 |
+
|
| 82 |
+
# Using Sequential to create a small model. When `model` is run,
|
| 83 |
+
# input will first be passed to `Conv2d(1,20,5)`. The output of
|
| 84 |
+
# `Conv2d(1,20,5)` will be used as the input to the first
|
| 85 |
+
# `ReLU`; the output of the first `ReLU` will become the input
|
| 86 |
+
# for `Conv2d(20,64,5)`. Finally, the output of
|
| 87 |
+
# `Conv2d(20,64,5)` will be used as input to the second `ReLU`
|
| 88 |
+
model = nn.Sequential(
|
| 89 |
+
nn.Conv2d(1, 20, 5), nn.ReLU(), nn.Conv2d(20, 64, 5), nn.ReLU()
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Using Sequential with OrderedDict. This is functionally the
|
| 93 |
+
# same as the above code
|
| 94 |
+
model = nn.Sequential(
|
| 95 |
+
OrderedDict(
|
| 96 |
+
[
|
| 97 |
+
("conv1", nn.Conv2d(1, 20, 5)),
|
| 98 |
+
("relu1", nn.ReLU()),
|
| 99 |
+
("conv2", nn.Conv2d(20, 64, 5)),
|
| 100 |
+
("relu2", nn.ReLU()),
|
| 101 |
+
]
|
| 102 |
+
)
|
| 103 |
+
)
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
_modules: dict[str, Module] # type: ignore[assignment]
|
| 107 |
+
|
| 108 |
+
@overload
|
| 109 |
+
def __init__(self, *args: Module) -> None: ...
|
| 110 |
+
|
| 111 |
+
@overload
|
| 112 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 113 |
+
def __init__(self, arg: OrderedDict[str, Module]) -> None: ...
|
| 114 |
+
|
| 115 |
+
def __init__(self, *args):
|
| 116 |
+
super().__init__()
|
| 117 |
+
if len(args) == 1 and isinstance(args[0], OrderedDict):
|
| 118 |
+
for key, module in args[0].items():
|
| 119 |
+
self.add_module(key, module)
|
| 120 |
+
else:
|
| 121 |
+
for idx, module in enumerate(args):
|
| 122 |
+
self.add_module(str(idx), module)
|
| 123 |
+
|
| 124 |
+
def _get_item_by_idx(self, iterator: Iterable[_V], idx: int) -> _V:
|
| 125 |
+
"""Get the idx-th item of the iterator."""
|
| 126 |
+
size = len(self)
|
| 127 |
+
idx = operator.index(idx)
|
| 128 |
+
if not -size <= idx < size:
|
| 129 |
+
raise IndexError(f"index {idx} is out of range")
|
| 130 |
+
idx %= size
|
| 131 |
+
return next(islice(iterator, idx, None))
|
| 132 |
+
|
| 133 |
+
@overload
|
| 134 |
+
def __getitem__(self, idx: slice) -> Sequential: ...
|
| 135 |
+
|
| 136 |
+
@overload
|
| 137 |
+
def __getitem__(self, idx: int) -> Module: ...
|
| 138 |
+
|
| 139 |
+
@_copy_to_script_wrapper
|
| 140 |
+
def __getitem__(self, idx: slice | int) -> Sequential | Module:
|
| 141 |
+
if isinstance(idx, slice):
|
| 142 |
+
return self.__class__(OrderedDict(list(self._modules.items())[idx]))
|
| 143 |
+
else:
|
| 144 |
+
return self._get_item_by_idx(self._modules.values(), idx)
|
| 145 |
+
|
| 146 |
+
def __setitem__(self, idx: int, module: Module) -> None:
|
| 147 |
+
key: str = self._get_item_by_idx(self._modules.keys(), idx)
|
| 148 |
+
return setattr(self, key, module)
|
| 149 |
+
|
| 150 |
+
def __delitem__(self, idx: slice | int) -> None:
|
| 151 |
+
if isinstance(idx, slice):
|
| 152 |
+
for key in list(self._modules.keys())[idx]:
|
| 153 |
+
delattr(self, key)
|
| 154 |
+
else:
|
| 155 |
+
key = self._get_item_by_idx(self._modules.keys(), idx)
|
| 156 |
+
delattr(self, key)
|
| 157 |
+
# To preserve numbering
|
| 158 |
+
str_indices = [str(i) for i in range(len(self._modules))]
|
| 159 |
+
self._modules = OrderedDict(
|
| 160 |
+
zip(str_indices, self._modules.values(), strict=True)
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
@_copy_to_script_wrapper
|
| 164 |
+
def __len__(self) -> int:
|
| 165 |
+
return len(self._modules)
|
| 166 |
+
|
| 167 |
+
def __add__(self, other) -> Sequential:
|
| 168 |
+
if isinstance(other, Sequential):
|
| 169 |
+
ret = Sequential()
|
| 170 |
+
for layer in self:
|
| 171 |
+
ret.append(layer)
|
| 172 |
+
for layer in other:
|
| 173 |
+
ret.append(layer)
|
| 174 |
+
return ret
|
| 175 |
+
else:
|
| 176 |
+
raise ValueError(
|
| 177 |
+
"add operator supports only objects "
|
| 178 |
+
f"of Sequential class, but {str(type(other))} is given."
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def pop(self, key: int | slice) -> Module:
|
| 182 |
+
"""
|
| 183 |
+
Pop ``key`` from self.
|
| 184 |
+
"""
|
| 185 |
+
v = self[key]
|
| 186 |
+
del self[key]
|
| 187 |
+
return v
|
| 188 |
+
|
| 189 |
+
def __iadd__(self, other) -> Self:
|
| 190 |
+
if isinstance(other, Sequential):
|
| 191 |
+
offset = len(self)
|
| 192 |
+
for i, module in enumerate(other):
|
| 193 |
+
self.add_module(str(i + offset), module)
|
| 194 |
+
return self
|
| 195 |
+
else:
|
| 196 |
+
raise ValueError(
|
| 197 |
+
"add operator supports only objects "
|
| 198 |
+
f"of Sequential class, but {str(type(other))} is given."
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def __mul__(self, other: int) -> Sequential:
|
| 202 |
+
if not isinstance(other, int):
|
| 203 |
+
raise TypeError(
|
| 204 |
+
f"unsupported operand type(s) for *: {type(self)} and {type(other)}"
|
| 205 |
+
)
|
| 206 |
+
elif other <= 0:
|
| 207 |
+
raise ValueError(
|
| 208 |
+
f"Non-positive multiplication factor {other} for {type(self)}"
|
| 209 |
+
)
|
| 210 |
+
else:
|
| 211 |
+
combined = Sequential()
|
| 212 |
+
offset = 0
|
| 213 |
+
for _ in range(other):
|
| 214 |
+
for module in self:
|
| 215 |
+
combined.add_module(str(offset), module)
|
| 216 |
+
offset += 1
|
| 217 |
+
return combined
|
| 218 |
+
|
| 219 |
+
def __rmul__(self, other: int) -> Sequential:
|
| 220 |
+
return self.__mul__(other)
|
| 221 |
+
|
| 222 |
+
def __imul__(self, other: int) -> Self:
|
| 223 |
+
if not isinstance(other, int):
|
| 224 |
+
raise TypeError(
|
| 225 |
+
f"unsupported operand type(s) for *: {type(self)} and {type(other)}"
|
| 226 |
+
)
|
| 227 |
+
elif other <= 0:
|
| 228 |
+
raise ValueError(
|
| 229 |
+
f"Non-positive multiplication factor {other} for {type(self)}"
|
| 230 |
+
)
|
| 231 |
+
else:
|
| 232 |
+
len_original = len(self)
|
| 233 |
+
offset = len(self)
|
| 234 |
+
for _ in range(other - 1):
|
| 235 |
+
for i in range(len_original):
|
| 236 |
+
self.add_module(str(i + offset), self._modules[str(i)])
|
| 237 |
+
offset += len_original
|
| 238 |
+
return self
|
| 239 |
+
|
| 240 |
+
@_copy_to_script_wrapper
|
| 241 |
+
def __dir__(self) -> list[str]:
|
| 242 |
+
keys = super().__dir__()
|
| 243 |
+
keys = [key for key in keys if not key.isdigit()]
|
| 244 |
+
return keys
|
| 245 |
+
|
| 246 |
+
@_copy_to_script_wrapper
|
| 247 |
+
def __iter__(self) -> Iterator[Module]:
|
| 248 |
+
return iter(self._modules.values())
|
| 249 |
+
|
| 250 |
+
# NB: We can't really type check this function as the type of input
|
| 251 |
+
# may change dynamically (as is tested in
|
| 252 |
+
# TestScript.test_sequential_intermediary_types). Cannot annotate
|
| 253 |
+
# with Any as TorchScript expects a more precise type
|
| 254 |
+
def forward(self, input):
|
| 255 |
+
"""
|
| 256 |
+
Runs the forward pass.
|
| 257 |
+
"""
|
| 258 |
+
for module in self:
|
| 259 |
+
input = module(input)
|
| 260 |
+
return input
|
| 261 |
+
|
| 262 |
+
def append(self, module: Module) -> Self:
|
| 263 |
+
r"""Append a given module to the end.
|
| 264 |
+
|
| 265 |
+
Args:
|
| 266 |
+
module (nn.Module): module to append
|
| 267 |
+
|
| 268 |
+
Example::
|
| 269 |
+
|
| 270 |
+
>>> import torch.nn as nn
|
| 271 |
+
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
|
| 272 |
+
>>> n.append(nn.Linear(3, 4))
|
| 273 |
+
Sequential(
|
| 274 |
+
(0): Linear(in_features=1, out_features=2, bias=True)
|
| 275 |
+
(1): Linear(in_features=2, out_features=3, bias=True)
|
| 276 |
+
(2): Linear(in_features=3, out_features=4, bias=True)
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
"""
|
| 280 |
+
self.add_module(str(len(self)), module)
|
| 281 |
+
return self
|
| 282 |
+
|
| 283 |
+
def insert(self, index: int, module: Module) -> Self:
|
| 284 |
+
"""
|
| 285 |
+
Inserts a module into the Sequential container at the specified index.
|
| 286 |
+
|
| 287 |
+
Args:
|
| 288 |
+
index (int): The index to insert the module.
|
| 289 |
+
module (Module): The module to be inserted.
|
| 290 |
+
|
| 291 |
+
Example::
|
| 292 |
+
|
| 293 |
+
>>> import torch.nn as nn
|
| 294 |
+
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
|
| 295 |
+
>>> n.insert(0, nn.Linear(3, 4))
|
| 296 |
+
Sequential(
|
| 297 |
+
(0): Linear(in_features=3, out_features=4, bias=True)
|
| 298 |
+
(1): Linear(in_features=1, out_features=2, bias=True)
|
| 299 |
+
(2): Linear(in_features=2, out_features=3, bias=True)
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
"""
|
| 303 |
+
if not isinstance(module, Module):
|
| 304 |
+
raise AssertionError(f"module should be of type: {Module}")
|
| 305 |
+
n = len(self._modules)
|
| 306 |
+
if not (-n <= index <= n):
|
| 307 |
+
raise IndexError(f"Index out of range: {index}")
|
| 308 |
+
if index < 0:
|
| 309 |
+
index += n
|
| 310 |
+
for i in range(n, index, -1):
|
| 311 |
+
self._modules[str(i)] = self._modules[str(i - 1)]
|
| 312 |
+
self._modules[str(index)] = module
|
| 313 |
+
return self
|
| 314 |
+
|
| 315 |
+
def extend(self, sequential: Iterable[Module]) -> Self:
|
| 316 |
+
"""
|
| 317 |
+
Extends the current Sequential container with layers from another Sequential container.
|
| 318 |
+
|
| 319 |
+
Args:
|
| 320 |
+
sequential (Sequential): A Sequential container whose layers will be added to the current container.
|
| 321 |
+
|
| 322 |
+
Example::
|
| 323 |
+
|
| 324 |
+
>>> import torch.nn as nn
|
| 325 |
+
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
|
| 326 |
+
>>> other = nn.Sequential(nn.Linear(3, 4), nn.Linear(4, 5))
|
| 327 |
+
>>> n.extend(other) # or `n + other`
|
| 328 |
+
Sequential(
|
| 329 |
+
(0): Linear(in_features=1, out_features=2, bias=True)
|
| 330 |
+
(1): Linear(in_features=2, out_features=3, bias=True)
|
| 331 |
+
(2): Linear(in_features=3, out_features=4, bias=True)
|
| 332 |
+
(3): Linear(in_features=4, out_features=5, bias=True)
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
"""
|
| 336 |
+
for layer in sequential:
|
| 337 |
+
self.append(layer)
|
| 338 |
+
return self
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class ModuleList(Module):
|
| 342 |
+
r"""Holds submodules in a list.
|
| 343 |
+
|
| 344 |
+
:class:`~torch.nn.ModuleList` can be indexed like a regular Python list, but
|
| 345 |
+
modules it contains are properly registered, and will be visible by all
|
| 346 |
+
:class:`~torch.nn.Module` methods.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
modules (iterable, optional): an iterable of modules to add
|
| 350 |
+
|
| 351 |
+
Example::
|
| 352 |
+
|
| 353 |
+
class MyModule(nn.Module):
|
| 354 |
+
def __init__(self) -> None:
|
| 355 |
+
super().__init__()
|
| 356 |
+
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
|
| 357 |
+
|
| 358 |
+
def forward(self, x):
|
| 359 |
+
# ModuleList can act as an iterable, or be indexed using ints
|
| 360 |
+
for i, l in enumerate(self.linears):
|
| 361 |
+
x = self.linears[i // 2](x) + l(x)
|
| 362 |
+
return x
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
_modules: dict[str, Module] # type: ignore[assignment]
|
| 366 |
+
|
| 367 |
+
def __init__(self, modules: Iterable[Module] | None = None) -> None:
|
| 368 |
+
super().__init__()
|
| 369 |
+
if modules is not None:
|
| 370 |
+
self += modules
|
| 371 |
+
|
| 372 |
+
def _get_abs_string_index(self, idx):
|
| 373 |
+
"""Get the absolute index for the list of modules."""
|
| 374 |
+
idx = operator.index(idx)
|
| 375 |
+
if not (-len(self) <= idx < len(self)):
|
| 376 |
+
raise IndexError(f"index {idx} is out of range")
|
| 377 |
+
if idx < 0:
|
| 378 |
+
idx += len(self)
|
| 379 |
+
return str(idx)
|
| 380 |
+
|
| 381 |
+
@overload
|
| 382 |
+
def __getitem__(self, idx: slice) -> ModuleList: ...
|
| 383 |
+
|
| 384 |
+
@overload
|
| 385 |
+
def __getitem__(self, idx: int) -> Module: ...
|
| 386 |
+
|
| 387 |
+
@_copy_to_script_wrapper
|
| 388 |
+
def __getitem__(self, idx: int | slice) -> Module | ModuleList:
|
| 389 |
+
if isinstance(idx, slice):
|
| 390 |
+
return self.__class__(list(self._modules.values())[idx])
|
| 391 |
+
else:
|
| 392 |
+
return self._modules[self._get_abs_string_index(idx)]
|
| 393 |
+
|
| 394 |
+
def __setitem__(self, idx: int, module: Module) -> None:
|
| 395 |
+
idx = self._get_abs_string_index(idx)
|
| 396 |
+
return setattr(self, str(idx), module)
|
| 397 |
+
|
| 398 |
+
def __delitem__(self, idx: int | slice) -> None:
|
| 399 |
+
if isinstance(idx, slice):
|
| 400 |
+
for k in range(len(self._modules))[idx]:
|
| 401 |
+
delattr(self, str(k))
|
| 402 |
+
else:
|
| 403 |
+
delattr(self, self._get_abs_string_index(idx))
|
| 404 |
+
# To preserve numbering, self._modules is being reconstructed with modules after deletion
|
| 405 |
+
str_indices = [str(i) for i in range(len(self._modules))]
|
| 406 |
+
self._modules = OrderedDict(
|
| 407 |
+
zip(str_indices, self._modules.values(), strict=True)
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
@_copy_to_script_wrapper
|
| 411 |
+
def __len__(self) -> int:
|
| 412 |
+
return len(self._modules)
|
| 413 |
+
|
| 414 |
+
@_copy_to_script_wrapper
|
| 415 |
+
def __iter__(self) -> Iterator[Module]:
|
| 416 |
+
return iter(self._modules.values())
|
| 417 |
+
|
| 418 |
+
def __iadd__(self, modules: Iterable[Module]) -> Self:
|
| 419 |
+
return self.extend(modules)
|
| 420 |
+
|
| 421 |
+
def __add__(self, other: Iterable[Module]) -> ModuleList:
|
| 422 |
+
combined = ModuleList()
|
| 423 |
+
for i, module in enumerate(chain(self, other)):
|
| 424 |
+
combined.add_module(str(i), module)
|
| 425 |
+
return combined
|
| 426 |
+
|
| 427 |
+
def __repr__(self) -> str:
|
| 428 |
+
"""Return a custom repr for ModuleList that compresses repeated module representations."""
|
| 429 |
+
list_of_reprs = [repr(item) for item in self]
|
| 430 |
+
if len(list_of_reprs) == 0:
|
| 431 |
+
return self._get_name() + "()"
|
| 432 |
+
|
| 433 |
+
start_end_indices = [[0, 0]]
|
| 434 |
+
repeated_blocks = [list_of_reprs[0]]
|
| 435 |
+
for i, r in enumerate(list_of_reprs[1:], 1):
|
| 436 |
+
if r == repeated_blocks[-1]:
|
| 437 |
+
start_end_indices[-1][1] += 1
|
| 438 |
+
continue
|
| 439 |
+
|
| 440 |
+
start_end_indices.append([i, i])
|
| 441 |
+
repeated_blocks.append(r)
|
| 442 |
+
|
| 443 |
+
lines = []
|
| 444 |
+
main_str = self._get_name() + "("
|
| 445 |
+
for (start_id, end_id), b in zip(
|
| 446 |
+
start_end_indices, repeated_blocks, strict=True
|
| 447 |
+
):
|
| 448 |
+
local_repr = f"({start_id}): {b}" # default repr
|
| 449 |
+
|
| 450 |
+
if start_id != end_id:
|
| 451 |
+
n = end_id - start_id + 1
|
| 452 |
+
local_repr = f"({start_id}-{end_id}): {n} x {b}"
|
| 453 |
+
|
| 454 |
+
local_repr = _addindent(local_repr, 2)
|
| 455 |
+
lines.append(local_repr)
|
| 456 |
+
|
| 457 |
+
main_str += "\n " + "\n ".join(lines) + "\n"
|
| 458 |
+
main_str += ")"
|
| 459 |
+
return main_str
|
| 460 |
+
|
| 461 |
+
@_copy_to_script_wrapper
|
| 462 |
+
def __dir__(self) -> list[str]:
|
| 463 |
+
keys = super().__dir__()
|
| 464 |
+
keys = [key for key in keys if not key.isdigit()]
|
| 465 |
+
return keys
|
| 466 |
+
|
| 467 |
+
def insert(self, index: int, module: Module) -> None:
|
| 468 |
+
r"""Insert a given module before a given index in the list.
|
| 469 |
+
|
| 470 |
+
Args:
|
| 471 |
+
index (int): index to insert.
|
| 472 |
+
module (nn.Module): module to insert
|
| 473 |
+
"""
|
| 474 |
+
for i in range(len(self._modules), index, -1):
|
| 475 |
+
self._modules[str(i)] = self._modules[str(i - 1)]
|
| 476 |
+
self._modules[str(index)] = module
|
| 477 |
+
|
| 478 |
+
def append(self, module: Module) -> Self:
|
| 479 |
+
r"""Append a given module to the end of the list.
|
| 480 |
+
|
| 481 |
+
Args:
|
| 482 |
+
module (nn.Module): module to append
|
| 483 |
+
"""
|
| 484 |
+
self.add_module(str(len(self)), module)
|
| 485 |
+
return self
|
| 486 |
+
|
| 487 |
+
def pop(self, key: int | slice) -> Module:
|
| 488 |
+
v = self[key]
|
| 489 |
+
del self[key]
|
| 490 |
+
return v
|
| 491 |
+
|
| 492 |
+
def extend(self, modules: Iterable[Module]) -> Self:
|
| 493 |
+
r"""Append modules from a Python iterable to the end of the list.
|
| 494 |
+
|
| 495 |
+
Args:
|
| 496 |
+
modules (iterable): iterable of modules to append
|
| 497 |
+
"""
|
| 498 |
+
if not isinstance(modules, container_abcs.Iterable):
|
| 499 |
+
raise TypeError(
|
| 500 |
+
"ModuleList.extend should be called with an "
|
| 501 |
+
"iterable, but got " + type(modules).__name__
|
| 502 |
+
)
|
| 503 |
+
offset = len(self)
|
| 504 |
+
for i, module in enumerate(modules):
|
| 505 |
+
self.add_module(str(offset + i), module)
|
| 506 |
+
return self
|
| 507 |
+
|
| 508 |
+
# remove forward altogether to fallback on Module's _forward_unimplemented
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
class ModuleDict(Module):
|
| 512 |
+
r"""Holds submodules in a dictionary.
|
| 513 |
+
|
| 514 |
+
:class:`~torch.nn.ModuleDict` can be indexed like a regular Python dictionary,
|
| 515 |
+
but modules it contains are properly registered, and will be visible by all
|
| 516 |
+
:class:`~torch.nn.Module` methods.
|
| 517 |
+
|
| 518 |
+
:class:`~torch.nn.ModuleDict` is an **ordered** dictionary that respects
|
| 519 |
+
|
| 520 |
+
* the order of insertion, and
|
| 521 |
+
|
| 522 |
+
* in :meth:`~torch.nn.ModuleDict.update`, the order of the merged
|
| 523 |
+
``OrderedDict``, ``dict`` or another
|
| 524 |
+
:class:`~torch.nn.ModuleDict` (the argument to
|
| 525 |
+
:meth:`~torch.nn.ModuleDict.update`).
|
| 526 |
+
|
| 527 |
+
Note that :meth:`~torch.nn.ModuleDict.update` with other unordered mapping
|
| 528 |
+
types does not preserve the order of the merged mapping.
|
| 529 |
+
|
| 530 |
+
Args:
|
| 531 |
+
modules (iterable, optional): a mapping (dictionary) of (string: module)
|
| 532 |
+
or an iterable of key-value pairs of type (string, module)
|
| 533 |
+
|
| 534 |
+
Example::
|
| 535 |
+
|
| 536 |
+
class MyModule(nn.Module):
|
| 537 |
+
def __init__(self) -> None:
|
| 538 |
+
super().__init__()
|
| 539 |
+
self.choices = nn.ModuleDict(
|
| 540 |
+
{"conv": nn.Conv2d(10, 10, 3), "pool": nn.MaxPool2d(3)}
|
| 541 |
+
)
|
| 542 |
+
self.activations = nn.ModuleDict(
|
| 543 |
+
[["lrelu", nn.LeakyReLU()], ["prelu", nn.PReLU()]]
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
def forward(self, x, choice, act):
|
| 547 |
+
x = self.choices[choice](x)
|
| 548 |
+
x = self.activations[act](x)
|
| 549 |
+
return x
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
_modules: dict[str, Module] # type: ignore[assignment]
|
| 553 |
+
|
| 554 |
+
def __init__(self, modules: Mapping[str, Module] | None = None) -> None:
|
| 555 |
+
super().__init__()
|
| 556 |
+
if modules is not None:
|
| 557 |
+
self.update(modules)
|
| 558 |
+
|
| 559 |
+
@_copy_to_script_wrapper
|
| 560 |
+
def __getitem__(self, key: str) -> Module:
|
| 561 |
+
return self._modules[key]
|
| 562 |
+
|
| 563 |
+
def __setitem__(self, key: str, module: Module) -> None:
|
| 564 |
+
self.add_module(key, module)
|
| 565 |
+
|
| 566 |
+
def __delitem__(self, key: str) -> None:
|
| 567 |
+
del self._modules[key]
|
| 568 |
+
|
| 569 |
+
@_copy_to_script_wrapper
|
| 570 |
+
def __len__(self) -> int:
|
| 571 |
+
return len(self._modules)
|
| 572 |
+
|
| 573 |
+
@_copy_to_script_wrapper
|
| 574 |
+
def __iter__(self) -> Iterator[str]:
|
| 575 |
+
return iter(self._modules)
|
| 576 |
+
|
| 577 |
+
@_copy_to_script_wrapper
|
| 578 |
+
def __contains__(self, key: str) -> bool:
|
| 579 |
+
return key in self._modules
|
| 580 |
+
|
| 581 |
+
def clear(self) -> None:
|
| 582 |
+
"""Remove all items from the ModuleDict."""
|
| 583 |
+
self._modules.clear()
|
| 584 |
+
|
| 585 |
+
def pop(self, key: str) -> Module:
|
| 586 |
+
r"""Remove key from the ModuleDict and return its module.
|
| 587 |
+
|
| 588 |
+
Args:
|
| 589 |
+
key (str): key to pop from the ModuleDict
|
| 590 |
+
"""
|
| 591 |
+
v = self[key]
|
| 592 |
+
del self[key]
|
| 593 |
+
return v
|
| 594 |
+
|
| 595 |
+
@_copy_to_script_wrapper
|
| 596 |
+
def keys(self) -> container_abcs.KeysView[str]:
|
| 597 |
+
r"""Return an iterable of the ModuleDict keys."""
|
| 598 |
+
return self._modules.keys()
|
| 599 |
+
|
| 600 |
+
@_copy_to_script_wrapper
|
| 601 |
+
def items(self) -> container_abcs.ItemsView[str, Module]:
|
| 602 |
+
r"""Return an iterable of the ModuleDict key/value pairs."""
|
| 603 |
+
return self._modules.items()
|
| 604 |
+
|
| 605 |
+
@_copy_to_script_wrapper
|
| 606 |
+
def values(self) -> container_abcs.ValuesView[Module]:
|
| 607 |
+
r"""Return an iterable of the ModuleDict values."""
|
| 608 |
+
return self._modules.values()
|
| 609 |
+
|
| 610 |
+
def update(self, modules: Mapping[str, Module]) -> None:
|
| 611 |
+
r"""Update the :class:`~torch.nn.ModuleDict` with key-value pairs from a mapping, overwriting existing keys.
|
| 612 |
+
|
| 613 |
+
.. note::
|
| 614 |
+
If :attr:`modules` is an ``OrderedDict``, a :class:`~torch.nn.ModuleDict`, or
|
| 615 |
+
an iterable of key-value pairs, the order of new elements in it is preserved.
|
| 616 |
+
|
| 617 |
+
Args:
|
| 618 |
+
modules (iterable): a mapping (dictionary) from string to :class:`~torch.nn.Module`,
|
| 619 |
+
or an iterable of key-value pairs of type (string, :class:`~torch.nn.Module`)
|
| 620 |
+
"""
|
| 621 |
+
if not isinstance(modules, container_abcs.Iterable):
|
| 622 |
+
raise TypeError(
|
| 623 |
+
"ModuleDict.update should be called with an "
|
| 624 |
+
"iterable of key/value pairs, but got " + type(modules).__name__
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
if isinstance(modules, (OrderedDict, ModuleDict, container_abcs.Mapping)):
|
| 628 |
+
for key, module in modules.items():
|
| 629 |
+
self[key] = module
|
| 630 |
+
else:
|
| 631 |
+
# modules here can be a list with two items
|
| 632 |
+
for j, m in enumerate(modules):
|
| 633 |
+
if not isinstance(m, container_abcs.Iterable):
|
| 634 |
+
raise TypeError(
|
| 635 |
+
"ModuleDict update sequence element "
|
| 636 |
+
"#" + str(j) + " should be Iterable; is" + type(m).__name__
|
| 637 |
+
)
|
| 638 |
+
# pyrefly: ignore [bad-argument-type]
|
| 639 |
+
if not len(m) == 2:
|
| 640 |
+
raise ValueError(
|
| 641 |
+
"ModuleDict update sequence element "
|
| 642 |
+
# pyrefly: ignore [bad-argument-type]
|
| 643 |
+
"#" + str(j) + " has length " + str(len(m)) + "; 2 is required"
|
| 644 |
+
)
|
| 645 |
+
# modules can be Mapping (what it's typed at), or a list: [(name1, module1), (name2, module2)]
|
| 646 |
+
# that's too cumbersome to type correctly with overloads, so we add an ignore here
|
| 647 |
+
self[m[0]] = m[1] # type: ignore[assignment]
|
| 648 |
+
|
| 649 |
+
# remove forward altogether to fallback on Module's _forward_unimplemented
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
class ParameterList(Module):
|
| 653 |
+
r"""Holds parameters in a list.
|
| 654 |
+
|
| 655 |
+
:class:`~torch.nn.ParameterList` can be used like a regular Python
|
| 656 |
+
list, but Tensors that are :class:`~torch.nn.Parameter` are properly registered,
|
| 657 |
+
and will be visible by all :class:`~torch.nn.Module` methods.
|
| 658 |
+
|
| 659 |
+
Note that the constructor, assigning an element of the list, the
|
| 660 |
+
:meth:`~torch.nn.ParameterList.append` method and the :meth:`~torch.nn.ParameterList.extend`
|
| 661 |
+
method will convert any :class:`~torch.Tensor` into :class:`~torch.nn.Parameter`.
|
| 662 |
+
|
| 663 |
+
Args:
|
| 664 |
+
parameters (iterable, optional): an iterable of elements to add to the list.
|
| 665 |
+
|
| 666 |
+
Example::
|
| 667 |
+
|
| 668 |
+
class MyModule(nn.Module):
|
| 669 |
+
def __init__(self) -> None:
|
| 670 |
+
super().__init__()
|
| 671 |
+
self.params = nn.ParameterList(
|
| 672 |
+
[nn.Parameter(torch.randn(10, 10)) for i in range(10)]
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
def forward(self, x):
|
| 676 |
+
# ParameterList can act as an iterable, or be indexed using ints
|
| 677 |
+
for i, p in enumerate(self.params):
|
| 678 |
+
x = self.params[i // 2].mm(x) + p.mm(x)
|
| 679 |
+
return x
|
| 680 |
+
"""
|
| 681 |
+
|
| 682 |
+
def __init__(self, values: Iterable[Any] | None = None) -> None:
|
| 683 |
+
super().__init__()
|
| 684 |
+
self._size = 0
|
| 685 |
+
if values is not None:
|
| 686 |
+
self += values
|
| 687 |
+
|
| 688 |
+
def _get_abs_string_index(self, idx):
|
| 689 |
+
"""Get the absolute index for the list of modules."""
|
| 690 |
+
idx = operator.index(idx)
|
| 691 |
+
if not (-len(self) <= idx < len(self)):
|
| 692 |
+
raise IndexError(f"index {idx} is out of range")
|
| 693 |
+
if idx < 0:
|
| 694 |
+
idx += len(self)
|
| 695 |
+
return str(idx)
|
| 696 |
+
|
| 697 |
+
@overload
|
| 698 |
+
def __getitem__(self, idx: int) -> Any: ...
|
| 699 |
+
|
| 700 |
+
@overload
|
| 701 |
+
# pyrefly: ignore [inconsistent-overload]
|
| 702 |
+
def __getitem__(self: T, idx: slice) -> T: ...
|
| 703 |
+
|
| 704 |
+
def __getitem__(self, idx):
|
| 705 |
+
if isinstance(idx, slice):
|
| 706 |
+
start, stop, step = idx.indices(len(self))
|
| 707 |
+
out = self.__class__()
|
| 708 |
+
for i in range(start, stop, step):
|
| 709 |
+
out.append(self[i])
|
| 710 |
+
return out
|
| 711 |
+
else:
|
| 712 |
+
idx = self._get_abs_string_index(idx)
|
| 713 |
+
return getattr(self, str(idx))
|
| 714 |
+
|
| 715 |
+
def __setitem__(self, idx: int, param: Any) -> None:
|
| 716 |
+
# Note that all other function that add an entry to the list part of
|
| 717 |
+
# the ParameterList end up here. So this is the only place where we need
|
| 718 |
+
# to wrap things into Parameter if needed.
|
| 719 |
+
# Objects added via setattr() are not in the list part and thus won't
|
| 720 |
+
# call into this function.
|
| 721 |
+
idx = self._get_abs_string_index(idx)
|
| 722 |
+
if isinstance(param, torch.Tensor) and not isinstance(param, Parameter):
|
| 723 |
+
param = Parameter(param)
|
| 724 |
+
return setattr(self, str(idx), param)
|
| 725 |
+
|
| 726 |
+
def __len__(self) -> int:
|
| 727 |
+
return self._size
|
| 728 |
+
|
| 729 |
+
def __iter__(self) -> Iterator[Any]:
|
| 730 |
+
return iter(self[i] for i in range(len(self)))
|
| 731 |
+
|
| 732 |
+
def __iadd__(self, parameters: Iterable[Any]) -> Self:
|
| 733 |
+
return self.extend(parameters)
|
| 734 |
+
|
| 735 |
+
def __dir__(self) -> list[str]:
|
| 736 |
+
keys = super().__dir__()
|
| 737 |
+
keys = [key for key in keys if not key.isdigit()]
|
| 738 |
+
return keys
|
| 739 |
+
|
| 740 |
+
def append(self, value: Any) -> Self:
|
| 741 |
+
"""Append a given value at the end of the list.
|
| 742 |
+
|
| 743 |
+
Args:
|
| 744 |
+
value (Any): value to append
|
| 745 |
+
"""
|
| 746 |
+
new_idx = len(self)
|
| 747 |
+
self._size += 1
|
| 748 |
+
self[new_idx] = value
|
| 749 |
+
return self
|
| 750 |
+
|
| 751 |
+
def extend(self, values: Iterable[Any]) -> Self:
|
| 752 |
+
"""Append values from a Python iterable to the end of the list.
|
| 753 |
+
|
| 754 |
+
Args:
|
| 755 |
+
values (iterable): iterable of values to append
|
| 756 |
+
"""
|
| 757 |
+
# Tensor is an iterable but we never want to unpack it here
|
| 758 |
+
if not isinstance(values, container_abcs.Iterable) or isinstance(
|
| 759 |
+
values, torch.Tensor
|
| 760 |
+
):
|
| 761 |
+
raise TypeError(
|
| 762 |
+
"ParameterList.extend should be called with an "
|
| 763 |
+
"iterable, but got " + type(values).__name__
|
| 764 |
+
)
|
| 765 |
+
for value in values:
|
| 766 |
+
self.append(value)
|
| 767 |
+
return self
|
| 768 |
+
|
| 769 |
+
def extra_repr(self) -> str:
|
| 770 |
+
"""
|
| 771 |
+
Return the extra representation of the module.
|
| 772 |
+
"""
|
| 773 |
+
child_lines = []
|
| 774 |
+
for k, p in enumerate(self):
|
| 775 |
+
if isinstance(p, torch.Tensor):
|
| 776 |
+
size_str = "x".join(str(size) for size in p.size())
|
| 777 |
+
if p.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]:
|
| 778 |
+
device_str = f" ({p.device})"
|
| 779 |
+
else:
|
| 780 |
+
device_str = ""
|
| 781 |
+
parastr = "{} containing: [{} of size {}{}]".format(
|
| 782 |
+
"Parameter" if isinstance(p, Parameter) else "Tensor",
|
| 783 |
+
p.dtype,
|
| 784 |
+
size_str,
|
| 785 |
+
device_str,
|
| 786 |
+
)
|
| 787 |
+
child_lines.append(" (" + str(k) + "): " + parastr)
|
| 788 |
+
else:
|
| 789 |
+
child_lines.append(
|
| 790 |
+
" (" + str(k) + "): Object of type: " + type(p).__name__
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
tmpstr = "\n".join(child_lines)
|
| 794 |
+
return tmpstr
|
| 795 |
+
|
| 796 |
+
def __call__(self, *args, **kwargs):
|
| 797 |
+
raise RuntimeError("ParameterList should not be called.")
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
class ParameterDict(Module):
|
| 801 |
+
r"""Holds parameters in a dictionary.
|
| 802 |
+
|
| 803 |
+
ParameterDict can be indexed like a regular Python dictionary, but Parameters it
|
| 804 |
+
contains are properly registered, and will be visible by all Module methods.
|
| 805 |
+
Other objects are treated as would be done by a regular Python dictionary
|
| 806 |
+
|
| 807 |
+
:class:`~torch.nn.ParameterDict` is an **ordered** dictionary.
|
| 808 |
+
:meth:`~torch.nn.ParameterDict.update` with other unordered mapping
|
| 809 |
+
types (e.g., Python's plain ``dict``) does not preserve the order of the
|
| 810 |
+
merged mapping. On the other hand, ``OrderedDict`` or another :class:`~torch.nn.ParameterDict`
|
| 811 |
+
will preserve their ordering.
|
| 812 |
+
|
| 813 |
+
Note that the constructor, assigning an element of the dictionary and the
|
| 814 |
+
:meth:`~torch.nn.ParameterDict.update` method will convert any :class:`~torch.Tensor` into
|
| 815 |
+
:class:`~torch.nn.Parameter`.
|
| 816 |
+
|
| 817 |
+
Args:
|
| 818 |
+
values (iterable, optional): a mapping (dictionary) of
|
| 819 |
+
(string : Any) or an iterable of key-value pairs
|
| 820 |
+
of type (string, Any)
|
| 821 |
+
|
| 822 |
+
Example::
|
| 823 |
+
|
| 824 |
+
class MyModule(nn.Module):
|
| 825 |
+
def __init__(self) -> None:
|
| 826 |
+
super().__init__()
|
| 827 |
+
self.params = nn.ParameterDict(
|
| 828 |
+
{
|
| 829 |
+
"left": nn.Parameter(torch.randn(5, 10)),
|
| 830 |
+
"right": nn.Parameter(torch.randn(5, 10)),
|
| 831 |
+
}
|
| 832 |
+
)
|
| 833 |
+
|
| 834 |
+
def forward(self, x, choice):
|
| 835 |
+
x = self.params[choice].mm(x)
|
| 836 |
+
return x
|
| 837 |
+
"""
|
| 838 |
+
|
| 839 |
+
def __init__(self, parameters: Any = None) -> None:
|
| 840 |
+
super().__init__()
|
| 841 |
+
self._keys: dict[str, None] = {}
|
| 842 |
+
if parameters is not None:
|
| 843 |
+
self.update(parameters)
|
| 844 |
+
|
| 845 |
+
def _key_to_attr(self, key: str) -> str:
|
| 846 |
+
if not isinstance(key, str):
|
| 847 |
+
raise TypeError(
|
| 848 |
+
"Index given to ParameterDict cannot be used as a key as it is "
|
| 849 |
+
f"not a string (type is '{type(key).__name__}'). Open an issue on "
|
| 850 |
+
"github if you need non-string keys."
|
| 851 |
+
)
|
| 852 |
+
else:
|
| 853 |
+
# Use the key as-is so that `.named_parameters()` returns the right thing
|
| 854 |
+
return key
|
| 855 |
+
|
| 856 |
+
def __getitem__(self, key: str) -> Any:
|
| 857 |
+
attr = self._key_to_attr(key)
|
| 858 |
+
return getattr(self, attr)
|
| 859 |
+
|
| 860 |
+
def __setitem__(self, key: str, value: Any) -> None:
|
| 861 |
+
# Note that all other function that add an entry to the dictionary part of
|
| 862 |
+
# the ParameterDict end up here. So this is the only place where we need
|
| 863 |
+
# to wrap things into Parameter if needed.
|
| 864 |
+
# Objects added via setattr() are not in the dictionary part and thus won't
|
| 865 |
+
# call into this function.
|
| 866 |
+
self._keys[key] = None
|
| 867 |
+
attr = self._key_to_attr(key)
|
| 868 |
+
if isinstance(value, torch.Tensor) and not isinstance(value, Parameter):
|
| 869 |
+
value = Parameter(value)
|
| 870 |
+
setattr(self, attr, value)
|
| 871 |
+
|
| 872 |
+
def __delitem__(self, key: str) -> None:
|
| 873 |
+
del self._keys[key]
|
| 874 |
+
attr = self._key_to_attr(key)
|
| 875 |
+
delattr(self, attr)
|
| 876 |
+
|
| 877 |
+
def __len__(self) -> int:
|
| 878 |
+
return len(self._keys)
|
| 879 |
+
|
| 880 |
+
def __iter__(self) -> Iterator[str]:
|
| 881 |
+
return iter(self._keys)
|
| 882 |
+
|
| 883 |
+
def __reversed__(self) -> Iterator[str]:
|
| 884 |
+
return reversed(self._keys)
|
| 885 |
+
|
| 886 |
+
def copy(self) -> ParameterDict:
|
| 887 |
+
"""Return a copy of this :class:`~torch.nn.ParameterDict` instance."""
|
| 888 |
+
# We have to use an OrderedDict because the ParameterDict constructor
|
| 889 |
+
# behaves differently on plain dict vs OrderedDict
|
| 890 |
+
return ParameterDict(OrderedDict((k, self[k]) for k in self._keys))
|
| 891 |
+
|
| 892 |
+
def __contains__(self, key: str) -> bool:
|
| 893 |
+
return key in self._keys
|
| 894 |
+
|
| 895 |
+
def setdefault(self, key: str, default: Any | None = None) -> Any:
|
| 896 |
+
"""Set the default for a key in the Parameterdict.
|
| 897 |
+
|
| 898 |
+
If key is in the ParameterDict, return its value.
|
| 899 |
+
If not, insert `key` with a parameter `default` and return `default`.
|
| 900 |
+
`default` defaults to `None`.
|
| 901 |
+
|
| 902 |
+
Args:
|
| 903 |
+
key (str): key to set default for
|
| 904 |
+
default (Any): the parameter set to the key
|
| 905 |
+
"""
|
| 906 |
+
if key not in self:
|
| 907 |
+
self[key] = default
|
| 908 |
+
return self[key]
|
| 909 |
+
|
| 910 |
+
def clear(self) -> None:
|
| 911 |
+
"""Remove all items from the ParameterDict."""
|
| 912 |
+
for k in self._keys.copy():
|
| 913 |
+
del self[k]
|
| 914 |
+
|
| 915 |
+
def pop(self, key: str) -> Any:
|
| 916 |
+
r"""Remove key from the ParameterDict and return its parameter.
|
| 917 |
+
|
| 918 |
+
Args:
|
| 919 |
+
key (str): key to pop from the ParameterDict
|
| 920 |
+
"""
|
| 921 |
+
v = self[key]
|
| 922 |
+
del self[key]
|
| 923 |
+
return v
|
| 924 |
+
|
| 925 |
+
def popitem(self) -> tuple[str, Any]:
|
| 926 |
+
"""Remove and return the last inserted `(key, parameter)` pair from the ParameterDict."""
|
| 927 |
+
k, _ = self._keys.popitem()
|
| 928 |
+
# We need the key in the _keys to be able to access/del
|
| 929 |
+
self._keys[k] = None
|
| 930 |
+
val = self[k]
|
| 931 |
+
del self[k]
|
| 932 |
+
return k, val
|
| 933 |
+
|
| 934 |
+
def get(self, key: str, default: Any | None = None) -> Any:
|
| 935 |
+
r"""Return the parameter associated with key if present. Otherwise return default if provided, None if not.
|
| 936 |
+
|
| 937 |
+
Args:
|
| 938 |
+
key (str): key to get from the ParameterDict
|
| 939 |
+
default (Parameter, optional): value to return if key not present
|
| 940 |
+
"""
|
| 941 |
+
return self[key] if key in self else default # noqa: SIM401
|
| 942 |
+
|
| 943 |
+
def fromkeys(
|
| 944 |
+
self, keys: Iterable[str], default: Any | None = None
|
| 945 |
+
) -> ParameterDict:
|
| 946 |
+
r"""Return a new ParameterDict with the keys provided.
|
| 947 |
+
|
| 948 |
+
Args:
|
| 949 |
+
keys (iterable, string): keys to make the new ParameterDict from
|
| 950 |
+
default (Parameter, optional): value to set for all keys
|
| 951 |
+
"""
|
| 952 |
+
return ParameterDict((k, default) for k in keys)
|
| 953 |
+
|
| 954 |
+
def keys(self) -> container_abcs.KeysView[str]:
|
| 955 |
+
r"""Return an iterable of the ParameterDict keys."""
|
| 956 |
+
return self._keys.keys()
|
| 957 |
+
|
| 958 |
+
def items(self) -> Iterable[tuple[str, Any]]:
|
| 959 |
+
r"""Return an iterable of the ParameterDict key/value pairs."""
|
| 960 |
+
return ((k, self[k]) for k in self._keys)
|
| 961 |
+
|
| 962 |
+
def values(self) -> Iterable[Any]:
|
| 963 |
+
r"""Return an iterable of the ParameterDict values."""
|
| 964 |
+
return (self[k] for k in self._keys)
|
| 965 |
+
|
| 966 |
+
def update(self, parameters: Mapping[str, Any] | ParameterDict) -> None:
|
| 967 |
+
r"""Update the :class:`~torch.nn.ParameterDict` with key-value pairs from ``parameters``, overwriting existing keys.
|
| 968 |
+
|
| 969 |
+
.. note::
|
| 970 |
+
If :attr:`parameters` is an ``OrderedDict``, a :class:`~torch.nn.ParameterDict`, or
|
| 971 |
+
an iterable of key-value pairs, the order of new elements in it is preserved.
|
| 972 |
+
|
| 973 |
+
Args:
|
| 974 |
+
parameters (iterable): a mapping (dictionary) from string to
|
| 975 |
+
:class:`~torch.nn.Parameter`, or an iterable of
|
| 976 |
+
key-value pairs of type (string, :class:`~torch.nn.Parameter`)
|
| 977 |
+
"""
|
| 978 |
+
if not isinstance(parameters, container_abcs.Iterable):
|
| 979 |
+
raise TypeError(
|
| 980 |
+
"ParametersDict.update should be called with an "
|
| 981 |
+
"iterable of key/value pairs, but got " + type(parameters).__name__
|
| 982 |
+
)
|
| 983 |
+
|
| 984 |
+
if isinstance(parameters, (OrderedDict, ParameterDict)):
|
| 985 |
+
for key, parameter in parameters.items():
|
| 986 |
+
self[key] = parameter
|
| 987 |
+
elif isinstance(parameters, container_abcs.Mapping):
|
| 988 |
+
for key, parameter in sorted(parameters.items()):
|
| 989 |
+
self[key] = parameter
|
| 990 |
+
else:
|
| 991 |
+
for j, p in enumerate(parameters):
|
| 992 |
+
if not isinstance(p, container_abcs.Iterable):
|
| 993 |
+
raise TypeError(
|
| 994 |
+
"ParameterDict update sequence element "
|
| 995 |
+
"#" + str(j) + " should be Iterable; is" + type(p).__name__
|
| 996 |
+
)
|
| 997 |
+
# pyrefly: ignore [bad-argument-type]
|
| 998 |
+
if not len(p) == 2:
|
| 999 |
+
raise ValueError(
|
| 1000 |
+
"ParameterDict update sequence element "
|
| 1001 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1002 |
+
"#" + str(j) + " has length " + str(len(p)) + "; 2 is required"
|
| 1003 |
+
)
|
| 1004 |
+
# parameters as length-2 list too cumbersome to type, see ModuleDict.update comment
|
| 1005 |
+
self[p[0]] = p[1] # type: ignore[assignment]
|
| 1006 |
+
|
| 1007 |
+
def extra_repr(self) -> str:
|
| 1008 |
+
child_lines = []
|
| 1009 |
+
for k, p in self.items():
|
| 1010 |
+
if isinstance(p, torch.Tensor):
|
| 1011 |
+
size_str = "x".join(str(size) for size in p.size())
|
| 1012 |
+
if p.device.type in ["cuda", torch._C._get_privateuse1_backend_name()]:
|
| 1013 |
+
device_str = f" ({p.device})"
|
| 1014 |
+
else:
|
| 1015 |
+
device_str = ""
|
| 1016 |
+
parastr = "{} containing: [{} of size {}{}]".format(
|
| 1017 |
+
"Parameter" if isinstance(p, Parameter) else "Tensor",
|
| 1018 |
+
torch.typename(p),
|
| 1019 |
+
size_str,
|
| 1020 |
+
device_str,
|
| 1021 |
+
)
|
| 1022 |
+
child_lines.append(" (" + str(k) + "): " + parastr)
|
| 1023 |
+
else:
|
| 1024 |
+
child_lines.append(
|
| 1025 |
+
" (" + str(k) + "): Object of type: " + type(p).__name__
|
| 1026 |
+
)
|
| 1027 |
+
tmpstr = "\n".join(child_lines)
|
| 1028 |
+
return tmpstr
|
| 1029 |
+
|
| 1030 |
+
def __call__(self, input):
|
| 1031 |
+
raise RuntimeError("ParameterDict should not be called.")
|
| 1032 |
+
|
| 1033 |
+
def __or__(self, other: ParameterDict) -> ParameterDict:
|
| 1034 |
+
copy = self.copy()
|
| 1035 |
+
copy.update(other)
|
| 1036 |
+
return copy
|
| 1037 |
+
|
| 1038 |
+
def __ror__(self, other: ParameterDict) -> ParameterDict:
|
| 1039 |
+
copy = other.copy()
|
| 1040 |
+
copy.update(self)
|
| 1041 |
+
return copy
|
| 1042 |
+
|
| 1043 |
+
def __ior__(self, other: ParameterDict) -> Self:
|
| 1044 |
+
self.update(other)
|
| 1045 |
+
return self
|
.venv/lib/python3.12/site-packages/torch/nn/modules/conv.py
ADDED
|
@@ -0,0 +1,1921 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
from typing import Literal
|
| 4 |
+
from typing_extensions import deprecated
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import Tensor
|
| 8 |
+
from torch._torch_docs import reproducibility_notes
|
| 9 |
+
from torch.nn import functional as F, init
|
| 10 |
+
from torch.nn.common_types import _size_1_t, _size_2_t, _size_3_t
|
| 11 |
+
from torch.nn.parameter import Parameter, UninitializedParameter
|
| 12 |
+
|
| 13 |
+
from .lazy import LazyModuleMixin
|
| 14 |
+
from .module import Module
|
| 15 |
+
from .utils import _pair, _reverse_repeat_tuple, _single, _triple
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"Conv1d",
|
| 20 |
+
"Conv2d",
|
| 21 |
+
"Conv3d",
|
| 22 |
+
"ConvTranspose1d",
|
| 23 |
+
"ConvTranspose2d",
|
| 24 |
+
"ConvTranspose3d",
|
| 25 |
+
"LazyConv1d",
|
| 26 |
+
"LazyConv2d",
|
| 27 |
+
"LazyConv3d",
|
| 28 |
+
"LazyConvTranspose1d",
|
| 29 |
+
"LazyConvTranspose2d",
|
| 30 |
+
"LazyConvTranspose3d",
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
convolution_notes = {
|
| 34 |
+
"groups_note": r"""* :attr:`groups` controls the connections between inputs and outputs.
|
| 35 |
+
:attr:`in_channels` and :attr:`out_channels` must both be divisible by
|
| 36 |
+
:attr:`groups`. For example,
|
| 37 |
+
|
| 38 |
+
* At groups=1, all inputs are convolved to all outputs.
|
| 39 |
+
* At groups=2, the operation becomes equivalent to having two conv
|
| 40 |
+
layers side by side, each seeing half the input channels
|
| 41 |
+
and producing half the output channels, and both subsequently
|
| 42 |
+
concatenated.
|
| 43 |
+
* At groups= :attr:`in_channels`, each input channel is convolved with
|
| 44 |
+
its own set of filters (of size
|
| 45 |
+
:math:`\frac{\text{out\_channels}}{\text{in\_channels}}`).""",
|
| 46 |
+
"depthwise_separable_note": r"""When `groups == in_channels` and `out_channels == K * in_channels`,
|
| 47 |
+
where `K` is a positive integer, this operation is also known as a "depthwise convolution".
|
| 48 |
+
|
| 49 |
+
In other words, for an input of size :math:`(N, C_{in}, L_{in})`,
|
| 50 |
+
a depthwise convolution with a depthwise multiplier `K` can be performed with the arguments
|
| 51 |
+
:math:`(C_\text{in}=C_\text{in}, C_\text{out}=C_\text{in} \times \text{K}, ..., \text{groups}=C_\text{in})`.""",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class _ConvNd(Module):
|
| 56 |
+
__constants__ = [
|
| 57 |
+
"stride",
|
| 58 |
+
"padding",
|
| 59 |
+
"dilation",
|
| 60 |
+
"groups",
|
| 61 |
+
"padding_mode",
|
| 62 |
+
"output_padding",
|
| 63 |
+
"in_channels",
|
| 64 |
+
"out_channels",
|
| 65 |
+
"kernel_size",
|
| 66 |
+
]
|
| 67 |
+
__annotations__ = {"bias": torch.Tensor | None}
|
| 68 |
+
|
| 69 |
+
def _conv_forward( # type: ignore[empty-body]
|
| 70 |
+
self, input: Tensor, weight: Tensor, bias: Tensor | None
|
| 71 |
+
) -> Tensor: ...
|
| 72 |
+
|
| 73 |
+
in_channels: int
|
| 74 |
+
_reversed_padding_repeated_twice: list[int]
|
| 75 |
+
out_channels: int
|
| 76 |
+
kernel_size: tuple[int, ...]
|
| 77 |
+
stride: tuple[int, ...]
|
| 78 |
+
padding: str | tuple[int, ...]
|
| 79 |
+
dilation: tuple[int, ...]
|
| 80 |
+
transposed: bool
|
| 81 |
+
output_padding: tuple[int, ...]
|
| 82 |
+
groups: int
|
| 83 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"]
|
| 84 |
+
weight: Tensor
|
| 85 |
+
bias: Tensor | None
|
| 86 |
+
|
| 87 |
+
def __init__(
|
| 88 |
+
self,
|
| 89 |
+
in_channels: int,
|
| 90 |
+
out_channels: int,
|
| 91 |
+
kernel_size: tuple[int, ...],
|
| 92 |
+
stride: tuple[int, ...],
|
| 93 |
+
padding: str | tuple[int, ...],
|
| 94 |
+
dilation: tuple[int, ...],
|
| 95 |
+
transposed: bool,
|
| 96 |
+
output_padding: tuple[int, ...],
|
| 97 |
+
groups: int,
|
| 98 |
+
bias: bool,
|
| 99 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"],
|
| 100 |
+
device=None,
|
| 101 |
+
dtype=None,
|
| 102 |
+
) -> None:
|
| 103 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 104 |
+
super().__init__()
|
| 105 |
+
if groups <= 0:
|
| 106 |
+
raise ValueError("groups must be a positive integer")
|
| 107 |
+
if in_channels % groups != 0:
|
| 108 |
+
raise ValueError("in_channels must be divisible by groups")
|
| 109 |
+
if out_channels % groups != 0:
|
| 110 |
+
raise ValueError("out_channels must be divisible by groups")
|
| 111 |
+
valid_padding_strings = {"same", "valid"}
|
| 112 |
+
if isinstance(padding, str):
|
| 113 |
+
if padding not in valid_padding_strings:
|
| 114 |
+
raise ValueError(
|
| 115 |
+
f"Invalid padding string {padding!r}, should be one of {valid_padding_strings}"
|
| 116 |
+
)
|
| 117 |
+
if padding == "same" and any(s != 1 for s in stride):
|
| 118 |
+
raise ValueError(
|
| 119 |
+
"padding='same' is not supported for strided convolutions"
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
valid_padding_modes = {"zeros", "reflect", "replicate", "circular"}
|
| 123 |
+
if padding_mode not in valid_padding_modes:
|
| 124 |
+
raise ValueError(
|
| 125 |
+
f"padding_mode must be one of {valid_padding_modes}, but got padding_mode='{padding_mode}'"
|
| 126 |
+
)
|
| 127 |
+
self.in_channels = in_channels
|
| 128 |
+
self.out_channels = out_channels
|
| 129 |
+
self.kernel_size = kernel_size
|
| 130 |
+
self.stride = stride
|
| 131 |
+
self.padding = padding
|
| 132 |
+
self.dilation = dilation
|
| 133 |
+
self.transposed = transposed
|
| 134 |
+
self.output_padding = output_padding
|
| 135 |
+
self.groups = groups
|
| 136 |
+
self.padding_mode = padding_mode
|
| 137 |
+
# `_reversed_padding_repeated_twice` is the padding to be passed to
|
| 138 |
+
# `F.pad` if needed (e.g., for non-zero padding types that are
|
| 139 |
+
# implemented as two ops: padding + conv). `F.pad` accepts paddings in
|
| 140 |
+
# reverse order than the dimension.
|
| 141 |
+
if isinstance(self.padding, str):
|
| 142 |
+
self._reversed_padding_repeated_twice = [0, 0] * len(kernel_size)
|
| 143 |
+
if padding == "same":
|
| 144 |
+
for d, k, i in zip(
|
| 145 |
+
dilation,
|
| 146 |
+
kernel_size,
|
| 147 |
+
range(len(kernel_size) - 1, -1, -1),
|
| 148 |
+
strict=False,
|
| 149 |
+
):
|
| 150 |
+
total_padding = d * (k - 1)
|
| 151 |
+
left_pad = total_padding // 2
|
| 152 |
+
self._reversed_padding_repeated_twice[2 * i] = left_pad
|
| 153 |
+
self._reversed_padding_repeated_twice[2 * i + 1] = (
|
| 154 |
+
total_padding - left_pad
|
| 155 |
+
)
|
| 156 |
+
else:
|
| 157 |
+
self._reversed_padding_repeated_twice = _reverse_repeat_tuple(
|
| 158 |
+
self.padding, 2
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
if transposed:
|
| 162 |
+
self.weight = Parameter(
|
| 163 |
+
torch.empty(
|
| 164 |
+
(in_channels, out_channels // groups, *kernel_size),
|
| 165 |
+
**factory_kwargs,
|
| 166 |
+
)
|
| 167 |
+
)
|
| 168 |
+
else:
|
| 169 |
+
self.weight = Parameter(
|
| 170 |
+
torch.empty(
|
| 171 |
+
(out_channels, in_channels // groups, *kernel_size),
|
| 172 |
+
**factory_kwargs,
|
| 173 |
+
)
|
| 174 |
+
)
|
| 175 |
+
if bias:
|
| 176 |
+
self.bias = Parameter(torch.empty(out_channels, **factory_kwargs))
|
| 177 |
+
else:
|
| 178 |
+
self.register_parameter("bias", None)
|
| 179 |
+
|
| 180 |
+
self.reset_parameters()
|
| 181 |
+
|
| 182 |
+
def reset_parameters(self) -> None:
|
| 183 |
+
# Use torch.no_grad() to allow in-place modification of weights/bias
|
| 184 |
+
with torch.no_grad():
|
| 185 |
+
# Check if the weight tensor is in channels_last_3d format to ensure numerical consistency
|
| 186 |
+
if not self.weight.is_contiguous():
|
| 187 |
+
# Use an empty contiguous buffer to optimize memory and ensure consistent initialization
|
| 188 |
+
temp_weight = torch.empty_like(
|
| 189 |
+
self.weight, memory_format=torch.contiguous_format
|
| 190 |
+
)
|
| 191 |
+
init.kaiming_uniform_(temp_weight, a=math.sqrt(5))
|
| 192 |
+
# Copy the initialized values back to the original tensor
|
| 193 |
+
self.weight.copy_(temp_weight)
|
| 194 |
+
else:
|
| 195 |
+
# Standard initialization for default contiguous memory format
|
| 196 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
| 197 |
+
if self.bias is not None:
|
| 198 |
+
# Bias initialization remains independent of weight memory format
|
| 199 |
+
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
|
| 200 |
+
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
|
| 201 |
+
init.uniform_(self.bias, -bound, bound)
|
| 202 |
+
|
| 203 |
+
def extra_repr(self):
|
| 204 |
+
s = "{in_channels}, {out_channels}, kernel_size={kernel_size}, stride={stride}"
|
| 205 |
+
if self.padding != (0,) * len(self.padding):
|
| 206 |
+
s += ", padding={padding}"
|
| 207 |
+
if self.dilation != (1,) * len(self.dilation):
|
| 208 |
+
s += ", dilation={dilation}"
|
| 209 |
+
if self.output_padding != (0,) * len(self.output_padding):
|
| 210 |
+
s += ", output_padding={output_padding}"
|
| 211 |
+
if self.groups != 1:
|
| 212 |
+
s += ", groups={groups}"
|
| 213 |
+
if self.bias is None:
|
| 214 |
+
s += ", bias=False"
|
| 215 |
+
if self.padding_mode != "zeros":
|
| 216 |
+
s += ", padding_mode={padding_mode}"
|
| 217 |
+
return s.format(**self.__dict__)
|
| 218 |
+
|
| 219 |
+
def __setstate__(self, state):
|
| 220 |
+
super().__setstate__(state)
|
| 221 |
+
if not hasattr(self, "padding_mode"):
|
| 222 |
+
self.padding_mode = "zeros"
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Conv1d(_ConvNd):
|
| 226 |
+
__doc__ = (
|
| 227 |
+
r"""Applies a 1D convolution over an input signal composed of several input
|
| 228 |
+
planes.
|
| 229 |
+
|
| 230 |
+
In the simplest case, the output value of the layer with input size
|
| 231 |
+
:math:`(N, C_{\text{in}}, L)` and output :math:`(N, C_{\text{out}}, L_{\text{out}})` can be
|
| 232 |
+
precisely described as:
|
| 233 |
+
|
| 234 |
+
.. math::
|
| 235 |
+
\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
|
| 236 |
+
\sum_{k = 0}^{C_{in} - 1} \text{weight}(C_{\text{out}_j}, k)
|
| 237 |
+
\star \text{input}(N_i, k)
|
| 238 |
+
|
| 239 |
+
where :math:`\star` is the valid `cross-correlation`_ operator,
|
| 240 |
+
:math:`N` is a batch size, :math:`C` denotes a number of channels,
|
| 241 |
+
:math:`L` is a length of signal sequence.
|
| 242 |
+
"""
|
| 243 |
+
+ r"""
|
| 244 |
+
|
| 245 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 246 |
+
|
| 247 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 248 |
+
|
| 249 |
+
* :attr:`stride` controls the stride for the cross-correlation, a single
|
| 250 |
+
number or a one-element tuple.
|
| 251 |
+
|
| 252 |
+
* :attr:`padding` controls the amount of padding applied to the input. It
|
| 253 |
+
can be either a string {{'valid', 'same'}} or a tuple of ints giving the
|
| 254 |
+
amount of implicit padding applied on both sides.
|
| 255 |
+
"""
|
| 256 |
+
"""
|
| 257 |
+
* :attr:`dilation` controls the spacing between the kernel points; also
|
| 258 |
+
known as the \u00e0 trous algorithm. It is harder to describe, but this `link`_
|
| 259 |
+
has a nice visualization of what :attr:`dilation` does.
|
| 260 |
+
"""
|
| 261 |
+
r"""
|
| 262 |
+
{groups_note}
|
| 263 |
+
|
| 264 |
+
Note:
|
| 265 |
+
{depthwise_separable_note}
|
| 266 |
+
Note:
|
| 267 |
+
{cudnn_reproducibility_note}
|
| 268 |
+
|
| 269 |
+
Note:
|
| 270 |
+
``padding='valid'`` is the same as no padding. ``padding='same'`` pads
|
| 271 |
+
the input so the output has the shape as the input. However, this mode
|
| 272 |
+
doesn't support any stride values other than 1.
|
| 273 |
+
|
| 274 |
+
Note:
|
| 275 |
+
This module supports complex data types i.e. ``complex32, complex64, complex128``.
|
| 276 |
+
|
| 277 |
+
Args:
|
| 278 |
+
in_channels (int): Number of channels in the input image
|
| 279 |
+
out_channels (int): Number of channels produced by the convolution
|
| 280 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 281 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 282 |
+
padding (int, tuple or str, optional): Padding added to both sides of
|
| 283 |
+
the input. Default: 0
|
| 284 |
+
dilation (int or tuple, optional): Spacing between kernel
|
| 285 |
+
elements. Default: 1
|
| 286 |
+
groups (int, optional): Number of blocked connections from input
|
| 287 |
+
channels to output channels. Default: 1
|
| 288 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the
|
| 289 |
+
output. Default: ``True``
|
| 290 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``,
|
| 291 |
+
``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 292 |
+
|
| 293 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 294 |
+
+ r"""
|
| 295 |
+
|
| 296 |
+
Shape:
|
| 297 |
+
- Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})`
|
| 298 |
+
- Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where
|
| 299 |
+
|
| 300 |
+
.. math::
|
| 301 |
+
L_{out} = \left\lfloor\frac{L_{in} + 2 \times \text{padding} - \text{dilation}
|
| 302 |
+
\times (\text{kernel\_size} - 1) - 1}{\text{stride}} + 1\right\rfloor
|
| 303 |
+
|
| 304 |
+
Attributes:
|
| 305 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 306 |
+
:math:`(\text{out\_channels},
|
| 307 |
+
\frac{\text{in\_channels}}{\text{groups}}, \text{kernel\_size})`.
|
| 308 |
+
The values of these weights are sampled from
|
| 309 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 310 |
+
:math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}`
|
| 311 |
+
bias (Tensor): the learnable bias of the module of shape
|
| 312 |
+
(out_channels). If :attr:`bias` is ``True``, then the values of these weights are
|
| 313 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 314 |
+
:math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}`
|
| 315 |
+
|
| 316 |
+
Examples::
|
| 317 |
+
|
| 318 |
+
>>> m = nn.Conv1d(16, 33, 3, stride=2)
|
| 319 |
+
>>> input = torch.randn(20, 16, 50)
|
| 320 |
+
>>> output = m(input)
|
| 321 |
+
|
| 322 |
+
.. _cross-correlation:
|
| 323 |
+
https://en.wikipedia.org/wiki/Cross-correlation
|
| 324 |
+
|
| 325 |
+
.. _link:
|
| 326 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 327 |
+
"""
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
def __init__(
|
| 331 |
+
self,
|
| 332 |
+
in_channels: int,
|
| 333 |
+
out_channels: int,
|
| 334 |
+
kernel_size: _size_1_t,
|
| 335 |
+
stride: _size_1_t = 1,
|
| 336 |
+
padding: str | _size_1_t = 0,
|
| 337 |
+
dilation: _size_1_t = 1,
|
| 338 |
+
groups: int = 1,
|
| 339 |
+
bias: bool = True,
|
| 340 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 341 |
+
device=None,
|
| 342 |
+
dtype=None,
|
| 343 |
+
) -> None:
|
| 344 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 345 |
+
# we create new variables below to make mypy happy since kernel_size has
|
| 346 |
+
# type Union[int, Tuple[int]] and kernel_size_ has type Tuple[int]
|
| 347 |
+
kernel_size_ = _single(kernel_size)
|
| 348 |
+
stride_ = _single(stride)
|
| 349 |
+
padding_ = padding if isinstance(padding, str) else _single(padding)
|
| 350 |
+
dilation_ = _single(dilation)
|
| 351 |
+
super().__init__(
|
| 352 |
+
in_channels,
|
| 353 |
+
out_channels,
|
| 354 |
+
kernel_size_,
|
| 355 |
+
stride_,
|
| 356 |
+
padding_,
|
| 357 |
+
dilation_,
|
| 358 |
+
False,
|
| 359 |
+
_single(0),
|
| 360 |
+
groups,
|
| 361 |
+
bias,
|
| 362 |
+
padding_mode,
|
| 363 |
+
**factory_kwargs,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def _conv_forward(self, input: Tensor, weight: Tensor, bias: Tensor | None):
|
| 367 |
+
if self.padding_mode != "zeros":
|
| 368 |
+
return F.conv1d(
|
| 369 |
+
F.pad(
|
| 370 |
+
input, self._reversed_padding_repeated_twice, mode=self.padding_mode
|
| 371 |
+
),
|
| 372 |
+
weight,
|
| 373 |
+
bias,
|
| 374 |
+
self.stride,
|
| 375 |
+
_single(0),
|
| 376 |
+
self.dilation,
|
| 377 |
+
self.groups,
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
return F.conv1d(
|
| 381 |
+
input, weight, bias, self.stride, self.padding, self.dilation, self.groups
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 385 |
+
return self._conv_forward(input, self.weight, self.bias)
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
class Conv2d(_ConvNd):
|
| 389 |
+
__doc__ = (
|
| 390 |
+
r"""Applies a 2D convolution over an input signal composed of several input
|
| 391 |
+
planes.
|
| 392 |
+
|
| 393 |
+
In the simplest case, the output value of the layer with input size
|
| 394 |
+
:math:`(N, C_{\text{in}}, H, W)` and output :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})`
|
| 395 |
+
can be precisely described as:
|
| 396 |
+
|
| 397 |
+
.. math::
|
| 398 |
+
\text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
|
| 399 |
+
\sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
where :math:`\star` is the valid 2D `cross-correlation`_ operator,
|
| 403 |
+
:math:`N` is a batch size, :math:`C_{\text{in}}` and :math:`C_{\text{out}}` correspond to
|
| 404 |
+
:attr:`in_channels` and :attr:`out_channels` respectively,
|
| 405 |
+
:math:`H` and :math:`W` are the input height and width in pixels.
|
| 406 |
+
See the Shape section below for how :math:`H_{\text{out}}` and :math:`W_{\text{out}}`
|
| 407 |
+
are derived from :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, and :attr:`dilation`.
|
| 408 |
+
"""
|
| 409 |
+
+ r"""
|
| 410 |
+
|
| 411 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 412 |
+
|
| 413 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 414 |
+
|
| 415 |
+
* :attr:`stride` controls the stride for the cross-correlation, a single
|
| 416 |
+
number or a tuple.
|
| 417 |
+
|
| 418 |
+
* :attr:`padding` controls the amount of padding applied to the input. It
|
| 419 |
+
can be either a string {{'valid', 'same'}} or an int / a tuple of ints giving the
|
| 420 |
+
amount of implicit padding applied on both sides.
|
| 421 |
+
"""
|
| 422 |
+
"""
|
| 423 |
+
* :attr:`dilation` controls the spacing between the kernel points; also
|
| 424 |
+
known as the \u00e0 trous algorithm. It is harder to describe, but this `link`_
|
| 425 |
+
has a nice visualization of what :attr:`dilation` does.
|
| 426 |
+
"""
|
| 427 |
+
r"""
|
| 428 |
+
|
| 429 |
+
{groups_note}
|
| 430 |
+
|
| 431 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
|
| 432 |
+
|
| 433 |
+
- a single ``int`` -- in which case the same value is used for the height and width dimension
|
| 434 |
+
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
|
| 435 |
+
and the second `int` for the width dimension
|
| 436 |
+
|
| 437 |
+
Note:
|
| 438 |
+
{depthwise_separable_note}
|
| 439 |
+
|
| 440 |
+
Note:
|
| 441 |
+
{cudnn_reproducibility_note}
|
| 442 |
+
|
| 443 |
+
Note:
|
| 444 |
+
``padding='valid'`` is the same as no padding. ``padding='same'`` pads
|
| 445 |
+
the input so the output has the shape as the input. However, this mode
|
| 446 |
+
doesn't support any stride values other than 1.
|
| 447 |
+
|
| 448 |
+
Note:
|
| 449 |
+
This module supports complex data types i.e. ``complex32, complex64, complex128``.
|
| 450 |
+
|
| 451 |
+
Args:
|
| 452 |
+
in_channels (int): Number of channels in the input image
|
| 453 |
+
out_channels (int): Number of channels produced by the convolution
|
| 454 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 455 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 456 |
+
padding (int, tuple or str, optional): Padding added to all four sides of
|
| 457 |
+
the input. Default: 0
|
| 458 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 459 |
+
groups (int, optional): Number of blocked connections from input
|
| 460 |
+
channels to output channels. Default: 1
|
| 461 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the
|
| 462 |
+
output. Default: ``True``
|
| 463 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``,
|
| 464 |
+
``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 465 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 466 |
+
+ r"""
|
| 467 |
+
|
| 468 |
+
Shape:
|
| 469 |
+
- Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})`
|
| 470 |
+
- Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where
|
| 471 |
+
|
| 472 |
+
.. math::
|
| 473 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] - \text{dilation}[0]
|
| 474 |
+
\times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
|
| 475 |
+
|
| 476 |
+
.. math::
|
| 477 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] - \text{dilation}[1]
|
| 478 |
+
\times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
|
| 479 |
+
|
| 480 |
+
Attributes:
|
| 481 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 482 |
+
:math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},`
|
| 483 |
+
:math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`.
|
| 484 |
+
The values of these weights are sampled from
|
| 485 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 486 |
+
:math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
|
| 487 |
+
bias (Tensor): the learnable bias of the module of shape
|
| 488 |
+
(out_channels). If :attr:`bias` is ``True``,
|
| 489 |
+
then the values of these weights are
|
| 490 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 491 |
+
:math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
|
| 492 |
+
|
| 493 |
+
Examples:
|
| 494 |
+
|
| 495 |
+
>>> # With square kernels and equal stride
|
| 496 |
+
>>> m = nn.Conv2d(16, 33, 3, stride=2)
|
| 497 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 498 |
+
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
|
| 499 |
+
>>> # non-square kernels and unequal stride and with padding and dilation
|
| 500 |
+
>>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
|
| 501 |
+
>>> input = torch.randn(20, 16, 50, 100)
|
| 502 |
+
>>> output = m(input)
|
| 503 |
+
|
| 504 |
+
.. _cross-correlation:
|
| 505 |
+
https://en.wikipedia.org/wiki/Cross-correlation
|
| 506 |
+
|
| 507 |
+
.. _link:
|
| 508 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 509 |
+
"""
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
def __init__(
|
| 513 |
+
self,
|
| 514 |
+
in_channels: int,
|
| 515 |
+
out_channels: int,
|
| 516 |
+
kernel_size: _size_2_t,
|
| 517 |
+
stride: _size_2_t = 1,
|
| 518 |
+
padding: str | _size_2_t = 0,
|
| 519 |
+
dilation: _size_2_t = 1,
|
| 520 |
+
groups: int = 1,
|
| 521 |
+
bias: bool = True,
|
| 522 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 523 |
+
device=None,
|
| 524 |
+
dtype=None,
|
| 525 |
+
) -> None:
|
| 526 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 527 |
+
kernel_size_ = _pair(kernel_size)
|
| 528 |
+
stride_ = _pair(stride)
|
| 529 |
+
padding_ = padding if isinstance(padding, str) else _pair(padding)
|
| 530 |
+
dilation_ = _pair(dilation)
|
| 531 |
+
super().__init__(
|
| 532 |
+
in_channels,
|
| 533 |
+
out_channels,
|
| 534 |
+
kernel_size_,
|
| 535 |
+
stride_,
|
| 536 |
+
padding_,
|
| 537 |
+
dilation_,
|
| 538 |
+
False,
|
| 539 |
+
_pair(0),
|
| 540 |
+
groups,
|
| 541 |
+
bias,
|
| 542 |
+
padding_mode,
|
| 543 |
+
**factory_kwargs,
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
def _conv_forward(self, input: Tensor, weight: Tensor, bias: Tensor | None):
|
| 547 |
+
if self.padding_mode != "zeros":
|
| 548 |
+
return F.conv2d(
|
| 549 |
+
F.pad(
|
| 550 |
+
input, self._reversed_padding_repeated_twice, mode=self.padding_mode
|
| 551 |
+
),
|
| 552 |
+
weight,
|
| 553 |
+
bias,
|
| 554 |
+
self.stride,
|
| 555 |
+
_pair(0),
|
| 556 |
+
self.dilation,
|
| 557 |
+
self.groups,
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
return F.conv2d(
|
| 561 |
+
input, weight, bias, self.stride, self.padding, self.dilation, self.groups
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 565 |
+
return self._conv_forward(input, self.weight, self.bias)
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class Conv3d(_ConvNd):
|
| 569 |
+
__doc__ = (
|
| 570 |
+
r"""Applies a 3D convolution over an input signal composed of several input
|
| 571 |
+
planes.
|
| 572 |
+
|
| 573 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C_{in}, D, H, W)`
|
| 574 |
+
and output :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` can be precisely described as:
|
| 575 |
+
|
| 576 |
+
.. math::
|
| 577 |
+
out(N_i, C_{out_j}) = bias(C_{out_j}) +
|
| 578 |
+
\sum_{k = 0}^{C_{in} - 1} weight(C_{out_j}, k) \star input(N_i, k)
|
| 579 |
+
|
| 580 |
+
where :math:`\star` is the valid 3D `cross-correlation`_ operator
|
| 581 |
+
"""
|
| 582 |
+
+ r"""
|
| 583 |
+
|
| 584 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 585 |
+
|
| 586 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 587 |
+
|
| 588 |
+
* :attr:`stride` controls the stride for the cross-correlation.
|
| 589 |
+
|
| 590 |
+
* :attr:`padding` controls the amount of padding applied to the input. It
|
| 591 |
+
can be either a string {{'valid', 'same'}} or a tuple of ints giving the
|
| 592 |
+
amount of implicit padding applied on both sides.
|
| 593 |
+
"""
|
| 594 |
+
"""
|
| 595 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 596 |
+
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
|
| 597 |
+
"""
|
| 598 |
+
r"""
|
| 599 |
+
|
| 600 |
+
{groups_note}
|
| 601 |
+
|
| 602 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
|
| 603 |
+
|
| 604 |
+
- a single ``int`` -- in which case the same value is used for the depth, height and width dimension
|
| 605 |
+
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
|
| 606 |
+
the second `int` for the height dimension and the third `int` for the width dimension
|
| 607 |
+
|
| 608 |
+
Note:
|
| 609 |
+
{depthwise_separable_note}
|
| 610 |
+
|
| 611 |
+
Note:
|
| 612 |
+
{cudnn_reproducibility_note}
|
| 613 |
+
|
| 614 |
+
Note:
|
| 615 |
+
``padding='valid'`` is the same as no padding. ``padding='same'`` pads
|
| 616 |
+
the input so the output has the shape as the input. However, this mode
|
| 617 |
+
doesn't support any stride values other than 1.
|
| 618 |
+
|
| 619 |
+
Note:
|
| 620 |
+
This module supports complex data types i.e. ``complex32, complex64, complex128``.
|
| 621 |
+
|
| 622 |
+
Args:
|
| 623 |
+
in_channels (int): Number of channels in the input image
|
| 624 |
+
out_channels (int): Number of channels produced by the convolution
|
| 625 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 626 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 627 |
+
padding (int, tuple or str, optional): Padding added to all six sides of
|
| 628 |
+
the input. Default: 0
|
| 629 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 630 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 631 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 632 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 633 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 634 |
+
+ r"""
|
| 635 |
+
|
| 636 |
+
Shape:
|
| 637 |
+
- Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})`
|
| 638 |
+
- Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or :math:`(C_{out}, D_{out}, H_{out}, W_{out})`,
|
| 639 |
+
where
|
| 640 |
+
|
| 641 |
+
.. math::
|
| 642 |
+
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0]
|
| 643 |
+
\times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
|
| 644 |
+
|
| 645 |
+
.. math::
|
| 646 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1]
|
| 647 |
+
\times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
|
| 648 |
+
|
| 649 |
+
.. math::
|
| 650 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2]
|
| 651 |
+
\times (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
|
| 652 |
+
|
| 653 |
+
Attributes:
|
| 654 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 655 |
+
:math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},`
|
| 656 |
+
:math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`.
|
| 657 |
+
The values of these weights are sampled from
|
| 658 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 659 |
+
:math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
|
| 660 |
+
bias (Tensor): the learnable bias of the module of shape (out_channels). If :attr:`bias` is ``True``,
|
| 661 |
+
then the values of these weights are
|
| 662 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 663 |
+
:math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
|
| 664 |
+
|
| 665 |
+
Examples::
|
| 666 |
+
|
| 667 |
+
>>> # With square kernels and equal stride
|
| 668 |
+
>>> m = nn.Conv3d(16, 33, 3, stride=2)
|
| 669 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 670 |
+
>>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
|
| 671 |
+
>>> input = torch.randn(20, 16, 10, 50, 100)
|
| 672 |
+
>>> output = m(input)
|
| 673 |
+
|
| 674 |
+
.. _cross-correlation:
|
| 675 |
+
https://en.wikipedia.org/wiki/Cross-correlation
|
| 676 |
+
|
| 677 |
+
.. _link:
|
| 678 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 679 |
+
"""
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
def __init__(
|
| 683 |
+
self,
|
| 684 |
+
in_channels: int,
|
| 685 |
+
out_channels: int,
|
| 686 |
+
kernel_size: _size_3_t,
|
| 687 |
+
stride: _size_3_t = 1,
|
| 688 |
+
padding: str | _size_3_t = 0,
|
| 689 |
+
dilation: _size_3_t = 1,
|
| 690 |
+
groups: int = 1,
|
| 691 |
+
bias: bool = True,
|
| 692 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 693 |
+
device=None,
|
| 694 |
+
dtype=None,
|
| 695 |
+
) -> None:
|
| 696 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 697 |
+
kernel_size_ = _triple(kernel_size)
|
| 698 |
+
stride_ = _triple(stride)
|
| 699 |
+
padding_ = padding if isinstance(padding, str) else _triple(padding)
|
| 700 |
+
dilation_ = _triple(dilation)
|
| 701 |
+
super().__init__(
|
| 702 |
+
in_channels,
|
| 703 |
+
out_channels,
|
| 704 |
+
kernel_size_,
|
| 705 |
+
stride_,
|
| 706 |
+
padding_,
|
| 707 |
+
dilation_,
|
| 708 |
+
False,
|
| 709 |
+
_triple(0),
|
| 710 |
+
groups,
|
| 711 |
+
bias,
|
| 712 |
+
padding_mode,
|
| 713 |
+
**factory_kwargs,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
def _conv_forward(self, input: Tensor, weight: Tensor, bias: Tensor | None):
|
| 717 |
+
if self.padding_mode != "zeros":
|
| 718 |
+
return F.conv3d(
|
| 719 |
+
F.pad(
|
| 720 |
+
input, self._reversed_padding_repeated_twice, mode=self.padding_mode
|
| 721 |
+
),
|
| 722 |
+
weight,
|
| 723 |
+
bias,
|
| 724 |
+
self.stride,
|
| 725 |
+
_triple(0),
|
| 726 |
+
self.dilation,
|
| 727 |
+
self.groups,
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
return F.conv3d(
|
| 731 |
+
input, weight, bias, self.stride, self.padding, self.dilation, self.groups
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 735 |
+
return self._conv_forward(input, self.weight, self.bias)
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
class _ConvTransposeNd(_ConvNd):
|
| 739 |
+
def __init__(
|
| 740 |
+
self,
|
| 741 |
+
in_channels,
|
| 742 |
+
out_channels,
|
| 743 |
+
kernel_size,
|
| 744 |
+
stride,
|
| 745 |
+
padding,
|
| 746 |
+
dilation,
|
| 747 |
+
transposed,
|
| 748 |
+
output_padding,
|
| 749 |
+
groups,
|
| 750 |
+
bias,
|
| 751 |
+
padding_mode,
|
| 752 |
+
device=None,
|
| 753 |
+
dtype=None,
|
| 754 |
+
) -> None:
|
| 755 |
+
if padding_mode != "zeros":
|
| 756 |
+
raise ValueError(
|
| 757 |
+
f'Only "zeros" padding mode is supported for {self.__class__.__name__}'
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 761 |
+
super().__init__(
|
| 762 |
+
in_channels,
|
| 763 |
+
out_channels,
|
| 764 |
+
kernel_size,
|
| 765 |
+
stride,
|
| 766 |
+
padding,
|
| 767 |
+
dilation,
|
| 768 |
+
transposed,
|
| 769 |
+
output_padding,
|
| 770 |
+
groups,
|
| 771 |
+
bias,
|
| 772 |
+
padding_mode,
|
| 773 |
+
**factory_kwargs,
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
# dilation being an optional parameter is for backwards
|
| 777 |
+
# compatibility
|
| 778 |
+
def _output_padding(
|
| 779 |
+
self,
|
| 780 |
+
input: Tensor,
|
| 781 |
+
output_size: list[int] | None,
|
| 782 |
+
stride: list[int],
|
| 783 |
+
padding: list[int],
|
| 784 |
+
kernel_size: list[int],
|
| 785 |
+
num_spatial_dims: int,
|
| 786 |
+
dilation: list[int] | None = None,
|
| 787 |
+
) -> list[int]:
|
| 788 |
+
if output_size is None:
|
| 789 |
+
ret = _single(self.output_padding) # converting to list if was not already
|
| 790 |
+
else:
|
| 791 |
+
has_batch_dim = input.dim() == num_spatial_dims + 2
|
| 792 |
+
num_non_spatial_dims = 2 if has_batch_dim else 1
|
| 793 |
+
if len(output_size) == num_non_spatial_dims + num_spatial_dims:
|
| 794 |
+
output_size = output_size[num_non_spatial_dims:]
|
| 795 |
+
if len(output_size) != num_spatial_dims:
|
| 796 |
+
raise ValueError(
|
| 797 |
+
f"ConvTranspose{num_spatial_dims}D: for {input.dim()}D input, output_size must have {num_spatial_dims} "
|
| 798 |
+
f"or {num_non_spatial_dims + num_spatial_dims} elements (got {len(output_size)})"
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
min_sizes = torch.jit.annotate(list[int], [])
|
| 802 |
+
max_sizes = torch.jit.annotate(list[int], [])
|
| 803 |
+
for d in range(num_spatial_dims):
|
| 804 |
+
dim_size = (
|
| 805 |
+
(input.size(d + num_non_spatial_dims) - 1) * stride[d]
|
| 806 |
+
- 2 * padding[d]
|
| 807 |
+
+ (dilation[d] if dilation is not None else 1)
|
| 808 |
+
* (kernel_size[d] - 1)
|
| 809 |
+
+ 1
|
| 810 |
+
)
|
| 811 |
+
min_sizes.append(dim_size)
|
| 812 |
+
max_sizes.append(min_sizes[d] + stride[d] - 1)
|
| 813 |
+
|
| 814 |
+
for i in range(len(output_size)):
|
| 815 |
+
size = output_size[i]
|
| 816 |
+
min_size = min_sizes[i]
|
| 817 |
+
max_size = max_sizes[i]
|
| 818 |
+
if size < min_size or size > max_size:
|
| 819 |
+
raise ValueError(
|
| 820 |
+
f"requested an output size of {output_size}, but valid sizes range "
|
| 821 |
+
f"from {min_sizes} to {max_sizes} (for an input of {input.size()[2:]})"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
res = torch.jit.annotate(list[int], [])
|
| 825 |
+
for d in range(num_spatial_dims):
|
| 826 |
+
res.append(output_size[d] - min_sizes[d])
|
| 827 |
+
|
| 828 |
+
ret = res
|
| 829 |
+
return ret
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
class ConvTranspose1d(_ConvTransposeNd):
|
| 833 |
+
__doc__ = (
|
| 834 |
+
r"""Applies a 1D transposed convolution operator over an input image
|
| 835 |
+
composed of several input planes.
|
| 836 |
+
|
| 837 |
+
This module can be seen as the gradient of Conv1d with respect to its input.
|
| 838 |
+
It is also known as a fractionally-strided convolution or
|
| 839 |
+
a deconvolution (although it is not an actual deconvolution operation as it does
|
| 840 |
+
not compute a true inverse of convolution). For more information, see the visualizations
|
| 841 |
+
`here`_ and the `Deconvolutional Networks`_ paper.
|
| 842 |
+
|
| 843 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 844 |
+
|
| 845 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 846 |
+
|
| 847 |
+
* :attr:`stride` controls the stride for the cross-correlation.
|
| 848 |
+
|
| 849 |
+
* :attr:`padding` controls the amount of implicit zero padding on both
|
| 850 |
+
sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
|
| 851 |
+
below for details.
|
| 852 |
+
|
| 853 |
+
* :attr:`output_padding` controls the additional size added to one side
|
| 854 |
+
of the output shape. See note below for details.
|
| 855 |
+
"""
|
| 856 |
+
"""
|
| 857 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 858 |
+
It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
|
| 859 |
+
"""
|
| 860 |
+
r"""
|
| 861 |
+
{groups_note}
|
| 862 |
+
|
| 863 |
+
Note:
|
| 864 |
+
The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
|
| 865 |
+
amount of zero padding to both sides of the input. This is set so that
|
| 866 |
+
when a :class:`~torch.nn.Conv1d` and a :class:`~torch.nn.ConvTranspose1d`
|
| 867 |
+
are initialized with same parameters, they are inverses of each other in
|
| 868 |
+
regard to the input and output shapes. However, when ``stride > 1``,
|
| 869 |
+
:class:`~torch.nn.Conv1d` maps multiple input shapes to the same output
|
| 870 |
+
shape. :attr:`output_padding` is provided to resolve this ambiguity by
|
| 871 |
+
effectively increasing the calculated output shape on one side. Note
|
| 872 |
+
that :attr:`output_padding` is only used to find output shape, but does
|
| 873 |
+
not actually add zero-padding to output.
|
| 874 |
+
|
| 875 |
+
Note:
|
| 876 |
+
In some circumstances when using the CUDA backend with CuDNN, this operator
|
| 877 |
+
may select a nondeterministic algorithm to increase performance. If this is
|
| 878 |
+
undesirable, you can try to make the operation deterministic (potentially at
|
| 879 |
+
a performance cost) by setting ``torch.backends.cudnn.deterministic =
|
| 880 |
+
True``.
|
| 881 |
+
Please see the notes on :doc:`/notes/randomness` for background.
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
Args:
|
| 885 |
+
in_channels (int): Number of channels in the input image
|
| 886 |
+
out_channels (int): Number of channels produced by the convolution
|
| 887 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 888 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 889 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 890 |
+
will be added to both sides of the input. Default: 0
|
| 891 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 892 |
+
of the output shape. Default: 0
|
| 893 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 894 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 895 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 896 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 897 |
+
+ r"""
|
| 898 |
+
|
| 899 |
+
Shape:
|
| 900 |
+
- Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})`
|
| 901 |
+
- Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where
|
| 902 |
+
|
| 903 |
+
.. math::
|
| 904 |
+
L_{out} = (L_{in} - 1) \times \text{stride} - 2 \times \text{padding} + \text{dilation}
|
| 905 |
+
\times (\text{kernel\_size} - 1) + \text{output\_padding} + 1
|
| 906 |
+
|
| 907 |
+
Attributes:
|
| 908 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 909 |
+
:math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
|
| 910 |
+
:math:`\text{kernel\_size})`.
|
| 911 |
+
The values of these weights are sampled from
|
| 912 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 913 |
+
:math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}`
|
| 914 |
+
bias (Tensor): the learnable bias of the module of shape (out_channels).
|
| 915 |
+
If :attr:`bias` is ``True``, then the values of these weights are
|
| 916 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 917 |
+
:math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}`
|
| 918 |
+
|
| 919 |
+
Examples::
|
| 920 |
+
|
| 921 |
+
>>> # With square kernels and equal stride
|
| 922 |
+
>>> m = nn.ConvTranspose1d(16, 33, 3, stride=2)
|
| 923 |
+
>>> input = torch.randn(20, 16, 50)
|
| 924 |
+
>>> output = m(input)
|
| 925 |
+
>>> # exact output size can be also specified as an argument
|
| 926 |
+
>>> input = torch.randn(1, 16, 12)
|
| 927 |
+
>>> downsample = nn.Conv1d(16, 16, 3, stride=2, padding=1)
|
| 928 |
+
>>> upsample = nn.ConvTranspose1d(16, 16, 3, stride=2, padding=1)
|
| 929 |
+
>>> h = downsample(input)
|
| 930 |
+
>>> h.size()
|
| 931 |
+
torch.Size([1, 16, 6])
|
| 932 |
+
>>> output = upsample(h, output_size=input.size())
|
| 933 |
+
>>> output.size()
|
| 934 |
+
torch.Size([1, 16, 12])
|
| 935 |
+
|
| 936 |
+
.. _`here`:
|
| 937 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 938 |
+
|
| 939 |
+
.. _`Deconvolutional Networks`:
|
| 940 |
+
https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
|
| 941 |
+
"""
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
def __init__(
|
| 945 |
+
self,
|
| 946 |
+
in_channels: int,
|
| 947 |
+
out_channels: int,
|
| 948 |
+
kernel_size: _size_1_t,
|
| 949 |
+
stride: _size_1_t = 1,
|
| 950 |
+
padding: _size_1_t = 0,
|
| 951 |
+
output_padding: _size_1_t = 0,
|
| 952 |
+
groups: int = 1,
|
| 953 |
+
bias: bool = True,
|
| 954 |
+
dilation: _size_1_t = 1,
|
| 955 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 956 |
+
device=None,
|
| 957 |
+
dtype=None,
|
| 958 |
+
) -> None:
|
| 959 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 960 |
+
kernel_size = _single(kernel_size)
|
| 961 |
+
stride = _single(stride)
|
| 962 |
+
padding = _single(padding)
|
| 963 |
+
dilation = _single(dilation)
|
| 964 |
+
output_padding = _single(output_padding)
|
| 965 |
+
super().__init__(
|
| 966 |
+
in_channels,
|
| 967 |
+
out_channels,
|
| 968 |
+
kernel_size,
|
| 969 |
+
stride,
|
| 970 |
+
padding,
|
| 971 |
+
dilation,
|
| 972 |
+
True,
|
| 973 |
+
output_padding,
|
| 974 |
+
groups,
|
| 975 |
+
bias,
|
| 976 |
+
padding_mode,
|
| 977 |
+
**factory_kwargs,
|
| 978 |
+
)
|
| 979 |
+
|
| 980 |
+
def forward(self, input: Tensor, output_size: list[int] | None = None) -> Tensor:
|
| 981 |
+
if self.padding_mode != "zeros":
|
| 982 |
+
raise ValueError(
|
| 983 |
+
"Only `zeros` padding mode is supported for ConvTranspose1d"
|
| 984 |
+
)
|
| 985 |
+
|
| 986 |
+
if not isinstance(self.padding, tuple):
|
| 987 |
+
raise AssertionError("self.padding must be a tuple")
|
| 988 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 989 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 990 |
+
num_spatial_dims = 1
|
| 991 |
+
output_padding = self._output_padding(
|
| 992 |
+
input,
|
| 993 |
+
output_size,
|
| 994 |
+
self.stride, # type: ignore[arg-type]
|
| 995 |
+
self.padding, # type: ignore[arg-type]
|
| 996 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 997 |
+
num_spatial_dims,
|
| 998 |
+
self.dilation, # type: ignore[arg-type]
|
| 999 |
+
)
|
| 1000 |
+
return F.conv_transpose1d(
|
| 1001 |
+
input,
|
| 1002 |
+
self.weight,
|
| 1003 |
+
self.bias,
|
| 1004 |
+
self.stride,
|
| 1005 |
+
self.padding,
|
| 1006 |
+
output_padding,
|
| 1007 |
+
self.groups,
|
| 1008 |
+
self.dilation,
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
|
| 1012 |
+
class ConvTranspose2d(_ConvTransposeNd):
|
| 1013 |
+
__doc__ = (
|
| 1014 |
+
r"""Applies a 2D transposed convolution operator over an input image
|
| 1015 |
+
composed of several input planes.
|
| 1016 |
+
|
| 1017 |
+
This module can be seen as the gradient of Conv2d with respect to its input.
|
| 1018 |
+
It is also known as a fractionally-strided convolution or
|
| 1019 |
+
a deconvolution (although it is not an actual deconvolution operation as it does
|
| 1020 |
+
not compute a true inverse of convolution). For more information, see the visualizations
|
| 1021 |
+
`here`_ and the `Deconvolutional Networks`_ paper.
|
| 1022 |
+
|
| 1023 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 1024 |
+
|
| 1025 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 1026 |
+
|
| 1027 |
+
* :attr:`stride` controls the stride for the cross-correlation. When stride > 1, ConvTranspose2d inserts zeros between input
|
| 1028 |
+
elements along the spatial dimensions before applying the convolution kernel. This zero-insertion operation is the standard
|
| 1029 |
+
behavior of transposed convolutions, which can increase the spatial resolution and is equivalent to a learnable
|
| 1030 |
+
upsampling operation.
|
| 1031 |
+
|
| 1032 |
+
* :attr:`padding` controls the amount of implicit zero padding on both
|
| 1033 |
+
sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
|
| 1034 |
+
below for details.
|
| 1035 |
+
|
| 1036 |
+
* :attr:`output_padding` controls the additional size added to one side
|
| 1037 |
+
of the output shape. See note below for details.
|
| 1038 |
+
"""
|
| 1039 |
+
"""
|
| 1040 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 1041 |
+
It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
|
| 1042 |
+
"""
|
| 1043 |
+
r"""
|
| 1044 |
+
{groups_note}
|
| 1045 |
+
|
| 1046 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding`
|
| 1047 |
+
can either be:
|
| 1048 |
+
|
| 1049 |
+
- a single ``int`` -- in which case the same value is used for the height and width dimensions
|
| 1050 |
+
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
|
| 1051 |
+
and the second `int` for the width dimension
|
| 1052 |
+
|
| 1053 |
+
Note:
|
| 1054 |
+
The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
|
| 1055 |
+
amount of zero padding to both sides of the input. This is set so that
|
| 1056 |
+
when a :class:`~torch.nn.Conv2d` and a :class:`~torch.nn.ConvTranspose2d`
|
| 1057 |
+
are initialized with same parameters, they are inverses of each other in
|
| 1058 |
+
regard to the input and output shapes. However, when ``stride > 1``,
|
| 1059 |
+
:class:`~torch.nn.Conv2d` maps multiple input shapes to the same output
|
| 1060 |
+
shape. :attr:`output_padding` is provided to resolve this ambiguity by
|
| 1061 |
+
effectively increasing the calculated output shape on one side. Note
|
| 1062 |
+
that :attr:`output_padding` is only used to find output shape, but does
|
| 1063 |
+
not actually add zero-padding to output.
|
| 1064 |
+
|
| 1065 |
+
Note:
|
| 1066 |
+
{cudnn_reproducibility_note}
|
| 1067 |
+
|
| 1068 |
+
Args:
|
| 1069 |
+
in_channels (int): Number of channels in the input image
|
| 1070 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1071 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1072 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1073 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 1074 |
+
will be added to both sides of each dimension in the input. Default: 0
|
| 1075 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 1076 |
+
of each dimension in the output shape. Default: 0
|
| 1077 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 1078 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 1079 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 1080 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 1081 |
+
+ r"""
|
| 1082 |
+
|
| 1083 |
+
Shape:
|
| 1084 |
+
- Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})`
|
| 1085 |
+
- Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where
|
| 1086 |
+
|
| 1087 |
+
.. math::
|
| 1088 |
+
H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0]
|
| 1089 |
+
\times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1
|
| 1090 |
+
.. math::
|
| 1091 |
+
W_{out} = (W_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1]
|
| 1092 |
+
\times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1
|
| 1093 |
+
|
| 1094 |
+
Attributes:
|
| 1095 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 1096 |
+
:math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
|
| 1097 |
+
:math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`.
|
| 1098 |
+
The values of these weights are sampled from
|
| 1099 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 1100 |
+
:math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
|
| 1101 |
+
bias (Tensor): the learnable bias of the module of shape (out_channels)
|
| 1102 |
+
If :attr:`bias` is ``True``, then the values of these weights are
|
| 1103 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 1104 |
+
:math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
|
| 1105 |
+
|
| 1106 |
+
Examples::
|
| 1107 |
+
|
| 1108 |
+
>>> # With square kernels and equal stride
|
| 1109 |
+
>>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)
|
| 1110 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 1111 |
+
>>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
|
| 1112 |
+
>>> input = torch.randn(20, 16, 50, 100)
|
| 1113 |
+
>>> output = m(input)
|
| 1114 |
+
>>> # exact output size can be also specified as an argument
|
| 1115 |
+
>>> input = torch.randn(1, 16, 12, 12)
|
| 1116 |
+
>>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1)
|
| 1117 |
+
>>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
|
| 1118 |
+
>>> h = downsample(input)
|
| 1119 |
+
>>> h.size()
|
| 1120 |
+
torch.Size([1, 16, 6, 6])
|
| 1121 |
+
>>> output = upsample(h, output_size=input.size())
|
| 1122 |
+
>>> output.size()
|
| 1123 |
+
torch.Size([1, 16, 12, 12])
|
| 1124 |
+
|
| 1125 |
+
.. _`here`:
|
| 1126 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 1127 |
+
|
| 1128 |
+
.. _`Deconvolutional Networks`:
|
| 1129 |
+
https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
|
| 1130 |
+
"""
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
def __init__(
|
| 1134 |
+
self,
|
| 1135 |
+
in_channels: int,
|
| 1136 |
+
out_channels: int,
|
| 1137 |
+
kernel_size: _size_2_t,
|
| 1138 |
+
stride: _size_2_t = 1,
|
| 1139 |
+
padding: _size_2_t = 0,
|
| 1140 |
+
output_padding: _size_2_t = 0,
|
| 1141 |
+
groups: int = 1,
|
| 1142 |
+
bias: bool = True,
|
| 1143 |
+
dilation: _size_2_t = 1,
|
| 1144 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1145 |
+
device=None,
|
| 1146 |
+
dtype=None,
|
| 1147 |
+
) -> None:
|
| 1148 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1149 |
+
kernel_size = _pair(kernel_size)
|
| 1150 |
+
stride = _pair(stride)
|
| 1151 |
+
padding = _pair(padding)
|
| 1152 |
+
dilation = _pair(dilation)
|
| 1153 |
+
output_padding = _pair(output_padding)
|
| 1154 |
+
super().__init__(
|
| 1155 |
+
in_channels,
|
| 1156 |
+
out_channels,
|
| 1157 |
+
kernel_size,
|
| 1158 |
+
stride,
|
| 1159 |
+
padding,
|
| 1160 |
+
dilation,
|
| 1161 |
+
True,
|
| 1162 |
+
output_padding,
|
| 1163 |
+
groups,
|
| 1164 |
+
bias,
|
| 1165 |
+
padding_mode,
|
| 1166 |
+
**factory_kwargs,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
def forward(self, input: Tensor, output_size: list[int] | None = None) -> Tensor:
|
| 1170 |
+
"""
|
| 1171 |
+
Performs the forward pass.
|
| 1172 |
+
|
| 1173 |
+
Attributes:
|
| 1174 |
+
input (Tensor): The input tensor.
|
| 1175 |
+
output_size (list[int], optional): A list of integers representing
|
| 1176 |
+
the size of the output tensor. Default is None.
|
| 1177 |
+
"""
|
| 1178 |
+
if self.padding_mode != "zeros":
|
| 1179 |
+
raise ValueError(
|
| 1180 |
+
"Only `zeros` padding mode is supported for ConvTranspose2d"
|
| 1181 |
+
)
|
| 1182 |
+
|
| 1183 |
+
if not isinstance(self.padding, tuple):
|
| 1184 |
+
raise AssertionError("self.padding must be a tuple")
|
| 1185 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 1186 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 1187 |
+
num_spatial_dims = 2
|
| 1188 |
+
output_padding = self._output_padding(
|
| 1189 |
+
input,
|
| 1190 |
+
output_size,
|
| 1191 |
+
self.stride, # type: ignore[arg-type]
|
| 1192 |
+
self.padding, # type: ignore[arg-type]
|
| 1193 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 1194 |
+
num_spatial_dims,
|
| 1195 |
+
self.dilation, # type: ignore[arg-type]
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
return F.conv_transpose2d(
|
| 1199 |
+
input,
|
| 1200 |
+
self.weight,
|
| 1201 |
+
self.bias,
|
| 1202 |
+
self.stride,
|
| 1203 |
+
self.padding,
|
| 1204 |
+
output_padding,
|
| 1205 |
+
self.groups,
|
| 1206 |
+
self.dilation,
|
| 1207 |
+
)
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
class ConvTranspose3d(_ConvTransposeNd):
|
| 1211 |
+
__doc__ = (
|
| 1212 |
+
r"""Applies a 3D transposed convolution operator over an input image composed of several input
|
| 1213 |
+
planes.
|
| 1214 |
+
The transposed convolution operator multiplies each input value element-wise by a learnable kernel,
|
| 1215 |
+
and sums over the outputs from all input feature planes.
|
| 1216 |
+
|
| 1217 |
+
This module can be seen as the gradient of Conv3d with respect to its input.
|
| 1218 |
+
It is also known as a fractionally-strided convolution or
|
| 1219 |
+
a deconvolution (although it is not an actual deconvolution operation as it does
|
| 1220 |
+
not compute a true inverse of convolution). For more information, see the visualizations
|
| 1221 |
+
`here`_ and the `Deconvolutional Networks`_ paper.
|
| 1222 |
+
|
| 1223 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 1224 |
+
|
| 1225 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 1226 |
+
|
| 1227 |
+
* :attr:`stride` controls the stride for the cross-correlation.
|
| 1228 |
+
|
| 1229 |
+
* :attr:`padding` controls the amount of implicit zero padding on both
|
| 1230 |
+
sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
|
| 1231 |
+
below for details.
|
| 1232 |
+
|
| 1233 |
+
* :attr:`output_padding` controls the additional size added to one side
|
| 1234 |
+
of the output shape. See note below for details.
|
| 1235 |
+
"""
|
| 1236 |
+
"""
|
| 1237 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 1238 |
+
It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
|
| 1239 |
+
"""
|
| 1240 |
+
r"""
|
| 1241 |
+
{groups_note}
|
| 1242 |
+
|
| 1243 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding`
|
| 1244 |
+
can either be:
|
| 1245 |
+
|
| 1246 |
+
- a single ``int`` -- in which case the same value is used for the depth, height and width dimensions
|
| 1247 |
+
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
|
| 1248 |
+
the second `int` for the height dimension and the third `int` for the width dimension
|
| 1249 |
+
|
| 1250 |
+
Note:
|
| 1251 |
+
The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
|
| 1252 |
+
amount of zero padding to both sides of the input. This is set so that
|
| 1253 |
+
when a :class:`~torch.nn.Conv3d` and a :class:`~torch.nn.ConvTranspose3d`
|
| 1254 |
+
are initialized with same parameters, they are inverses of each other in
|
| 1255 |
+
regard to the input and output shapes. However, when ``stride > 1``,
|
| 1256 |
+
:class:`~torch.nn.Conv3d` maps multiple input shapes to the same output
|
| 1257 |
+
shape. :attr:`output_padding` is provided to resolve this ambiguity by
|
| 1258 |
+
effectively increasing the calculated output shape on one side. Note
|
| 1259 |
+
that :attr:`output_padding` is only used to find output shape, but does
|
| 1260 |
+
not actually add zero-padding to output.
|
| 1261 |
+
|
| 1262 |
+
Note:
|
| 1263 |
+
{cudnn_reproducibility_note}
|
| 1264 |
+
|
| 1265 |
+
Args:
|
| 1266 |
+
in_channels (int): Number of channels in the input image
|
| 1267 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1268 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1269 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1270 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 1271 |
+
will be added to both sides of each dimension in the input. Default: 0
|
| 1272 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 1273 |
+
of each dimension in the output shape. Default: 0
|
| 1274 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 1275 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 1276 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 1277 |
+
""".format(**reproducibility_notes, **convolution_notes)
|
| 1278 |
+
+ r"""
|
| 1279 |
+
|
| 1280 |
+
Shape:
|
| 1281 |
+
- Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})`
|
| 1282 |
+
- Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or
|
| 1283 |
+
:math:`(C_{out}, D_{out}, H_{out}, W_{out})`, where
|
| 1284 |
+
|
| 1285 |
+
.. math::
|
| 1286 |
+
D_{out} = (D_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0]
|
| 1287 |
+
\times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1
|
| 1288 |
+
.. math::
|
| 1289 |
+
H_{out} = (H_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1]
|
| 1290 |
+
\times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1
|
| 1291 |
+
.. math::
|
| 1292 |
+
W_{out} = (W_{in} - 1) \times \text{stride}[2] - 2 \times \text{padding}[2] + \text{dilation}[2]
|
| 1293 |
+
\times (\text{kernel\_size}[2] - 1) + \text{output\_padding}[2] + 1
|
| 1294 |
+
|
| 1295 |
+
|
| 1296 |
+
Attributes:
|
| 1297 |
+
weight (Tensor): the learnable weights of the module of shape
|
| 1298 |
+
:math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
|
| 1299 |
+
:math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`.
|
| 1300 |
+
The values of these weights are sampled from
|
| 1301 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 1302 |
+
:math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
|
| 1303 |
+
bias (Tensor): the learnable bias of the module of shape (out_channels)
|
| 1304 |
+
If :attr:`bias` is ``True``, then the values of these weights are
|
| 1305 |
+
sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 1306 |
+
:math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
|
| 1307 |
+
|
| 1308 |
+
Examples::
|
| 1309 |
+
|
| 1310 |
+
>>> # With square kernels and equal stride
|
| 1311 |
+
>>> m = nn.ConvTranspose3d(16, 33, 3, stride=2)
|
| 1312 |
+
>>> # non-square kernels and unequal stride and with padding
|
| 1313 |
+
>>> m = nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
|
| 1314 |
+
>>> input = torch.randn(20, 16, 10, 50, 100)
|
| 1315 |
+
>>> output = m(input)
|
| 1316 |
+
|
| 1317 |
+
.. _`here`:
|
| 1318 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 1319 |
+
|
| 1320 |
+
.. _`Deconvolutional Networks`:
|
| 1321 |
+
https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
|
| 1322 |
+
"""
|
| 1323 |
+
)
|
| 1324 |
+
|
| 1325 |
+
def __init__(
|
| 1326 |
+
self,
|
| 1327 |
+
in_channels: int,
|
| 1328 |
+
out_channels: int,
|
| 1329 |
+
kernel_size: _size_3_t,
|
| 1330 |
+
stride: _size_3_t = 1,
|
| 1331 |
+
padding: _size_3_t = 0,
|
| 1332 |
+
output_padding: _size_3_t = 0,
|
| 1333 |
+
groups: int = 1,
|
| 1334 |
+
bias: bool = True,
|
| 1335 |
+
dilation: _size_3_t = 1,
|
| 1336 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1337 |
+
device=None,
|
| 1338 |
+
dtype=None,
|
| 1339 |
+
) -> None:
|
| 1340 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1341 |
+
kernel_size = _triple(kernel_size)
|
| 1342 |
+
stride = _triple(stride)
|
| 1343 |
+
padding = _triple(padding)
|
| 1344 |
+
dilation = _triple(dilation)
|
| 1345 |
+
output_padding = _triple(output_padding)
|
| 1346 |
+
super().__init__(
|
| 1347 |
+
in_channels,
|
| 1348 |
+
out_channels,
|
| 1349 |
+
kernel_size,
|
| 1350 |
+
stride,
|
| 1351 |
+
padding,
|
| 1352 |
+
dilation,
|
| 1353 |
+
True,
|
| 1354 |
+
output_padding,
|
| 1355 |
+
groups,
|
| 1356 |
+
bias,
|
| 1357 |
+
padding_mode,
|
| 1358 |
+
**factory_kwargs,
|
| 1359 |
+
)
|
| 1360 |
+
|
| 1361 |
+
def forward(self, input: Tensor, output_size: list[int] | None = None) -> Tensor:
|
| 1362 |
+
if self.padding_mode != "zeros":
|
| 1363 |
+
raise ValueError(
|
| 1364 |
+
"Only `zeros` padding mode is supported for ConvTranspose3d"
|
| 1365 |
+
)
|
| 1366 |
+
|
| 1367 |
+
if not isinstance(self.padding, tuple):
|
| 1368 |
+
raise AssertionError("self.padding must be a tuple")
|
| 1369 |
+
# One cannot replace List by Tuple or Sequence in "_output_padding" because
|
| 1370 |
+
# TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
|
| 1371 |
+
num_spatial_dims = 3
|
| 1372 |
+
output_padding = self._output_padding(
|
| 1373 |
+
input,
|
| 1374 |
+
output_size,
|
| 1375 |
+
self.stride, # type: ignore[arg-type]
|
| 1376 |
+
self.padding, # type: ignore[arg-type]
|
| 1377 |
+
self.kernel_size, # type: ignore[arg-type]
|
| 1378 |
+
num_spatial_dims,
|
| 1379 |
+
self.dilation, # type: ignore[arg-type]
|
| 1380 |
+
)
|
| 1381 |
+
|
| 1382 |
+
return F.conv_transpose3d(
|
| 1383 |
+
input,
|
| 1384 |
+
self.weight,
|
| 1385 |
+
self.bias,
|
| 1386 |
+
self.stride,
|
| 1387 |
+
self.padding,
|
| 1388 |
+
output_padding,
|
| 1389 |
+
self.groups,
|
| 1390 |
+
self.dilation,
|
| 1391 |
+
)
|
| 1392 |
+
|
| 1393 |
+
|
| 1394 |
+
# TODO: Deprecate and remove the following alias `_ConvTransposeMixin`.
|
| 1395 |
+
#
|
| 1396 |
+
# `_ConvTransposeMixin` was a mixin that was removed. It is meant to be used
|
| 1397 |
+
# with `_ConvNd` to construct actual module classes that implements conv
|
| 1398 |
+
# transpose ops:
|
| 1399 |
+
#
|
| 1400 |
+
# class MyConvTranspose(_ConvNd, _ConvTransposeMixin):
|
| 1401 |
+
# ...
|
| 1402 |
+
#
|
| 1403 |
+
# In PyTorch, it has been replaced by `_ConvTransposeNd`, which is a proper
|
| 1404 |
+
# subclass of `_ConvNd`. However, some user code in the wild still (incorrectly)
|
| 1405 |
+
# use the internal class `_ConvTransposeMixin`. Hence, we provide this alias
|
| 1406 |
+
# for BC, because it is cheap and easy for us to do so, even though that
|
| 1407 |
+
# `_ConvTransposeNd` is really not a mixin anymore (but multiple inheritance as
|
| 1408 |
+
# above would still work).
|
| 1409 |
+
class _ConvTransposeMixin(_ConvTransposeNd):
|
| 1410 |
+
@deprecated(
|
| 1411 |
+
"`_ConvTransposeMixin` is a deprecated internal class. "
|
| 1412 |
+
"Please consider using public APIs.",
|
| 1413 |
+
category=FutureWarning,
|
| 1414 |
+
)
|
| 1415 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 1416 |
+
super().__init__(*args, **kwargs)
|
| 1417 |
+
|
| 1418 |
+
|
| 1419 |
+
# TODO: Conv2dLocal
|
| 1420 |
+
# TODO: Conv2dMap
|
| 1421 |
+
# TODO: ConvTranspose2dMap
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
class _LazyConvXdMixin(LazyModuleMixin):
|
| 1425 |
+
groups: int
|
| 1426 |
+
transposed: bool
|
| 1427 |
+
in_channels: int
|
| 1428 |
+
out_channels: int
|
| 1429 |
+
kernel_size: tuple[int, ...]
|
| 1430 |
+
weight: UninitializedParameter
|
| 1431 |
+
bias: UninitializedParameter
|
| 1432 |
+
|
| 1433 |
+
def reset_parameters(self) -> None:
|
| 1434 |
+
# has_uninitialized_params is defined in parent class and it is using a protocol on self
|
| 1435 |
+
if not self.has_uninitialized_params() and self.in_channels != 0: # type: ignore[misc]
|
| 1436 |
+
# "type:ignore[..]" is required because mypy thinks that "reset_parameters" is undefined
|
| 1437 |
+
# in super class. Turns out that it is defined in _ConvND which is inherited by any class
|
| 1438 |
+
# that also inherits _LazyConvXdMixin
|
| 1439 |
+
super().reset_parameters() # type: ignore[misc]
|
| 1440 |
+
|
| 1441 |
+
# Signature of "initialize_parameters" is incompatible with the definition in supertype LazyModuleMixin
|
| 1442 |
+
def initialize_parameters(self, input: Tensor, *args, **kwargs) -> None: # type: ignore[override]
|
| 1443 |
+
# defined by parent class but using a protocol
|
| 1444 |
+
if self.has_uninitialized_params(): # type: ignore[misc]
|
| 1445 |
+
self.in_channels = self._get_in_channels(input)
|
| 1446 |
+
if self.in_channels % self.groups != 0:
|
| 1447 |
+
raise ValueError("in_channels must be divisible by groups")
|
| 1448 |
+
if not isinstance(self.weight, UninitializedParameter):
|
| 1449 |
+
raise AssertionError("self.weight must be an UninitializedParameter")
|
| 1450 |
+
if self.transposed:
|
| 1451 |
+
self.weight.materialize(
|
| 1452 |
+
(
|
| 1453 |
+
self.in_channels,
|
| 1454 |
+
self.out_channels // self.groups,
|
| 1455 |
+
*self.kernel_size,
|
| 1456 |
+
)
|
| 1457 |
+
)
|
| 1458 |
+
else:
|
| 1459 |
+
self.weight.materialize(
|
| 1460 |
+
(
|
| 1461 |
+
self.out_channels,
|
| 1462 |
+
self.in_channels // self.groups,
|
| 1463 |
+
*self.kernel_size,
|
| 1464 |
+
)
|
| 1465 |
+
)
|
| 1466 |
+
if self.bias is not None:
|
| 1467 |
+
if not isinstance(self.bias, UninitializedParameter):
|
| 1468 |
+
raise AssertionError("self.bias must be an UninitializedParameter")
|
| 1469 |
+
self.bias.materialize((self.out_channels,))
|
| 1470 |
+
self.reset_parameters()
|
| 1471 |
+
|
| 1472 |
+
# Function to extract in_channels from first input.
|
| 1473 |
+
def _get_in_channels(self, input: Tensor) -> int:
|
| 1474 |
+
num_spatial_dims = self._get_num_spatial_dims()
|
| 1475 |
+
num_dims_no_batch = num_spatial_dims + 1 # +1 for channels dim
|
| 1476 |
+
num_dims_batch = num_dims_no_batch + 1
|
| 1477 |
+
if input.dim() not in (num_dims_no_batch, num_dims_batch):
|
| 1478 |
+
raise RuntimeError(
|
| 1479 |
+
f"Expected {num_dims_no_batch}D (unbatched) or {num_dims_batch}D (batched) input "
|
| 1480 |
+
f"to {self.__class__.__name__}, but "
|
| 1481 |
+
f"got input of size: {input.shape}"
|
| 1482 |
+
)
|
| 1483 |
+
return input.shape[1] if input.dim() == num_dims_batch else input.shape[0]
|
| 1484 |
+
|
| 1485 |
+
# Function to return the number of spatial dims expected for inputs to the module.
|
| 1486 |
+
# This is expected to be implemented by subclasses.
|
| 1487 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1488 |
+
raise NotImplementedError
|
| 1489 |
+
|
| 1490 |
+
|
| 1491 |
+
# LazyConv1d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1492 |
+
class LazyConv1d(_LazyConvXdMixin, Conv1d): # type: ignore[misc]
|
| 1493 |
+
r"""A :class:`torch.nn.Conv1d` module with lazy initialization of the ``in_channels`` argument.
|
| 1494 |
+
|
| 1495 |
+
The ``in_channels`` argument of the :class:`Conv1d` is inferred from the ``input.size(1)``.
|
| 1496 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1497 |
+
|
| 1498 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1499 |
+
on lazy modules and their limitations.
|
| 1500 |
+
|
| 1501 |
+
Args:
|
| 1502 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1503 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1504 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1505 |
+
padding (int or tuple, optional): Zero-padding added to both sides of
|
| 1506 |
+
the input. Default: 0
|
| 1507 |
+
dilation (int or tuple, optional): Spacing between kernel
|
| 1508 |
+
elements. Default: 1
|
| 1509 |
+
groups (int, optional): Number of blocked connections from input
|
| 1510 |
+
channels to output channels. Default: 1
|
| 1511 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the
|
| 1512 |
+
output. Default: ``True``
|
| 1513 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``,
|
| 1514 |
+
``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 1515 |
+
|
| 1516 |
+
.. seealso:: :class:`torch.nn.Conv1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1517 |
+
"""
|
| 1518 |
+
|
| 1519 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1520 |
+
# since we are redefining the variable.
|
| 1521 |
+
cls_to_become = Conv1d # type: ignore[assignment]
|
| 1522 |
+
|
| 1523 |
+
def __init__(
|
| 1524 |
+
self,
|
| 1525 |
+
out_channels: int,
|
| 1526 |
+
kernel_size: _size_1_t,
|
| 1527 |
+
stride: _size_1_t = 1,
|
| 1528 |
+
padding: _size_1_t = 0,
|
| 1529 |
+
dilation: _size_1_t = 1,
|
| 1530 |
+
groups: int = 1,
|
| 1531 |
+
bias: bool = True,
|
| 1532 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1533 |
+
device=None,
|
| 1534 |
+
dtype=None,
|
| 1535 |
+
) -> None:
|
| 1536 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1537 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1538 |
+
super().__init__(
|
| 1539 |
+
0,
|
| 1540 |
+
0,
|
| 1541 |
+
kernel_size,
|
| 1542 |
+
stride,
|
| 1543 |
+
padding,
|
| 1544 |
+
dilation,
|
| 1545 |
+
groups,
|
| 1546 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1547 |
+
# that will soon be overwritten.
|
| 1548 |
+
False,
|
| 1549 |
+
padding_mode,
|
| 1550 |
+
**factory_kwargs,
|
| 1551 |
+
)
|
| 1552 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1553 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1554 |
+
self.out_channels = out_channels
|
| 1555 |
+
if bias:
|
| 1556 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1557 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1558 |
+
|
| 1559 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1560 |
+
return 1
|
| 1561 |
+
|
| 1562 |
+
|
| 1563 |
+
# LazyConv2d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1564 |
+
class LazyConv2d(_LazyConvXdMixin, Conv2d): # type: ignore[misc]
|
| 1565 |
+
r"""A :class:`torch.nn.Conv2d` module with lazy initialization of the ``in_channels`` argument.
|
| 1566 |
+
|
| 1567 |
+
The ``in_channels`` argument of the :class:`Conv2d` that is inferred from the ``input.size(1)``.
|
| 1568 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1569 |
+
|
| 1570 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1571 |
+
on lazy modules and their limitations.
|
| 1572 |
+
|
| 1573 |
+
Args:
|
| 1574 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1575 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1576 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1577 |
+
padding (int or tuple, optional): Zero-padding added to both sides of
|
| 1578 |
+
the input. Default: 0
|
| 1579 |
+
dilation (int or tuple, optional): Spacing between kernel
|
| 1580 |
+
elements. Default: 1
|
| 1581 |
+
groups (int, optional): Number of blocked connections from input
|
| 1582 |
+
channels to output channels. Default: 1
|
| 1583 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the
|
| 1584 |
+
output. Default: ``True``
|
| 1585 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``,
|
| 1586 |
+
``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 1587 |
+
|
| 1588 |
+
.. seealso:: :class:`torch.nn.Conv2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1589 |
+
"""
|
| 1590 |
+
|
| 1591 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1592 |
+
# since we are redefining the variable.
|
| 1593 |
+
cls_to_become = Conv2d # type: ignore[assignment]
|
| 1594 |
+
|
| 1595 |
+
def __init__(
|
| 1596 |
+
self,
|
| 1597 |
+
out_channels: int,
|
| 1598 |
+
kernel_size: _size_2_t,
|
| 1599 |
+
stride: _size_2_t = 1,
|
| 1600 |
+
padding: _size_2_t = 0,
|
| 1601 |
+
dilation: _size_2_t = 1,
|
| 1602 |
+
groups: int = 1,
|
| 1603 |
+
bias: bool = True,
|
| 1604 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1605 |
+
device=None,
|
| 1606 |
+
dtype=None,
|
| 1607 |
+
) -> None:
|
| 1608 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1609 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1610 |
+
super().__init__(
|
| 1611 |
+
0,
|
| 1612 |
+
0,
|
| 1613 |
+
kernel_size,
|
| 1614 |
+
stride,
|
| 1615 |
+
padding,
|
| 1616 |
+
dilation,
|
| 1617 |
+
groups,
|
| 1618 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1619 |
+
# that will soon be overwritten.
|
| 1620 |
+
False,
|
| 1621 |
+
padding_mode,
|
| 1622 |
+
**factory_kwargs,
|
| 1623 |
+
)
|
| 1624 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1625 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1626 |
+
self.out_channels = out_channels
|
| 1627 |
+
if bias:
|
| 1628 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1629 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1630 |
+
|
| 1631 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1632 |
+
return 2
|
| 1633 |
+
|
| 1634 |
+
|
| 1635 |
+
# LazyConv3d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1636 |
+
class LazyConv3d(_LazyConvXdMixin, Conv3d): # type: ignore[misc]
|
| 1637 |
+
r"""A :class:`torch.nn.Conv3d` module with lazy initialization of the ``in_channels`` argument.
|
| 1638 |
+
|
| 1639 |
+
The ``in_channels`` argument of the :class:`Conv3d` that is inferred from
|
| 1640 |
+
the ``input.size(1)``.
|
| 1641 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1642 |
+
|
| 1643 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1644 |
+
on lazy modules and their limitations.
|
| 1645 |
+
|
| 1646 |
+
Args:
|
| 1647 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1648 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1649 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1650 |
+
padding (int or tuple, optional): Zero-padding added to both sides of
|
| 1651 |
+
the input. Default: 0
|
| 1652 |
+
dilation (int or tuple, optional): Spacing between kernel
|
| 1653 |
+
elements. Default: 1
|
| 1654 |
+
groups (int, optional): Number of blocked connections from input
|
| 1655 |
+
channels to output channels. Default: 1
|
| 1656 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the
|
| 1657 |
+
output. Default: ``True``
|
| 1658 |
+
padding_mode (str, optional): ``'zeros'``, ``'reflect'``,
|
| 1659 |
+
``'replicate'`` or ``'circular'``. Default: ``'zeros'``
|
| 1660 |
+
|
| 1661 |
+
.. seealso:: :class:`torch.nn.Conv3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1662 |
+
"""
|
| 1663 |
+
|
| 1664 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1665 |
+
# since we are redefining the variable.
|
| 1666 |
+
cls_to_become = Conv3d # type: ignore[assignment]
|
| 1667 |
+
|
| 1668 |
+
def __init__(
|
| 1669 |
+
self,
|
| 1670 |
+
out_channels: int,
|
| 1671 |
+
kernel_size: _size_3_t,
|
| 1672 |
+
stride: _size_3_t = 1,
|
| 1673 |
+
padding: _size_3_t = 0,
|
| 1674 |
+
dilation: _size_3_t = 1,
|
| 1675 |
+
groups: int = 1,
|
| 1676 |
+
bias: bool = True,
|
| 1677 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1678 |
+
device=None,
|
| 1679 |
+
dtype=None,
|
| 1680 |
+
) -> None:
|
| 1681 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1682 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1683 |
+
super().__init__(
|
| 1684 |
+
0,
|
| 1685 |
+
0,
|
| 1686 |
+
kernel_size,
|
| 1687 |
+
stride,
|
| 1688 |
+
padding,
|
| 1689 |
+
dilation,
|
| 1690 |
+
groups,
|
| 1691 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1692 |
+
# that will soon be overwritten.
|
| 1693 |
+
False,
|
| 1694 |
+
padding_mode,
|
| 1695 |
+
**factory_kwargs,
|
| 1696 |
+
)
|
| 1697 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1698 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1699 |
+
self.out_channels = out_channels
|
| 1700 |
+
if bias:
|
| 1701 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1702 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1703 |
+
|
| 1704 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1705 |
+
return 3
|
| 1706 |
+
|
| 1707 |
+
|
| 1708 |
+
# LazyConvTranspose1d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1709 |
+
class LazyConvTranspose1d(_LazyConvXdMixin, ConvTranspose1d): # type: ignore[misc]
|
| 1710 |
+
r"""A :class:`torch.nn.ConvTranspose1d` module with lazy initialization of the ``in_channels`` argument.
|
| 1711 |
+
|
| 1712 |
+
The ``in_channels`` argument of the :class:`ConvTranspose1d` that is inferred from
|
| 1713 |
+
the ``input.size(1)``.
|
| 1714 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1715 |
+
|
| 1716 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1717 |
+
on lazy modules and their limitations.
|
| 1718 |
+
|
| 1719 |
+
Args:
|
| 1720 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1721 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1722 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1723 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 1724 |
+
will be added to both sides of the input. Default: 0
|
| 1725 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 1726 |
+
of the output shape. Default: 0
|
| 1727 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 1728 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 1729 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 1730 |
+
|
| 1731 |
+
.. seealso:: :class:`torch.nn.ConvTranspose1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1732 |
+
"""
|
| 1733 |
+
|
| 1734 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1735 |
+
# since we are redefining the variable.
|
| 1736 |
+
cls_to_become = ConvTranspose1d # type: ignore[assignment]
|
| 1737 |
+
|
| 1738 |
+
def __init__(
|
| 1739 |
+
self,
|
| 1740 |
+
out_channels: int,
|
| 1741 |
+
kernel_size: _size_1_t,
|
| 1742 |
+
stride: _size_1_t = 1,
|
| 1743 |
+
padding: _size_1_t = 0,
|
| 1744 |
+
output_padding: _size_1_t = 0,
|
| 1745 |
+
groups: int = 1,
|
| 1746 |
+
bias: bool = True,
|
| 1747 |
+
dilation: _size_1_t = 1,
|
| 1748 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1749 |
+
device=None,
|
| 1750 |
+
dtype=None,
|
| 1751 |
+
) -> None:
|
| 1752 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1753 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1754 |
+
super().__init__(
|
| 1755 |
+
0,
|
| 1756 |
+
0,
|
| 1757 |
+
kernel_size,
|
| 1758 |
+
stride,
|
| 1759 |
+
padding,
|
| 1760 |
+
output_padding,
|
| 1761 |
+
groups,
|
| 1762 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1763 |
+
# that will soon be overwritten.
|
| 1764 |
+
False,
|
| 1765 |
+
dilation,
|
| 1766 |
+
padding_mode,
|
| 1767 |
+
**factory_kwargs,
|
| 1768 |
+
)
|
| 1769 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1770 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1771 |
+
self.out_channels = out_channels
|
| 1772 |
+
if bias:
|
| 1773 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1774 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1775 |
+
|
| 1776 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1777 |
+
return 1
|
| 1778 |
+
|
| 1779 |
+
|
| 1780 |
+
# LazyConvTranspose2d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1781 |
+
class LazyConvTranspose2d(_LazyConvXdMixin, ConvTranspose2d): # type: ignore[misc]
|
| 1782 |
+
r"""A :class:`torch.nn.ConvTranspose2d` module with lazy initialization of the ``in_channels`` argument.
|
| 1783 |
+
|
| 1784 |
+
The ``in_channels`` argument of the :class:`ConvTranspose2d` is inferred from
|
| 1785 |
+
the ``input.size(1)``.
|
| 1786 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1787 |
+
|
| 1788 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1789 |
+
on lazy modules and their limitations.
|
| 1790 |
+
|
| 1791 |
+
Args:
|
| 1792 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1793 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1794 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1795 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 1796 |
+
will be added to both sides of each dimension in the input. Default: 0
|
| 1797 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 1798 |
+
of each dimension in the output shape. Default: 0
|
| 1799 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 1800 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 1801 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 1802 |
+
|
| 1803 |
+
.. seealso:: :class:`torch.nn.ConvTranspose2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1804 |
+
"""
|
| 1805 |
+
|
| 1806 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1807 |
+
# since we are redefining the variable.
|
| 1808 |
+
cls_to_become = ConvTranspose2d # type: ignore[assignment]
|
| 1809 |
+
|
| 1810 |
+
def __init__(
|
| 1811 |
+
self,
|
| 1812 |
+
out_channels: int,
|
| 1813 |
+
kernel_size: _size_2_t,
|
| 1814 |
+
stride: _size_2_t = 1,
|
| 1815 |
+
padding: _size_2_t = 0,
|
| 1816 |
+
output_padding: _size_2_t = 0,
|
| 1817 |
+
groups: int = 1,
|
| 1818 |
+
bias: bool = True,
|
| 1819 |
+
dilation: int = 1,
|
| 1820 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1821 |
+
device=None,
|
| 1822 |
+
dtype=None,
|
| 1823 |
+
) -> None:
|
| 1824 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1825 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1826 |
+
super().__init__(
|
| 1827 |
+
0,
|
| 1828 |
+
0,
|
| 1829 |
+
kernel_size,
|
| 1830 |
+
stride,
|
| 1831 |
+
padding,
|
| 1832 |
+
output_padding,
|
| 1833 |
+
groups,
|
| 1834 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1835 |
+
# that will soon be overwritten.
|
| 1836 |
+
False,
|
| 1837 |
+
dilation,
|
| 1838 |
+
padding_mode,
|
| 1839 |
+
**factory_kwargs,
|
| 1840 |
+
)
|
| 1841 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1842 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1843 |
+
self.out_channels = out_channels
|
| 1844 |
+
if bias:
|
| 1845 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1846 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1847 |
+
|
| 1848 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1849 |
+
return 2
|
| 1850 |
+
|
| 1851 |
+
|
| 1852 |
+
# LazyConvTranspose3d defines weight as a Tensor but derived class defines it as UninitializedParameter
|
| 1853 |
+
class LazyConvTranspose3d(_LazyConvXdMixin, ConvTranspose3d): # type: ignore[misc]
|
| 1854 |
+
r"""A :class:`torch.nn.ConvTranspose3d` module with lazy initialization of the ``in_channels`` argument.
|
| 1855 |
+
|
| 1856 |
+
The ``in_channels`` argument of the :class:`ConvTranspose3d` is inferred from
|
| 1857 |
+
the ``input.size(1)``.
|
| 1858 |
+
The attributes that will be lazily initialized are `weight` and `bias`.
|
| 1859 |
+
|
| 1860 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 1861 |
+
on lazy modules and their limitations.
|
| 1862 |
+
|
| 1863 |
+
Args:
|
| 1864 |
+
out_channels (int): Number of channels produced by the convolution
|
| 1865 |
+
kernel_size (int or tuple): Size of the convolving kernel
|
| 1866 |
+
stride (int or tuple, optional): Stride of the convolution. Default: 1
|
| 1867 |
+
padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
|
| 1868 |
+
will be added to both sides of each dimension in the input. Default: 0
|
| 1869 |
+
output_padding (int or tuple, optional): Additional size added to one side
|
| 1870 |
+
of each dimension in the output shape. Default: 0
|
| 1871 |
+
groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
|
| 1872 |
+
bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
|
| 1873 |
+
dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
|
| 1874 |
+
|
| 1875 |
+
.. seealso:: :class:`torch.nn.ConvTranspose3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
|
| 1876 |
+
"""
|
| 1877 |
+
|
| 1878 |
+
# super class defines this variable as None. "type: ignore[..] is required
|
| 1879 |
+
# since we are redefining the variable.
|
| 1880 |
+
cls_to_become = ConvTranspose3d # type: ignore[assignment]
|
| 1881 |
+
|
| 1882 |
+
def __init__(
|
| 1883 |
+
self,
|
| 1884 |
+
out_channels: int,
|
| 1885 |
+
kernel_size: _size_3_t,
|
| 1886 |
+
stride: _size_3_t = 1,
|
| 1887 |
+
padding: _size_3_t = 0,
|
| 1888 |
+
output_padding: _size_3_t = 0,
|
| 1889 |
+
groups: int = 1,
|
| 1890 |
+
bias: bool = True,
|
| 1891 |
+
dilation: _size_3_t = 1,
|
| 1892 |
+
padding_mode: Literal["zeros", "reflect", "replicate", "circular"] = "zeros",
|
| 1893 |
+
device=None,
|
| 1894 |
+
dtype=None,
|
| 1895 |
+
) -> None:
|
| 1896 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 1897 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1898 |
+
super().__init__(
|
| 1899 |
+
0,
|
| 1900 |
+
0,
|
| 1901 |
+
kernel_size,
|
| 1902 |
+
stride,
|
| 1903 |
+
padding,
|
| 1904 |
+
output_padding,
|
| 1905 |
+
groups,
|
| 1906 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 1907 |
+
# that will soon be overwritten.
|
| 1908 |
+
False,
|
| 1909 |
+
dilation,
|
| 1910 |
+
padding_mode,
|
| 1911 |
+
**factory_kwargs,
|
| 1912 |
+
)
|
| 1913 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1914 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 1915 |
+
self.out_channels = out_channels
|
| 1916 |
+
if bias:
|
| 1917 |
+
# pyrefly: ignore [bad-override, unexpected-keyword]
|
| 1918 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 1919 |
+
|
| 1920 |
+
def _get_num_spatial_dims(self) -> int:
|
| 1921 |
+
return 3
|
.venv/lib/python3.12/site-packages/torch/nn/modules/distance.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
|
| 4 |
+
from .module import Module
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["PairwiseDistance", "CosineSimilarity"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PairwiseDistance(Module):
|
| 11 |
+
r"""
|
| 12 |
+
Computes the pairwise distance between input vectors, or between columns of input matrices.
|
| 13 |
+
|
| 14 |
+
Distances are computed using ``p``-norm, with constant ``eps`` added to avoid division by zero
|
| 15 |
+
if ``p`` is negative, i.e.:
|
| 16 |
+
|
| 17 |
+
.. math ::
|
| 18 |
+
\mathrm{dist}\left(x, y\right) = \left\Vert x-y + \epsilon e \right\Vert_p,
|
| 19 |
+
|
| 20 |
+
where :math:`e` is the vector of ones and the ``p``-norm is given by.
|
| 21 |
+
|
| 22 |
+
.. math ::
|
| 23 |
+
\Vert x \Vert _p = \left( \sum_{i=1}^n \vert x_i \vert ^ p \right) ^ {1/p}.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
p (real, optional): the norm degree. Can be negative. Default: 2
|
| 27 |
+
eps (float, optional): Small value to avoid division by zero.
|
| 28 |
+
Default: 1e-6
|
| 29 |
+
keepdim (bool, optional): Determines whether or not to keep the vector dimension.
|
| 30 |
+
Default: False
|
| 31 |
+
Shape:
|
| 32 |
+
- Input1: :math:`(N, D)` or :math:`(D)` where `N = batch dimension` and `D = vector dimension`
|
| 33 |
+
- Input2: :math:`(N, D)` or :math:`(D)`, same shape as the Input1
|
| 34 |
+
- Output: :math:`(N)` or :math:`()` based on input dimension.
|
| 35 |
+
If :attr:`keepdim` is ``True``, then :math:`(N, 1)` or :math:`(1)` based on input dimension.
|
| 36 |
+
|
| 37 |
+
Examples:
|
| 38 |
+
>>> pdist = nn.PairwiseDistance(p=2)
|
| 39 |
+
>>> input1 = torch.randn(100, 128)
|
| 40 |
+
>>> input2 = torch.randn(100, 128)
|
| 41 |
+
>>> output = pdist(input1, input2)
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
__constants__ = ["norm", "eps", "keepdim"]
|
| 45 |
+
norm: float
|
| 46 |
+
eps: float
|
| 47 |
+
keepdim: bool
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self, p: float = 2.0, eps: float = 1e-6, keepdim: bool = False
|
| 51 |
+
) -> None:
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.norm = p
|
| 54 |
+
self.eps = eps
|
| 55 |
+
self.keepdim = keepdim
|
| 56 |
+
|
| 57 |
+
def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
|
| 58 |
+
"""
|
| 59 |
+
Runs the forward pass.
|
| 60 |
+
"""
|
| 61 |
+
return F.pairwise_distance(x1, x2, self.norm, self.eps, self.keepdim)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CosineSimilarity(Module):
|
| 65 |
+
r"""Returns cosine similarity between :math:`x_1` and :math:`x_2`, computed along `dim`.
|
| 66 |
+
|
| 67 |
+
.. math ::
|
| 68 |
+
\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
dim (int, optional): Dimension where cosine similarity is computed. Default: 1
|
| 72 |
+
eps (float, optional): Small value to avoid division by zero.
|
| 73 |
+
Default: 1e-8
|
| 74 |
+
Shape:
|
| 75 |
+
- Input1: :math:`(\ast_1, D, \ast_2)` where D is at position `dim`
|
| 76 |
+
- Input2: :math:`(\ast_1, D, \ast_2)`, same number of dimensions as x1, matching x1 size at dimension `dim`,
|
| 77 |
+
and broadcastable with x1 at other dimensions.
|
| 78 |
+
- Output: :math:`(\ast_1, \ast_2)`
|
| 79 |
+
|
| 80 |
+
Examples:
|
| 81 |
+
>>> input1 = torch.randn(100, 128)
|
| 82 |
+
>>> input2 = torch.randn(100, 128)
|
| 83 |
+
>>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
|
| 84 |
+
>>> output = cos(input1, input2)
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
__constants__ = ["dim", "eps"]
|
| 88 |
+
dim: int
|
| 89 |
+
eps: float
|
| 90 |
+
|
| 91 |
+
def __init__(self, dim: int = 1, eps: float = 1e-8) -> None:
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.dim = dim
|
| 94 |
+
self.eps = eps
|
| 95 |
+
|
| 96 |
+
def forward(self, x1: Tensor, x2: Tensor) -> Tensor:
|
| 97 |
+
"""
|
| 98 |
+
Runs the forward pass.
|
| 99 |
+
"""
|
| 100 |
+
return F.cosine_similarity(x1, x2, self.dim, self.eps)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/dropout.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
|
| 4 |
+
from .module import Module
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"Dropout",
|
| 9 |
+
"Dropout1d",
|
| 10 |
+
"Dropout2d",
|
| 11 |
+
"Dropout3d",
|
| 12 |
+
"AlphaDropout",
|
| 13 |
+
"FeatureAlphaDropout",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _DropoutNd(Module):
|
| 18 |
+
__constants__ = ["p", "inplace"]
|
| 19 |
+
p: float
|
| 20 |
+
inplace: bool
|
| 21 |
+
|
| 22 |
+
def __init__(self, p: float = 0.5, inplace: bool = False) -> None:
|
| 23 |
+
super().__init__()
|
| 24 |
+
if p < 0 or p > 1:
|
| 25 |
+
raise ValueError(
|
| 26 |
+
f"dropout probability has to be between 0 and 1, but got {p}"
|
| 27 |
+
)
|
| 28 |
+
self.p = p
|
| 29 |
+
self.inplace = inplace
|
| 30 |
+
|
| 31 |
+
def extra_repr(self) -> str:
|
| 32 |
+
return f"p={self.p}, inplace={self.inplace}"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Dropout(_DropoutNd):
|
| 36 |
+
r"""During training, randomly zeroes some of the elements of the input tensor with probability :attr:`p`.
|
| 37 |
+
|
| 38 |
+
The zeroed elements are chosen independently for each forward call and are sampled from a Bernoulli distribution.
|
| 39 |
+
|
| 40 |
+
Each channel will be zeroed out independently on every forward call.
|
| 41 |
+
|
| 42 |
+
This has proven to be an effective technique for regularization and
|
| 43 |
+
preventing the co-adaptation of neurons as described in the paper
|
| 44 |
+
`Improving neural networks by preventing co-adaptation of feature
|
| 45 |
+
detectors`_ .
|
| 46 |
+
|
| 47 |
+
Furthermore, the outputs are scaled by a factor of :math:`\frac{1}{1-p}` during
|
| 48 |
+
training. This means that during evaluation the module simply computes an
|
| 49 |
+
identity function.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
p: probability of an element to be zeroed. Default: 0.5
|
| 53 |
+
inplace: If set to ``True``, will do this operation in-place. Default: ``False``
|
| 54 |
+
|
| 55 |
+
Shape:
|
| 56 |
+
- Input: :math:`(*)`. Input can be of any shape
|
| 57 |
+
- Output: :math:`(*)`. Output is of the same shape as input
|
| 58 |
+
|
| 59 |
+
Examples::
|
| 60 |
+
|
| 61 |
+
>>> m = nn.Dropout(p=0.2)
|
| 62 |
+
>>> input = torch.randn(20, 16)
|
| 63 |
+
>>> output = m(input)
|
| 64 |
+
|
| 65 |
+
.. _Improving neural networks by preventing co-adaptation of feature
|
| 66 |
+
detectors: https://arxiv.org/abs/1207.0580
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 70 |
+
"""
|
| 71 |
+
Runs the forward pass.
|
| 72 |
+
"""
|
| 73 |
+
return F.dropout(input, self.p, self.training, self.inplace)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class Dropout1d(_DropoutNd):
|
| 77 |
+
r"""Randomly zero out entire channels.
|
| 78 |
+
|
| 79 |
+
A channel is a 1D feature map,
|
| 80 |
+
e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
|
| 81 |
+
batched input is a 1D tensor :math:`\text{input}[i, j]`.
|
| 82 |
+
|
| 83 |
+
Each channel will be zeroed out independently on every forward call with
|
| 84 |
+
probability :attr:`p` using samples from a Bernoulli distribution.
|
| 85 |
+
|
| 86 |
+
Usually the input comes from :class:`nn.Conv1d` modules.
|
| 87 |
+
|
| 88 |
+
As described in the paper
|
| 89 |
+
`Efficient Object Localization Using Convolutional Networks`_ ,
|
| 90 |
+
if adjacent pixels within feature maps are strongly correlated
|
| 91 |
+
(as is normally the case in early convolution layers) then i.i.d. dropout
|
| 92 |
+
will not regularize the activations and will otherwise just result
|
| 93 |
+
in an effective learning rate decrease.
|
| 94 |
+
|
| 95 |
+
In this case, :func:`nn.Dropout1d` will help promote independence between
|
| 96 |
+
feature maps and should be used instead.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
p (float, optional): probability of an element to be zero-ed.
|
| 100 |
+
inplace (bool, optional): If set to ``True``, will do this operation
|
| 101 |
+
in-place
|
| 102 |
+
|
| 103 |
+
Shape:
|
| 104 |
+
- Input: :math:`(N, C, L)` or :math:`(C, L)`.
|
| 105 |
+
- Output: :math:`(N, C, L)` or :math:`(C, L)` (same shape as input).
|
| 106 |
+
|
| 107 |
+
Examples::
|
| 108 |
+
|
| 109 |
+
>>> m = nn.Dropout1d(p=0.2)
|
| 110 |
+
>>> input = torch.randn(20, 16, 32)
|
| 111 |
+
>>> output = m(input)
|
| 112 |
+
|
| 113 |
+
.. _Efficient Object Localization Using Convolutional Networks:
|
| 114 |
+
https://arxiv.org/abs/1411.4280
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 118 |
+
"""
|
| 119 |
+
Runs the forward pass.
|
| 120 |
+
"""
|
| 121 |
+
return F.dropout1d(input, self.p, self.training, self.inplace)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class Dropout2d(_DropoutNd):
|
| 125 |
+
r"""Randomly zero out entire channels.
|
| 126 |
+
|
| 127 |
+
A channel is a 2D feature map,
|
| 128 |
+
e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
|
| 129 |
+
batched input is a 2D tensor :math:`\text{input}[i, j]`.
|
| 130 |
+
|
| 131 |
+
Each channel will be zeroed out independently on every forward call with
|
| 132 |
+
probability :attr:`p` using samples from a Bernoulli distribution.
|
| 133 |
+
|
| 134 |
+
Usually the input comes from :class:`nn.Conv2d` modules.
|
| 135 |
+
|
| 136 |
+
As described in the paper
|
| 137 |
+
`Efficient Object Localization Using Convolutional Networks`_ ,
|
| 138 |
+
if adjacent pixels within feature maps are strongly correlated
|
| 139 |
+
(as is normally the case in early convolution layers) then i.i.d. dropout
|
| 140 |
+
will not regularize the activations and will otherwise just result
|
| 141 |
+
in an effective learning rate decrease.
|
| 142 |
+
|
| 143 |
+
In this case, :func:`nn.Dropout2d` will help promote independence between
|
| 144 |
+
feature maps and should be used instead.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
p (float, optional): probability of an element to be zero-ed.
|
| 148 |
+
inplace (bool, optional): If set to ``True``, will do this operation
|
| 149 |
+
in-place
|
| 150 |
+
|
| 151 |
+
.. warning ::
|
| 152 |
+
Due to historical reasons, this class will perform 1D channel-wise dropout
|
| 153 |
+
for 3D inputs (as done by :class:`nn.Dropout1d`). Thus, it currently does NOT
|
| 154 |
+
support inputs without a batch dimension of shape :math:`(C, H, W)`. This
|
| 155 |
+
behavior will change in a future release to interpret 3D inputs as no-batch-dim
|
| 156 |
+
inputs. To maintain the old behavior, switch to :class:`nn.Dropout1d`.
|
| 157 |
+
|
| 158 |
+
Shape:
|
| 159 |
+
- Input: :math:`(N, C, H, W)` or :math:`(N, C, L)`.
|
| 160 |
+
- Output: :math:`(N, C, H, W)` or :math:`(N, C, L)` (same shape as input).
|
| 161 |
+
|
| 162 |
+
Examples::
|
| 163 |
+
|
| 164 |
+
>>> m = nn.Dropout2d(p=0.2)
|
| 165 |
+
>>> input = torch.randn(20, 16, 32, 32)
|
| 166 |
+
>>> output = m(input)
|
| 167 |
+
|
| 168 |
+
.. _Efficient Object Localization Using Convolutional Networks:
|
| 169 |
+
https://arxiv.org/abs/1411.4280
|
| 170 |
+
"""
|
| 171 |
+
|
| 172 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 173 |
+
"""
|
| 174 |
+
Runs the forward pass.
|
| 175 |
+
"""
|
| 176 |
+
return F.dropout2d(input, self.p, self.training, self.inplace)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Dropout3d(_DropoutNd):
|
| 180 |
+
r"""Randomly zero out entire channels.
|
| 181 |
+
|
| 182 |
+
A channel is a 3D feature map,
|
| 183 |
+
e.g., the :math:`j`-th channel of the :math:`i`-th sample in the
|
| 184 |
+
batched input is a 3D tensor :math:`\text{input}[i, j]`.
|
| 185 |
+
|
| 186 |
+
Each channel will be zeroed out independently on every forward call with
|
| 187 |
+
probability :attr:`p` using samples from a Bernoulli distribution.
|
| 188 |
+
|
| 189 |
+
Usually the input comes from :class:`nn.Conv3d` modules.
|
| 190 |
+
|
| 191 |
+
As described in the paper
|
| 192 |
+
`Efficient Object Localization Using Convolutional Networks`_ ,
|
| 193 |
+
if adjacent pixels within feature maps are strongly correlated
|
| 194 |
+
(as is normally the case in early convolution layers) then i.i.d. dropout
|
| 195 |
+
will not regularize the activations and will otherwise just result
|
| 196 |
+
in an effective learning rate decrease.
|
| 197 |
+
|
| 198 |
+
In this case, :func:`nn.Dropout3d` will help promote independence between
|
| 199 |
+
feature maps and should be used instead.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
p (float, optional): probability of an element to be zeroed.
|
| 203 |
+
inplace (bool, optional): If set to ``True``, will do this operation
|
| 204 |
+
in-place
|
| 205 |
+
|
| 206 |
+
Shape:
|
| 207 |
+
- Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`.
|
| 208 |
+
- Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input).
|
| 209 |
+
|
| 210 |
+
Examples::
|
| 211 |
+
|
| 212 |
+
>>> m = nn.Dropout3d(p=0.2)
|
| 213 |
+
>>> input = torch.randn(20, 16, 4, 32, 32)
|
| 214 |
+
>>> output = m(input)
|
| 215 |
+
|
| 216 |
+
.. _Efficient Object Localization Using Convolutional Networks:
|
| 217 |
+
https://arxiv.org/abs/1411.4280
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 221 |
+
"""
|
| 222 |
+
Runs the forward pass.
|
| 223 |
+
"""
|
| 224 |
+
return F.dropout3d(input, self.p, self.training, self.inplace)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class AlphaDropout(_DropoutNd):
|
| 228 |
+
r"""Applies Alpha Dropout over the input.
|
| 229 |
+
|
| 230 |
+
Alpha Dropout is a type of Dropout that maintains the self-normalizing
|
| 231 |
+
property.
|
| 232 |
+
For an input with zero mean and unit standard deviation, the output of
|
| 233 |
+
Alpha Dropout maintains the original mean and standard deviation of the
|
| 234 |
+
input.
|
| 235 |
+
Alpha Dropout goes hand-in-hand with SELU activation function, which ensures
|
| 236 |
+
that the outputs have zero mean and unit standard deviation.
|
| 237 |
+
|
| 238 |
+
During training, it randomly masks some of the elements of the input
|
| 239 |
+
tensor with probability *p* using samples from a bernoulli distribution.
|
| 240 |
+
The elements to be masked are randomized on every forward call, and scaled
|
| 241 |
+
and shifted to maintain zero mean and unit standard deviation.
|
| 242 |
+
|
| 243 |
+
During evaluation the module simply computes an identity function.
|
| 244 |
+
|
| 245 |
+
More details can be found in the paper `Self-Normalizing Neural Networks`_ .
|
| 246 |
+
|
| 247 |
+
Args:
|
| 248 |
+
p (float): probability of an element to be dropped. Default: 0.5
|
| 249 |
+
inplace (bool, optional): If set to ``True``, will do this operation
|
| 250 |
+
in-place
|
| 251 |
+
|
| 252 |
+
Shape:
|
| 253 |
+
- Input: :math:`(*)`. Input can be of any shape
|
| 254 |
+
- Output: :math:`(*)`. Output is of the same shape as input
|
| 255 |
+
|
| 256 |
+
Examples::
|
| 257 |
+
|
| 258 |
+
>>> m = nn.AlphaDropout(p=0.2)
|
| 259 |
+
>>> input = torch.randn(20, 16)
|
| 260 |
+
>>> output = m(input)
|
| 261 |
+
|
| 262 |
+
.. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 266 |
+
"""
|
| 267 |
+
Runs the forward pass.
|
| 268 |
+
"""
|
| 269 |
+
return F.alpha_dropout(input, self.p, self.training)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class FeatureAlphaDropout(_DropoutNd):
|
| 273 |
+
r"""Randomly masks out entire channels.
|
| 274 |
+
|
| 275 |
+
A channel is a feature map,
|
| 276 |
+
e.g. the :math:`j`-th channel of the :math:`i`-th sample in the batch input
|
| 277 |
+
is a tensor :math:`\text{input}[i, j]` of the input tensor). Instead of
|
| 278 |
+
setting activations to zero, as in regular Dropout, the activations are set
|
| 279 |
+
to the negative saturation value of the SELU activation function. More details
|
| 280 |
+
can be found in the paper `Self-Normalizing Neural Networks`_ .
|
| 281 |
+
|
| 282 |
+
Each element will be masked independently for each sample on every forward
|
| 283 |
+
call with probability :attr:`p` using samples from a Bernoulli distribution.
|
| 284 |
+
The elements to be masked are randomized on every forward call, and scaled
|
| 285 |
+
and shifted to maintain zero mean and unit variance.
|
| 286 |
+
|
| 287 |
+
Usually the input comes from :class:`nn.AlphaDropout` modules.
|
| 288 |
+
|
| 289 |
+
As described in the paper
|
| 290 |
+
`Efficient Object Localization Using Convolutional Networks`_ ,
|
| 291 |
+
if adjacent pixels within feature maps are strongly correlated
|
| 292 |
+
(as is normally the case in early convolution layers) then i.i.d. dropout
|
| 293 |
+
will not regularize the activations and will otherwise just result
|
| 294 |
+
in an effective learning rate decrease.
|
| 295 |
+
|
| 296 |
+
In this case, :func:`nn.AlphaDropout` will help promote independence between
|
| 297 |
+
feature maps and should be used instead.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
p (float, optional): probability of an element to be zeroed. Default: 0.5
|
| 301 |
+
inplace (bool, optional): If set to ``True``, will do this operation
|
| 302 |
+
in-place
|
| 303 |
+
|
| 304 |
+
Shape:
|
| 305 |
+
- Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`.
|
| 306 |
+
- Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input).
|
| 307 |
+
|
| 308 |
+
Examples::
|
| 309 |
+
|
| 310 |
+
>>> m = nn.FeatureAlphaDropout(p=0.2)
|
| 311 |
+
>>> input = torch.randn(20, 16, 4, 32, 32)
|
| 312 |
+
>>> output = m(input)
|
| 313 |
+
|
| 314 |
+
.. _Self-Normalizing Neural Networks: https://arxiv.org/abs/1706.02515
|
| 315 |
+
.. _Efficient Object Localization Using Convolutional Networks:
|
| 316 |
+
https://arxiv.org/abs/1411.4280
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 320 |
+
"""
|
| 321 |
+
Runs the forward pass.
|
| 322 |
+
"""
|
| 323 |
+
return F.feature_alpha_dropout(input, self.p, self.training)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/flatten.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
from torch import Tensor
|
| 4 |
+
from torch.types import _size
|
| 5 |
+
|
| 6 |
+
from .module import Module
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["Flatten", "Unflatten"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Flatten(Module):
|
| 13 |
+
r"""
|
| 14 |
+
Flattens a contiguous range of dims into a tensor.
|
| 15 |
+
|
| 16 |
+
For use with :class:`~nn.Sequential`, see :meth:`torch.flatten` for details.
|
| 17 |
+
|
| 18 |
+
Shape:
|
| 19 |
+
- Input: :math:`(*, S_{\text{start}},..., S_{i}, ..., S_{\text{end}}, *)`,'
|
| 20 |
+
where :math:`S_{i}` is the size at dimension :math:`i` and :math:`*` means any
|
| 21 |
+
number of dimensions including none.
|
| 22 |
+
- Output: :math:`(*, \prod_{i=\text{start}}^{\text{end}} S_{i}, *)`.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
start_dim: first dim to flatten (default = 1).
|
| 26 |
+
end_dim: last dim to flatten (default = -1).
|
| 27 |
+
|
| 28 |
+
Examples::
|
| 29 |
+
>>> input = torch.randn(32, 1, 5, 5)
|
| 30 |
+
>>> # With default parameters
|
| 31 |
+
>>> m = nn.Flatten()
|
| 32 |
+
>>> output = m(input)
|
| 33 |
+
>>> output.size()
|
| 34 |
+
torch.Size([32, 25])
|
| 35 |
+
>>> # With non-default parameters
|
| 36 |
+
>>> m = nn.Flatten(0, 2)
|
| 37 |
+
>>> output = m(input)
|
| 38 |
+
>>> output.size()
|
| 39 |
+
torch.Size([160, 5])
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
__constants__ = ["start_dim", "end_dim"]
|
| 43 |
+
start_dim: int
|
| 44 |
+
end_dim: int
|
| 45 |
+
|
| 46 |
+
def __init__(self, start_dim: int = 1, end_dim: int = -1) -> None:
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.start_dim = start_dim
|
| 49 |
+
self.end_dim = end_dim
|
| 50 |
+
|
| 51 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 52 |
+
"""
|
| 53 |
+
Runs the forward pass.
|
| 54 |
+
"""
|
| 55 |
+
return input.flatten(self.start_dim, self.end_dim)
|
| 56 |
+
|
| 57 |
+
def extra_repr(self) -> str:
|
| 58 |
+
"""
|
| 59 |
+
Returns the extra representation of the module.
|
| 60 |
+
"""
|
| 61 |
+
return f"start_dim={self.start_dim}, end_dim={self.end_dim}"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Unflatten(Module):
|
| 65 |
+
r"""
|
| 66 |
+
Unflattens a tensor dim expanding it to a desired shape. For use with :class:`~nn.Sequential`.
|
| 67 |
+
|
| 68 |
+
* :attr:`dim` specifies the dimension of the input tensor to be unflattened.
|
| 69 |
+
|
| 70 |
+
* :attr:`unflattened_size` is the new shape of the unflattened dimension of the tensor and it can be
|
| 71 |
+
a `tuple` of ints or a `list` of ints or `torch.Size` for `Tensor` input.
|
| 72 |
+
|
| 73 |
+
Shape:
|
| 74 |
+
- Input: :math:`(*, S_{\text{dim}}, *)`, where :math:`S_{\text{dim}}` is the size at
|
| 75 |
+
dimension :attr:`dim` and :math:`*` means any number of dimensions including none.
|
| 76 |
+
- Output: :math:`(*, U_1, ..., U_n, *)`, where :math:`U` = :attr:`unflattened_size` and
|
| 77 |
+
:math:`\prod_{i=1}^n U_i = S_{\text{dim}}`.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
dim (int): Dimension to be unflattened
|
| 81 |
+
unflattened_size (Union[torch.Size, Tuple, List]): New shape of the unflattened dimension
|
| 82 |
+
|
| 83 |
+
Examples:
|
| 84 |
+
>>> input = torch.randn(2, 50)
|
| 85 |
+
>>> # With tuple of ints
|
| 86 |
+
>>> m = nn.Sequential(
|
| 87 |
+
>>> nn.Linear(50, 50),
|
| 88 |
+
>>> nn.Unflatten(1, (2, 5, 5))
|
| 89 |
+
>>> )
|
| 90 |
+
>>> output = m(input)
|
| 91 |
+
>>> output.size()
|
| 92 |
+
torch.Size([2, 2, 5, 5])
|
| 93 |
+
>>> # With torch.Size
|
| 94 |
+
>>> m = nn.Sequential(
|
| 95 |
+
>>> nn.Linear(50, 50),
|
| 96 |
+
>>> nn.Unflatten(1, torch.Size([2, 5, 5]))
|
| 97 |
+
>>> )
|
| 98 |
+
>>> output = m(input)
|
| 99 |
+
>>> output.size()
|
| 100 |
+
torch.Size([2, 2, 5, 5])
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
__constants__ = ["dim", "unflattened_size"]
|
| 104 |
+
dim: int
|
| 105 |
+
unflattened_size: _size
|
| 106 |
+
|
| 107 |
+
def __init__(self, dim: int, unflattened_size: _size) -> None:
|
| 108 |
+
super().__init__()
|
| 109 |
+
self._require_tuple_int(unflattened_size)
|
| 110 |
+
self.dim = dim
|
| 111 |
+
self.unflattened_size = unflattened_size
|
| 112 |
+
|
| 113 |
+
def _require_tuple_int(self, input) -> None:
|
| 114 |
+
if isinstance(input, (tuple, list)):
|
| 115 |
+
for idx, elem in enumerate(input):
|
| 116 |
+
if not isinstance(elem, int):
|
| 117 |
+
raise TypeError(
|
| 118 |
+
"unflattened_size must be tuple of ints, "
|
| 119 |
+
+ f"but found element of type {type(elem).__name__} at pos {idx}"
|
| 120 |
+
)
|
| 121 |
+
return
|
| 122 |
+
raise TypeError(
|
| 123 |
+
f"unflattened_size must be a tuple of ints, but found type {type(input).__name__}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 127 |
+
"""
|
| 128 |
+
Runs the forward pass.
|
| 129 |
+
"""
|
| 130 |
+
return input.unflatten(self.dim, self.unflattened_size)
|
| 131 |
+
|
| 132 |
+
def extra_repr(self) -> str:
|
| 133 |
+
"""
|
| 134 |
+
Returns the extra representation of the module.
|
| 135 |
+
"""
|
| 136 |
+
return f"dim={self.dim}, unflattened_size={self.unflattened_size}"
|
.venv/lib/python3.12/site-packages/torch/nn/modules/fold.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
from torch.nn.common_types import _size_any_t
|
| 4 |
+
|
| 5 |
+
from .module import Module
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["Fold", "Unfold"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class Fold(Module):
|
| 12 |
+
(
|
| 13 |
+
r"""Combines an array of sliding local blocks into a large containing tensor.
|
| 14 |
+
|
| 15 |
+
Consider a batched :attr:`input` tensor containing sliding local blocks,
|
| 16 |
+
e.g., patches of images, of shape :math:`(N, C \times \prod(\text{kernel\_size}), L)`,
|
| 17 |
+
where :math:`N` is batch dimension, :math:`C \times \prod(\text{kernel\_size})`
|
| 18 |
+
is the number of values within a block (a block has :math:`\prod(\text{kernel\_size})`
|
| 19 |
+
spatial locations each containing a :math:`C`-channeled vector), and
|
| 20 |
+
:math:`L` is the total number of blocks. (This is exactly the
|
| 21 |
+
same specification as the output shape of :class:`~torch.nn.Unfold`.) This
|
| 22 |
+
operation combines these local blocks into the large :attr:`output` tensor
|
| 23 |
+
of shape :math:`(N, C, \text{output\_size}[0], \text{output\_size}[1], \dots)`
|
| 24 |
+
by summing the overlapping values. Similar to :class:`~torch.nn.Unfold`, the
|
| 25 |
+
arguments must satisfy
|
| 26 |
+
|
| 27 |
+
.. math::
|
| 28 |
+
L = \prod_d \left\lfloor\frac{\text{output\_size}[d] + 2 \times \text{padding}[d] %
|
| 29 |
+
- \text{dilation}[d] \times (\text{kernel\_size}[d] - 1) - 1}{\text{stride}[d]} + 1\right\rfloor,
|
| 30 |
+
|
| 31 |
+
where :math:`d` is over all spatial dimensions.
|
| 32 |
+
|
| 33 |
+
* :attr:`output_size` describes the spatial shape of the large containing
|
| 34 |
+
tensor of the sliding local blocks. It is useful to resolve the ambiguity
|
| 35 |
+
when multiple input shapes map to same number of sliding blocks, e.g.,
|
| 36 |
+
with ``stride > 0``.
|
| 37 |
+
|
| 38 |
+
The :attr:`padding`, :attr:`stride` and :attr:`dilation` arguments specify
|
| 39 |
+
how the sliding blocks are retrieved.
|
| 40 |
+
|
| 41 |
+
* :attr:`stride` controls the stride for the sliding blocks.
|
| 42 |
+
|
| 43 |
+
* :attr:`padding` controls the amount of implicit zero-paddings on both
|
| 44 |
+
sides for :attr:`padding` number of points for each dimension before
|
| 45 |
+
reshaping.
|
| 46 |
+
"""
|
| 47 |
+
"""
|
| 48 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 49 |
+
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
|
| 50 |
+
"""
|
| 51 |
+
r"""
|
| 52 |
+
Args:
|
| 53 |
+
output_size (int or tuple): the shape of the spatial dimensions of the
|
| 54 |
+
output (i.e., ``output.sizes()[2:]``)
|
| 55 |
+
kernel_size (int or tuple): the size of the sliding blocks
|
| 56 |
+
dilation (int or tuple, optional): a parameter that controls the
|
| 57 |
+
stride of elements within the
|
| 58 |
+
neighborhood. Default: 1
|
| 59 |
+
padding (int or tuple, optional): implicit zero padding to be added on
|
| 60 |
+
both sides of input. Default: 0
|
| 61 |
+
stride (int or tuple): the stride of the sliding blocks in the input
|
| 62 |
+
spatial dimensions. Default: 1
|
| 63 |
+
|
| 64 |
+
* If :attr:`output_size`, :attr:`kernel_size`, :attr:`dilation`,
|
| 65 |
+
:attr:`padding` or :attr:`stride` is an int or a tuple of length 1 then
|
| 66 |
+
their values will be replicated across all spatial dimensions.
|
| 67 |
+
|
| 68 |
+
* For the case of two output spatial dimensions this operation is sometimes
|
| 69 |
+
called ``col2im``.
|
| 70 |
+
|
| 71 |
+
.. note::
|
| 72 |
+
:class:`~torch.nn.Fold` calculates each combined value in the resulting
|
| 73 |
+
large tensor by summing all values from all containing blocks.
|
| 74 |
+
:class:`~torch.nn.Unfold` extracts the values in the local blocks by
|
| 75 |
+
copying from the large tensor. So, if the blocks overlap, they are not
|
| 76 |
+
inverses of each other.
|
| 77 |
+
|
| 78 |
+
In general, folding and unfolding operations are related as
|
| 79 |
+
follows. Consider :class:`~torch.nn.Fold` and
|
| 80 |
+
:class:`~torch.nn.Unfold` instances created with the same
|
| 81 |
+
parameters:
|
| 82 |
+
|
| 83 |
+
>>> fold_params = dict(kernel_size=..., dilation=..., padding=..., stride=...)
|
| 84 |
+
>>> fold = nn.Fold(output_size=..., **fold_params)
|
| 85 |
+
>>> unfold = nn.Unfold(**fold_params)
|
| 86 |
+
|
| 87 |
+
Then for any (supported) ``input`` tensor the following
|
| 88 |
+
equality holds:
|
| 89 |
+
|
| 90 |
+
::
|
| 91 |
+
|
| 92 |
+
fold(unfold(input)) == divisor * input
|
| 93 |
+
|
| 94 |
+
where ``divisor`` is a tensor that depends only on the shape
|
| 95 |
+
and dtype of the ``input``:
|
| 96 |
+
|
| 97 |
+
>>> # xdoctest: +SKIP
|
| 98 |
+
>>> input_ones = torch.ones(input.shape, dtype=input.dtype)
|
| 99 |
+
>>> divisor = fold(unfold(input_ones))
|
| 100 |
+
|
| 101 |
+
When the ``divisor`` tensor contains no zero elements, then
|
| 102 |
+
``fold`` and ``unfold`` operations are inverses of each
|
| 103 |
+
other (up to constant divisor).
|
| 104 |
+
|
| 105 |
+
.. warning::
|
| 106 |
+
Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.
|
| 107 |
+
|
| 108 |
+
Shape:
|
| 109 |
+
- Input: :math:`(N, C \times \prod(\text{kernel\_size}), L)` or :math:`(C \times \prod(\text{kernel\_size}), L)`
|
| 110 |
+
- Output: :math:`(N, C, \text{output\_size}[0], \text{output\_size}[1], \dots)`
|
| 111 |
+
or :math:`(C, \text{output\_size}[0], \text{output\_size}[1], \dots)` as described above
|
| 112 |
+
|
| 113 |
+
Examples::
|
| 114 |
+
|
| 115 |
+
>>> fold = nn.Fold(output_size=(4, 5), kernel_size=(2, 2))
|
| 116 |
+
>>> input = torch.randn(1, 3 * 2 * 2, 12)
|
| 117 |
+
>>> output = fold(input)
|
| 118 |
+
>>> output.size()
|
| 119 |
+
torch.Size([1, 3, 4, 5])
|
| 120 |
+
|
| 121 |
+
.. _link:
|
| 122 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
__constants__ = ["output_size", "kernel_size", "dilation", "padding", "stride"]
|
| 128 |
+
output_size: _size_any_t
|
| 129 |
+
kernel_size: _size_any_t
|
| 130 |
+
dilation: _size_any_t
|
| 131 |
+
padding: _size_any_t
|
| 132 |
+
stride: _size_any_t
|
| 133 |
+
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
output_size: _size_any_t,
|
| 137 |
+
kernel_size: _size_any_t,
|
| 138 |
+
dilation: _size_any_t = 1,
|
| 139 |
+
padding: _size_any_t = 0,
|
| 140 |
+
stride: _size_any_t = 1,
|
| 141 |
+
) -> None:
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.output_size = output_size
|
| 144 |
+
self.kernel_size = kernel_size
|
| 145 |
+
self.dilation = dilation
|
| 146 |
+
self.padding = padding
|
| 147 |
+
self.stride = stride
|
| 148 |
+
|
| 149 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 150 |
+
"""
|
| 151 |
+
Runs the forward pass.
|
| 152 |
+
"""
|
| 153 |
+
return F.fold(
|
| 154 |
+
input,
|
| 155 |
+
self.output_size,
|
| 156 |
+
self.kernel_size,
|
| 157 |
+
self.dilation,
|
| 158 |
+
self.padding,
|
| 159 |
+
self.stride,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def extra_repr(self) -> str:
|
| 163 |
+
"""
|
| 164 |
+
Return the extra representation of the module.
|
| 165 |
+
"""
|
| 166 |
+
return (
|
| 167 |
+
"output_size={output_size}, kernel_size={kernel_size}, "
|
| 168 |
+
"dilation={dilation}, padding={padding}, stride={stride}".format(
|
| 169 |
+
**self.__dict__
|
| 170 |
+
)
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class Unfold(Module):
|
| 175 |
+
(
|
| 176 |
+
r"""Extracts sliding local blocks from a batched input tensor.
|
| 177 |
+
|
| 178 |
+
Consider a batched :attr:`input` tensor of shape :math:`(N, C, *)`,
|
| 179 |
+
where :math:`N` is the batch dimension, :math:`C` is the channel dimension,
|
| 180 |
+
and :math:`*` represent arbitrary spatial dimensions. This operation flattens
|
| 181 |
+
each sliding :attr:`kernel_size`-sized block within the spatial dimensions
|
| 182 |
+
of :attr:`input` into a column (i.e., last dimension) of a 3-D :attr:`output`
|
| 183 |
+
tensor of shape :math:`(N, C \times \prod(\text{kernel\_size}), L)`, where
|
| 184 |
+
:math:`C \times \prod(\text{kernel\_size})` is the total number of values
|
| 185 |
+
within each block (a block has :math:`\prod(\text{kernel\_size})` spatial
|
| 186 |
+
locations each containing a :math:`C`-channeled vector), and :math:`L` is
|
| 187 |
+
the total number of such blocks:
|
| 188 |
+
|
| 189 |
+
.. math::
|
| 190 |
+
L = \prod_d \left\lfloor\frac{\text{spatial\_size}[d] + 2 \times \text{padding}[d] %
|
| 191 |
+
- \text{dilation}[d] \times (\text{kernel\_size}[d] - 1) - 1}{\text{stride}[d]} + 1\right\rfloor,
|
| 192 |
+
|
| 193 |
+
where :math:`\text{spatial\_size}` is formed by the spatial dimensions
|
| 194 |
+
of :attr:`input` (:math:`*` above), and :math:`d` is over all spatial
|
| 195 |
+
dimensions.
|
| 196 |
+
|
| 197 |
+
Therefore, indexing :attr:`output` at the last dimension (column dimension)
|
| 198 |
+
gives all values within a certain block.
|
| 199 |
+
|
| 200 |
+
The :attr:`padding`, :attr:`stride` and :attr:`dilation` arguments specify
|
| 201 |
+
how the sliding blocks are retrieved.
|
| 202 |
+
|
| 203 |
+
* :attr:`stride` controls the stride for the sliding blocks.
|
| 204 |
+
|
| 205 |
+
* :attr:`padding` controls the amount of implicit zero-paddings on both
|
| 206 |
+
sides for :attr:`padding` number of points for each dimension before
|
| 207 |
+
reshaping.
|
| 208 |
+
"""
|
| 209 |
+
"""
|
| 210 |
+
* :attr:`dilation` controls the spacing between the kernel points; also known as the \u00e0 trous algorithm.
|
| 211 |
+
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
|
| 212 |
+
"""
|
| 213 |
+
r"""
|
| 214 |
+
Args:
|
| 215 |
+
kernel_size (int or tuple): the size of the sliding blocks
|
| 216 |
+
dilation (int or tuple, optional): a parameter that controls the
|
| 217 |
+
stride of elements within the
|
| 218 |
+
neighborhood. Default: 1
|
| 219 |
+
padding (int or tuple, optional): implicit zero padding to be added on
|
| 220 |
+
both sides of input. Default: 0
|
| 221 |
+
stride (int or tuple, optional): the stride of the sliding blocks in the input
|
| 222 |
+
spatial dimensions. Default: 1
|
| 223 |
+
|
| 224 |
+
* If :attr:`kernel_size`, :attr:`dilation`, :attr:`padding` or
|
| 225 |
+
:attr:`stride` is an int or a tuple of length 1, their values will be
|
| 226 |
+
replicated across all spatial dimensions.
|
| 227 |
+
|
| 228 |
+
* For the case of two input spatial dimensions this operation is sometimes
|
| 229 |
+
called ``im2col``.
|
| 230 |
+
|
| 231 |
+
.. note::
|
| 232 |
+
:class:`~torch.nn.Fold` calculates each combined value in the resulting
|
| 233 |
+
large tensor by summing all values from all containing blocks.
|
| 234 |
+
:class:`~torch.nn.Unfold` extracts the values in the local blocks by
|
| 235 |
+
copying from the large tensor. So, if the blocks overlap, they are not
|
| 236 |
+
inverses of each other.
|
| 237 |
+
|
| 238 |
+
In general, folding and unfolding operations are related as
|
| 239 |
+
follows. Consider :class:`~torch.nn.Fold` and
|
| 240 |
+
:class:`~torch.nn.Unfold` instances created with the same
|
| 241 |
+
parameters:
|
| 242 |
+
|
| 243 |
+
>>> fold_params = dict(kernel_size=..., dilation=..., padding=..., stride=...)
|
| 244 |
+
>>> fold = nn.Fold(output_size=..., **fold_params)
|
| 245 |
+
>>> unfold = nn.Unfold(**fold_params)
|
| 246 |
+
|
| 247 |
+
Then for any (supported) ``input`` tensor the following
|
| 248 |
+
equality holds:
|
| 249 |
+
|
| 250 |
+
::
|
| 251 |
+
|
| 252 |
+
fold(unfold(input)) == divisor * input
|
| 253 |
+
|
| 254 |
+
where ``divisor`` is a tensor that depends only on the shape
|
| 255 |
+
and dtype of the ``input``:
|
| 256 |
+
|
| 257 |
+
>>> # xdoctest: +SKIP
|
| 258 |
+
>>> input_ones = torch.ones(input.shape, dtype=input.dtype)
|
| 259 |
+
>>> divisor = fold(unfold(input_ones))
|
| 260 |
+
|
| 261 |
+
When the ``divisor`` tensor contains no zero elements, then
|
| 262 |
+
``fold`` and ``unfold`` operations are inverses of each
|
| 263 |
+
other (up to constant divisor).
|
| 264 |
+
|
| 265 |
+
.. warning::
|
| 266 |
+
Currently, only 4-D input tensors (batched image-like tensors) are
|
| 267 |
+
supported.
|
| 268 |
+
|
| 269 |
+
Shape:
|
| 270 |
+
- Input: :math:`(N, C, *)`
|
| 271 |
+
- Output: :math:`(N, C \times \prod(\text{kernel\_size}), L)` as described above
|
| 272 |
+
|
| 273 |
+
Examples::
|
| 274 |
+
|
| 275 |
+
>>> unfold = nn.Unfold(kernel_size=(2, 3))
|
| 276 |
+
>>> input = torch.randn(2, 5, 3, 4)
|
| 277 |
+
>>> output = unfold(input)
|
| 278 |
+
>>> # each patch contains 30 values (2x3=6 vectors, each of 5 channels)
|
| 279 |
+
>>> # 4 blocks (2x3 kernels) in total in the 3x4 input
|
| 280 |
+
>>> output.size()
|
| 281 |
+
torch.Size([2, 30, 4])
|
| 282 |
+
|
| 283 |
+
>>> # xdoctest: +IGNORE_WANT
|
| 284 |
+
>>> # Convolution is equivalent with Unfold + Matrix Multiplication + Fold (or view to output shape)
|
| 285 |
+
>>> inp = torch.randn(1, 3, 10, 12)
|
| 286 |
+
>>> w = torch.randn(2, 3, 4, 5)
|
| 287 |
+
>>> inp_unf = torch.nn.functional.unfold(inp, (4, 5))
|
| 288 |
+
>>> out_unf = inp_unf.transpose(1, 2).matmul(w.view(w.size(0), -1).t()).transpose(1, 2)
|
| 289 |
+
>>> out = torch.nn.functional.fold(out_unf, (7, 8), (1, 1))
|
| 290 |
+
>>> # or equivalently (and avoiding a copy),
|
| 291 |
+
>>> # out = out_unf.view(1, 2, 7, 8)
|
| 292 |
+
>>> (torch.nn.functional.conv2d(inp, w) - out).abs().max()
|
| 293 |
+
tensor(1.9073e-06)
|
| 294 |
+
|
| 295 |
+
.. _link:
|
| 296 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 297 |
+
|
| 298 |
+
"""
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
__constants__ = ["kernel_size", "dilation", "padding", "stride"]
|
| 302 |
+
kernel_size: _size_any_t
|
| 303 |
+
dilation: _size_any_t
|
| 304 |
+
padding: _size_any_t
|
| 305 |
+
stride: _size_any_t
|
| 306 |
+
|
| 307 |
+
def __init__(
|
| 308 |
+
self,
|
| 309 |
+
kernel_size: _size_any_t,
|
| 310 |
+
dilation: _size_any_t = 1,
|
| 311 |
+
padding: _size_any_t = 0,
|
| 312 |
+
stride: _size_any_t = 1,
|
| 313 |
+
) -> None:
|
| 314 |
+
super().__init__()
|
| 315 |
+
self.kernel_size = kernel_size
|
| 316 |
+
self.dilation = dilation
|
| 317 |
+
self.padding = padding
|
| 318 |
+
self.stride = stride
|
| 319 |
+
|
| 320 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 321 |
+
"""
|
| 322 |
+
Runs the forward pass.
|
| 323 |
+
"""
|
| 324 |
+
return F.unfold(
|
| 325 |
+
input, self.kernel_size, self.dilation, self.padding, self.stride
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
def extra_repr(self) -> str:
|
| 329 |
+
"""
|
| 330 |
+
Return the extra representation of the module.
|
| 331 |
+
"""
|
| 332 |
+
return (
|
| 333 |
+
"kernel_size={kernel_size}, dilation={dilation}, padding={padding},"
|
| 334 |
+
" stride={stride}".format(**self.__dict__)
|
| 335 |
+
)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/instancenorm.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
|
| 8 |
+
from .batchnorm import _LazyNormBase, _NormBase
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = [
|
| 12 |
+
"InstanceNorm1d",
|
| 13 |
+
"InstanceNorm2d",
|
| 14 |
+
"InstanceNorm3d",
|
| 15 |
+
"LazyInstanceNorm1d",
|
| 16 |
+
"LazyInstanceNorm2d",
|
| 17 |
+
"LazyInstanceNorm3d",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class _InstanceNorm(_NormBase):
|
| 22 |
+
def __init__(
|
| 23 |
+
self,
|
| 24 |
+
num_features: int,
|
| 25 |
+
eps: float = 1e-5,
|
| 26 |
+
momentum: float = 0.1,
|
| 27 |
+
affine: bool = False,
|
| 28 |
+
track_running_stats: bool = False,
|
| 29 |
+
device=None,
|
| 30 |
+
dtype=None,
|
| 31 |
+
*,
|
| 32 |
+
bias: bool = True, # for backward compatibility
|
| 33 |
+
) -> None:
|
| 34 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 35 |
+
super().__init__(
|
| 36 |
+
num_features,
|
| 37 |
+
eps,
|
| 38 |
+
momentum,
|
| 39 |
+
affine,
|
| 40 |
+
track_running_stats,
|
| 41 |
+
**factory_kwargs,
|
| 42 |
+
bias=bias,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def _check_input_dim(self, input):
|
| 46 |
+
raise NotImplementedError
|
| 47 |
+
|
| 48 |
+
def _get_no_batch_dim(self):
|
| 49 |
+
raise NotImplementedError
|
| 50 |
+
|
| 51 |
+
def _handle_no_batch_input(self, input):
|
| 52 |
+
return self._apply_instance_norm(input.unsqueeze(0)).squeeze(0)
|
| 53 |
+
|
| 54 |
+
def _apply_instance_norm(self, input):
|
| 55 |
+
return F.instance_norm(
|
| 56 |
+
input,
|
| 57 |
+
self.running_mean,
|
| 58 |
+
self.running_var,
|
| 59 |
+
self.weight,
|
| 60 |
+
self.bias,
|
| 61 |
+
self.training or not self.track_running_stats,
|
| 62 |
+
self.momentum if self.momentum is not None else 0.0,
|
| 63 |
+
self.eps,
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def _load_from_state_dict(
|
| 67 |
+
self,
|
| 68 |
+
state_dict,
|
| 69 |
+
prefix,
|
| 70 |
+
local_metadata,
|
| 71 |
+
strict,
|
| 72 |
+
missing_keys,
|
| 73 |
+
unexpected_keys,
|
| 74 |
+
error_msgs,
|
| 75 |
+
) -> None:
|
| 76 |
+
version = local_metadata.get("version", None)
|
| 77 |
+
# at version 1: removed running_mean and running_var when
|
| 78 |
+
# track_running_stats=False (default)
|
| 79 |
+
if version is None and not self.track_running_stats:
|
| 80 |
+
running_stats_keys = []
|
| 81 |
+
for name in ("running_mean", "running_var"):
|
| 82 |
+
key = prefix + name
|
| 83 |
+
if key in state_dict:
|
| 84 |
+
running_stats_keys.append(key)
|
| 85 |
+
if len(running_stats_keys) > 0:
|
| 86 |
+
error_msgs.append(
|
| 87 |
+
"Unexpected running stats buffer(s) {names} for {klass} "
|
| 88 |
+
"with track_running_stats=False. If state_dict is a "
|
| 89 |
+
"checkpoint saved before 0.4.0, this may be expected "
|
| 90 |
+
"because {klass} does not track running stats by default "
|
| 91 |
+
"since 0.4.0. Please remove these keys from state_dict. If "
|
| 92 |
+
"the running stats are actually needed, instead set "
|
| 93 |
+
"track_running_stats=True in {klass} to enable them. See "
|
| 94 |
+
"the documentation of {klass} for details.".format(
|
| 95 |
+
names=" and ".join(f'"{k}"' for k in running_stats_keys),
|
| 96 |
+
klass=self.__class__.__name__,
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
for key in running_stats_keys:
|
| 100 |
+
state_dict.pop(key)
|
| 101 |
+
|
| 102 |
+
super()._load_from_state_dict(
|
| 103 |
+
state_dict,
|
| 104 |
+
prefix,
|
| 105 |
+
local_metadata,
|
| 106 |
+
strict,
|
| 107 |
+
missing_keys,
|
| 108 |
+
unexpected_keys,
|
| 109 |
+
error_msgs,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 113 |
+
self._check_input_dim(input)
|
| 114 |
+
|
| 115 |
+
feature_dim = input.dim() - self._get_no_batch_dim()
|
| 116 |
+
if input.size(feature_dim) != self.num_features:
|
| 117 |
+
if self.affine:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f"expected input's size at dim={feature_dim} to match num_features"
|
| 120 |
+
f" ({self.num_features}), but got: {input.size(feature_dim)}."
|
| 121 |
+
)
|
| 122 |
+
else:
|
| 123 |
+
warnings.warn(
|
| 124 |
+
f"input's size at dim={feature_dim} does not match num_features. "
|
| 125 |
+
"You can silence this warning by not passing in num_features, "
|
| 126 |
+
"which is not used because affine=False",
|
| 127 |
+
stacklevel=2,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if input.dim() == self._get_no_batch_dim():
|
| 131 |
+
return self._handle_no_batch_input(input)
|
| 132 |
+
|
| 133 |
+
return self._apply_instance_norm(input)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class InstanceNorm1d(_InstanceNorm):
|
| 137 |
+
r"""Applies Instance Normalization.
|
| 138 |
+
|
| 139 |
+
This operation applies Instance Normalization
|
| 140 |
+
over a 2D (unbatched) or 3D (batched) input as described in the paper
|
| 141 |
+
`Instance Normalization: The Missing Ingredient for Fast Stylization
|
| 142 |
+
<https://arxiv.org/abs/1607.08022>`__.
|
| 143 |
+
|
| 144 |
+
.. math::
|
| 145 |
+
|
| 146 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 147 |
+
|
| 148 |
+
The mean and standard-deviation are calculated per-dimension separately
|
| 149 |
+
for each object in a mini-batch. :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 150 |
+
of size `C` (where `C` is the number of features or channels of the input) if :attr:`affine` is ``True``.
|
| 151 |
+
The variance is calculated via the biased estimator, equivalent to
|
| 152 |
+
`torch.var(input, correction=0)`.
|
| 153 |
+
|
| 154 |
+
By default, this layer uses instance statistics computed from input data in
|
| 155 |
+
both training and evaluation modes.
|
| 156 |
+
|
| 157 |
+
If :attr:`track_running_stats` is set to ``True``, during training this
|
| 158 |
+
layer keeps running estimates of its computed mean and variance, which are
|
| 159 |
+
then used for normalization during evaluation. The running estimates are
|
| 160 |
+
kept with a default :attr:`momentum` of 0.1.
|
| 161 |
+
|
| 162 |
+
.. note::
|
| 163 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 164 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 165 |
+
update rule for running statistics here is
|
| 166 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 167 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 168 |
+
new observed value.
|
| 169 |
+
|
| 170 |
+
.. note::
|
| 171 |
+
:class:`InstanceNorm1d` and :class:`LayerNorm` are very similar, but
|
| 172 |
+
have some subtle differences. :class:`InstanceNorm1d` is applied
|
| 173 |
+
on each channel of channeled data like multidimensional time series, but
|
| 174 |
+
:class:`LayerNorm` is usually applied on entire sample and often in NLP
|
| 175 |
+
tasks. Additionally, :class:`LayerNorm` applies elementwise affine
|
| 176 |
+
transform, while :class:`InstanceNorm1d` usually doesn't apply affine
|
| 177 |
+
transform.
|
| 178 |
+
|
| 179 |
+
Args:
|
| 180 |
+
num_features: number of features or channels :math:`C` of the input
|
| 181 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 182 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 183 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 184 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 185 |
+
Default: ``False``
|
| 186 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 187 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 188 |
+
this module does not track such statistics and always uses batch
|
| 189 |
+
statistics in both training and eval modes. Default: ``False``
|
| 190 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 191 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 192 |
+
|
| 193 |
+
Shape:
|
| 194 |
+
- Input: :math:`(N, C, L)` or :math:`(C, L)`
|
| 195 |
+
- Output: :math:`(N, C, L)` or :math:`(C, L)` (same shape as input)
|
| 196 |
+
|
| 197 |
+
Examples::
|
| 198 |
+
|
| 199 |
+
>>> # Without Learnable Parameters
|
| 200 |
+
>>> m = nn.InstanceNorm1d(100)
|
| 201 |
+
>>> # With Learnable Parameters
|
| 202 |
+
>>> m = nn.InstanceNorm1d(100, affine=True)
|
| 203 |
+
>>> input = torch.randn(20, 100, 40)
|
| 204 |
+
>>> output = m(input)
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def _get_no_batch_dim(self) -> int:
|
| 208 |
+
return 2
|
| 209 |
+
|
| 210 |
+
def _check_input_dim(self, input) -> None:
|
| 211 |
+
if input.dim() not in (2, 3):
|
| 212 |
+
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class LazyInstanceNorm1d(_LazyNormBase, _InstanceNorm):
|
| 216 |
+
r"""A :class:`torch.nn.InstanceNorm1d` module with lazy initialization of the ``num_features`` argument.
|
| 217 |
+
|
| 218 |
+
The ``num_features`` argument of the :class:`InstanceNorm1d` is inferred from the ``input.size(1)``.
|
| 219 |
+
The attributes that will be lazily initialized are `weight`, `bias`, `running_mean` and `running_var`.
|
| 220 |
+
|
| 221 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 222 |
+
on lazy modules and their limitations.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
num_features: :math:`C` from an expected input of size
|
| 226 |
+
:math:`(N, C, L)` or :math:`(C, L)`
|
| 227 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 228 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 229 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 230 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 231 |
+
Default: ``False``
|
| 232 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 233 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 234 |
+
this module does not track such statistics and always uses batch
|
| 235 |
+
statistics in both training and eval modes. Default: ``False``
|
| 236 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 237 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 238 |
+
|
| 239 |
+
Shape:
|
| 240 |
+
- Input: :math:`(N, C, L)` or :math:`(C, L)`
|
| 241 |
+
- Output: :math:`(N, C, L)` or :math:`(C, L)` (same shape as input)
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
cls_to_become = InstanceNorm1d # type: ignore[assignment]
|
| 245 |
+
|
| 246 |
+
def _get_no_batch_dim(self) -> int:
|
| 247 |
+
return 2
|
| 248 |
+
|
| 249 |
+
def _check_input_dim(self, input) -> None:
|
| 250 |
+
if input.dim() not in (2, 3):
|
| 251 |
+
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class InstanceNorm2d(_InstanceNorm):
|
| 255 |
+
r"""Applies Instance Normalization.
|
| 256 |
+
|
| 257 |
+
This operation applies Instance Normalization
|
| 258 |
+
over a 4D input (a mini-batch of 2D inputs
|
| 259 |
+
with additional channel dimension) as described in the paper
|
| 260 |
+
`Instance Normalization: The Missing Ingredient for Fast Stylization
|
| 261 |
+
<https://arxiv.org/abs/1607.08022>`__.
|
| 262 |
+
|
| 263 |
+
.. math::
|
| 264 |
+
|
| 265 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 266 |
+
|
| 267 |
+
The mean and standard-deviation are calculated per-dimension separately
|
| 268 |
+
for each object in a mini-batch. :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 269 |
+
of size `C` (where `C` is the input size) if :attr:`affine` is ``True``.
|
| 270 |
+
The standard-deviation is calculated via the biased estimator, equivalent to
|
| 271 |
+
`torch.var(input, correction=0)`.
|
| 272 |
+
|
| 273 |
+
By default, this layer uses instance statistics computed from input data in
|
| 274 |
+
both training and evaluation modes.
|
| 275 |
+
|
| 276 |
+
If :attr:`track_running_stats` is set to ``True``, during training this
|
| 277 |
+
layer keeps running estimates of its computed mean and variance, which are
|
| 278 |
+
then used for normalization during evaluation. The running estimates are
|
| 279 |
+
kept with a default :attr:`momentum` of 0.1.
|
| 280 |
+
|
| 281 |
+
.. note::
|
| 282 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 283 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 284 |
+
update rule for running statistics here is
|
| 285 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 286 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 287 |
+
new observed value.
|
| 288 |
+
|
| 289 |
+
.. note::
|
| 290 |
+
:class:`InstanceNorm2d` and :class:`LayerNorm` are very similar, but
|
| 291 |
+
have some subtle differences. :class:`InstanceNorm2d` is applied
|
| 292 |
+
on each channel of channeled data like RGB images, but
|
| 293 |
+
:class:`LayerNorm` is usually applied on entire sample and often in NLP
|
| 294 |
+
tasks. Additionally, :class:`LayerNorm` applies elementwise affine
|
| 295 |
+
transform, while :class:`InstanceNorm2d` usually doesn't apply affine
|
| 296 |
+
transform.
|
| 297 |
+
|
| 298 |
+
Args:
|
| 299 |
+
num_features: :math:`C` from an expected input of size
|
| 300 |
+
:math:`(N, C, H, W)` or :math:`(C, H, W)`
|
| 301 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 302 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 303 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 304 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 305 |
+
Default: ``False``
|
| 306 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 307 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 308 |
+
this module does not track such statistics and always uses batch
|
| 309 |
+
statistics in both training and eval modes. Default: ``False``
|
| 310 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 311 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 312 |
+
|
| 313 |
+
Shape:
|
| 314 |
+
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`
|
| 315 |
+
- Output: :math:`(N, C, H, W)` or :math:`(C, H, W)` (same shape as input)
|
| 316 |
+
|
| 317 |
+
Examples::
|
| 318 |
+
|
| 319 |
+
>>> # Without Learnable Parameters
|
| 320 |
+
>>> m = nn.InstanceNorm2d(100)
|
| 321 |
+
>>> # With Learnable Parameters
|
| 322 |
+
>>> m = nn.InstanceNorm2d(100, affine=True)
|
| 323 |
+
>>> input = torch.randn(20, 100, 35, 45)
|
| 324 |
+
>>> output = m(input)
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
def _get_no_batch_dim(self) -> int:
|
| 328 |
+
return 3
|
| 329 |
+
|
| 330 |
+
def _check_input_dim(self, input) -> None:
|
| 331 |
+
if input.dim() not in (3, 4):
|
| 332 |
+
raise ValueError(f"expected 3D or 4D input (got {input.dim()}D input)")
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class LazyInstanceNorm2d(_LazyNormBase, _InstanceNorm):
|
| 336 |
+
r"""A :class:`torch.nn.InstanceNorm2d` module with lazy initialization of the ``num_features`` argument.
|
| 337 |
+
|
| 338 |
+
The ``num_features`` argument of the :class:`InstanceNorm2d` is inferred from the ``input.size(1)``.
|
| 339 |
+
The attributes that will be lazily initialized are `weight`, `bias`,
|
| 340 |
+
`running_mean` and `running_var`.
|
| 341 |
+
|
| 342 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 343 |
+
on lazy modules and their limitations.
|
| 344 |
+
|
| 345 |
+
Args:
|
| 346 |
+
num_features: :math:`C` from an expected input of size
|
| 347 |
+
:math:`(N, C, H, W)` or :math:`(C, H, W)`
|
| 348 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 349 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 350 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 351 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 352 |
+
Default: ``False``
|
| 353 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 354 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 355 |
+
this module does not track such statistics and always uses batch
|
| 356 |
+
statistics in both training and eval modes. Default: ``False``
|
| 357 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 358 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 359 |
+
|
| 360 |
+
Shape:
|
| 361 |
+
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)`
|
| 362 |
+
- Output: :math:`(N, C, H, W)` or :math:`(C, H, W)` (same shape as input)
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
cls_to_become = InstanceNorm2d # type: ignore[assignment]
|
| 366 |
+
|
| 367 |
+
def _get_no_batch_dim(self) -> int:
|
| 368 |
+
return 3
|
| 369 |
+
|
| 370 |
+
def _check_input_dim(self, input) -> None:
|
| 371 |
+
if input.dim() not in (3, 4):
|
| 372 |
+
raise ValueError(f"expected 3D or 4D input (got {input.dim()}D input)")
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class InstanceNorm3d(_InstanceNorm):
|
| 376 |
+
r"""Applies Instance Normalization.
|
| 377 |
+
|
| 378 |
+
This operation applies Instance Normalization
|
| 379 |
+
over a 5D input (a mini-batch of 3D inputs with additional channel dimension) as described in the paper
|
| 380 |
+
`Instance Normalization: The Missing Ingredient for Fast Stylization
|
| 381 |
+
<https://arxiv.org/abs/1607.08022>`__.
|
| 382 |
+
|
| 383 |
+
.. math::
|
| 384 |
+
|
| 385 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 386 |
+
|
| 387 |
+
The mean and standard-deviation are calculated per-dimension separately
|
| 388 |
+
for each object in a mini-batch. :math:`\gamma` and :math:`\beta` are learnable parameter vectors
|
| 389 |
+
of size C (where C is the input size) if :attr:`affine` is ``True``.
|
| 390 |
+
The standard-deviation is calculated via the biased estimator, equivalent to
|
| 391 |
+
`torch.var(input, correction=0)`.
|
| 392 |
+
|
| 393 |
+
By default, this layer uses instance statistics computed from input data in
|
| 394 |
+
both training and evaluation modes.
|
| 395 |
+
|
| 396 |
+
If :attr:`track_running_stats` is set to ``True``, during training this
|
| 397 |
+
layer keeps running estimates of its computed mean and variance, which are
|
| 398 |
+
then used for normalization during evaluation. The running estimates are
|
| 399 |
+
kept with a default :attr:`momentum` of 0.1.
|
| 400 |
+
|
| 401 |
+
.. note::
|
| 402 |
+
This :attr:`momentum` argument is different from one used in optimizer
|
| 403 |
+
classes and the conventional notion of momentum. Mathematically, the
|
| 404 |
+
update rule for running statistics here is
|
| 405 |
+
:math:`\hat{x}_\text{new} = (1 - \text{momentum}) \times \hat{x} + \text{momentum} \times x_t`,
|
| 406 |
+
where :math:`\hat{x}` is the estimated statistic and :math:`x_t` is the
|
| 407 |
+
new observed value.
|
| 408 |
+
|
| 409 |
+
.. note::
|
| 410 |
+
:class:`InstanceNorm3d` and :class:`LayerNorm` are very similar, but
|
| 411 |
+
have some subtle differences. :class:`InstanceNorm3d` is applied
|
| 412 |
+
on each channel of channeled data like 3D models with RGB color, but
|
| 413 |
+
:class:`LayerNorm` is usually applied on entire sample and often in NLP
|
| 414 |
+
tasks. Additionally, :class:`LayerNorm` applies elementwise affine
|
| 415 |
+
transform, while :class:`InstanceNorm3d` usually doesn't apply affine
|
| 416 |
+
transform.
|
| 417 |
+
|
| 418 |
+
Args:
|
| 419 |
+
num_features: :math:`C` from an expected input of size
|
| 420 |
+
:math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`
|
| 421 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 422 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 423 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 424 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 425 |
+
Default: ``False``
|
| 426 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 427 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 428 |
+
this module does not track such statistics and always uses batch
|
| 429 |
+
statistics in both training and eval modes. Default: ``False``
|
| 430 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 431 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 432 |
+
|
| 433 |
+
Shape:
|
| 434 |
+
- Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`
|
| 435 |
+
- Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input)
|
| 436 |
+
|
| 437 |
+
Examples::
|
| 438 |
+
|
| 439 |
+
>>> # Without Learnable Parameters
|
| 440 |
+
>>> m = nn.InstanceNorm3d(100)
|
| 441 |
+
>>> # With Learnable Parameters
|
| 442 |
+
>>> m = nn.InstanceNorm3d(100, affine=True)
|
| 443 |
+
>>> input = torch.randn(20, 100, 35, 45, 10)
|
| 444 |
+
>>> output = m(input)
|
| 445 |
+
"""
|
| 446 |
+
|
| 447 |
+
def _get_no_batch_dim(self) -> int:
|
| 448 |
+
return 4
|
| 449 |
+
|
| 450 |
+
def _check_input_dim(self, input) -> None:
|
| 451 |
+
if input.dim() not in (4, 5):
|
| 452 |
+
raise ValueError(f"expected 4D or 5D input (got {input.dim()}D input)")
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class LazyInstanceNorm3d(_LazyNormBase, _InstanceNorm):
|
| 456 |
+
r"""A :class:`torch.nn.InstanceNorm3d` module with lazy initialization of the ``num_features`` argument.
|
| 457 |
+
|
| 458 |
+
The ``num_features`` argument of the :class:`InstanceNorm3d` is inferred from the ``input.size(1)``.
|
| 459 |
+
The attributes that will be lazily initialized are `weight`, `bias`,
|
| 460 |
+
`running_mean` and `running_var`.
|
| 461 |
+
|
| 462 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 463 |
+
on lazy modules and their limitations.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
num_features: :math:`C` from an expected input of size
|
| 467 |
+
:math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`
|
| 468 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 469 |
+
momentum: the value used for the running_mean and running_var computation. Default: 0.1
|
| 470 |
+
affine: a boolean value that when set to ``True``, this module has
|
| 471 |
+
learnable affine parameters, initialized the same way as done for batch normalization.
|
| 472 |
+
Default: ``False``
|
| 473 |
+
track_running_stats: a boolean value that when set to ``True``, this
|
| 474 |
+
module tracks the running mean and variance, and when set to ``False``,
|
| 475 |
+
this module does not track such statistics and always uses batch
|
| 476 |
+
statistics in both training and eval modes. Default: ``False``
|
| 477 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 478 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 479 |
+
|
| 480 |
+
Shape:
|
| 481 |
+
- Input: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)`
|
| 482 |
+
- Output: :math:`(N, C, D, H, W)` or :math:`(C, D, H, W)` (same shape as input)
|
| 483 |
+
"""
|
| 484 |
+
|
| 485 |
+
cls_to_become = InstanceNorm3d # type: ignore[assignment]
|
| 486 |
+
|
| 487 |
+
def _get_no_batch_dim(self) -> int:
|
| 488 |
+
return 4
|
| 489 |
+
|
| 490 |
+
def _check_input_dim(self, input) -> None:
|
| 491 |
+
if input.dim() not in (4, 5):
|
| 492 |
+
raise ValueError(f"expected 4D or 5D input (got {input.dim()}D input)")
|
.venv/lib/python3.12/site-packages/torch/nn/modules/lazy.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import itertools
|
| 3 |
+
from typing import Any, Protocol
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.nn.parameter import is_lazy
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = ["LazyModuleMixin"]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class _LazyProtocol(Protocol):
|
| 13 |
+
"""This class is used to avoid errors with mypy checks for the attributes in a mixin.
|
| 14 |
+
|
| 15 |
+
https://mypy.readthedocs.io/en/latest/more_types.html#mixin-classes
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def _register_load_state_dict_pre_hook(self, hook): ...
|
| 19 |
+
|
| 20 |
+
def register_forward_pre_hook(self, hook, *, prepend=False, with_kwargs=False): ...
|
| 21 |
+
|
| 22 |
+
def _lazy_load_hook(
|
| 23 |
+
self,
|
| 24 |
+
state_dict,
|
| 25 |
+
prefix,
|
| 26 |
+
local_metadata,
|
| 27 |
+
strict,
|
| 28 |
+
missing_keys,
|
| 29 |
+
unexpected_keys,
|
| 30 |
+
error_msgs,
|
| 31 |
+
): ...
|
| 32 |
+
|
| 33 |
+
def _get_name(self): ...
|
| 34 |
+
|
| 35 |
+
def _infer_parameters(self, module, input): ...
|
| 36 |
+
|
| 37 |
+
@property
|
| 38 |
+
def _parameters(self): ...
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def _buffers(self): ...
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def _non_persistent_buffers_set(self): ...
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def _load_hook(self): ...
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def _initialize_hook(self): ...
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class LazyModuleMixin:
|
| 54 |
+
r"""A mixin for modules that lazily initialize parameters, also known as "lazy modules".
|
| 55 |
+
|
| 56 |
+
.. warning::
|
| 57 |
+
Lazy modules are an experimental new feature under active development,
|
| 58 |
+
and their API is likely to change.
|
| 59 |
+
|
| 60 |
+
Modules that lazily initialize parameters, or "lazy modules",
|
| 61 |
+
derive the shapes of their parameters from the first input(s)
|
| 62 |
+
to their forward method. Until that first forward they contain
|
| 63 |
+
:class:`torch.nn.UninitializedParameter` s that should not be accessed
|
| 64 |
+
or used, and afterward they contain regular :class:`torch.nn.Parameter` s.
|
| 65 |
+
Lazy modules are convenient since they don't require computing some
|
| 66 |
+
module arguments, like the :attr:`in_features` argument of a
|
| 67 |
+
typical :class:`torch.nn.Linear`.
|
| 68 |
+
|
| 69 |
+
After construction, networks with lazy modules should first
|
| 70 |
+
be converted to the desired dtype and placed on the expected device.
|
| 71 |
+
This is because lazy modules only perform shape inference so the usual dtype
|
| 72 |
+
and device placement behavior applies.
|
| 73 |
+
The lazy modules should then perform "dry runs" to initialize all the components in the module.
|
| 74 |
+
These "dry runs" send inputs of the correct size, dtype, and device through
|
| 75 |
+
the network and to each one of its lazy modules. After this the network can be used as usual.
|
| 76 |
+
|
| 77 |
+
>>> # xdoctest: +SKIP
|
| 78 |
+
>>> class LazyMLP(torch.nn.Module):
|
| 79 |
+
... def __init__(self) -> None:
|
| 80 |
+
... super().__init__()
|
| 81 |
+
... self.fc1 = torch.nn.LazyLinear(10)
|
| 82 |
+
... self.relu1 = torch.nn.ReLU()
|
| 83 |
+
... self.fc2 = torch.nn.LazyLinear(1)
|
| 84 |
+
... self.relu2 = torch.nn.ReLU()
|
| 85 |
+
...
|
| 86 |
+
... def forward(self, input):
|
| 87 |
+
... x = self.relu1(self.fc1(input))
|
| 88 |
+
... y = self.relu2(self.fc2(x))
|
| 89 |
+
... return y
|
| 90 |
+
>>> # constructs a network with lazy modules
|
| 91 |
+
>>> lazy_mlp = LazyMLP()
|
| 92 |
+
>>> # transforms the network's device and dtype
|
| 93 |
+
>>> # NOTE: these transforms can and should be applied after construction and before any 'dry runs'
|
| 94 |
+
>>> lazy_mlp = lazy_mlp.cuda()
|
| 95 |
+
>>> lazy_mlp
|
| 96 |
+
LazyMLP( (fc1): LazyLinear(in_features=0, out_features=10, bias=True)
|
| 97 |
+
(relu1): ReLU()
|
| 98 |
+
(fc2): LazyLinear(in_features=0, out_features=1, bias=True)
|
| 99 |
+
(relu2): ReLU()
|
| 100 |
+
)
|
| 101 |
+
>>> # performs a dry run to initialize the network's lazy modules
|
| 102 |
+
>>> lazy_mlp(torch.ones(10, 10).cuda())
|
| 103 |
+
>>> # after initialization, LazyLinear modules become regular Linear modules
|
| 104 |
+
>>> lazy_mlp
|
| 105 |
+
LazyMLP(
|
| 106 |
+
(fc1): Linear(in_features=10, out_features=10, bias=True)
|
| 107 |
+
(relu1): ReLU()
|
| 108 |
+
(fc2): Linear(in_features=10, out_features=1, bias=True)
|
| 109 |
+
(relu2): ReLU()
|
| 110 |
+
)
|
| 111 |
+
>>> # attaches an optimizer, since parameters can now be used as usual
|
| 112 |
+
>>> optim = torch.optim.SGD(lazy_mlp.parameters(), lr=0.01)
|
| 113 |
+
|
| 114 |
+
A final caveat when using lazy modules is that the order of initialization of a network's
|
| 115 |
+
parameters may change, since the lazy modules are always initialized after other modules.
|
| 116 |
+
For example, if the LazyMLP class defined above had a :class:`torch.nn.LazyLinear` module
|
| 117 |
+
first and then a regular :class:`torch.nn.Linear` second, the second module would be
|
| 118 |
+
initialized on construction and the first module would be initialized during the first dry run.
|
| 119 |
+
This can cause the parameters of a network using lazy modules to be initialized differently
|
| 120 |
+
than the parameters of a network without lazy modules as the order of parameter initializations,
|
| 121 |
+
which often depends on a stateful random number generator, is different.
|
| 122 |
+
Check :doc:`/notes/randomness` for more details.
|
| 123 |
+
|
| 124 |
+
Lazy modules can be serialized with a state dict like other modules. For example:
|
| 125 |
+
|
| 126 |
+
>>> lazy_mlp = LazyMLP()
|
| 127 |
+
>>> # The state dict shows the uninitialized parameters
|
| 128 |
+
>>> lazy_mlp.state_dict()
|
| 129 |
+
OrderedDict({'fc1.weight': <UninitializedParameter>,
|
| 130 |
+
'fc1.bias': <UninitializedParameter>,
|
| 131 |
+
'fc2.weight': <UninitializedParameter>,
|
| 132 |
+
'fc2.bias': <UninitializedParameter>})
|
| 133 |
+
|
| 134 |
+
Lazy modules can load regular :class:`torch.nn.Parameter` s (i.e. you can serialize/deserialize
|
| 135 |
+
initialized LazyModules and they will remain initialized)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
>>> full_mlp = LazyMLP()
|
| 139 |
+
>>> # Dry run to initialize another module
|
| 140 |
+
>>> full_mlp.forward(torch.ones(10, 1))
|
| 141 |
+
>>> # Load an initialized state into a lazy module
|
| 142 |
+
>>> lazy_mlp.load_state_dict(full_mlp.state_dict())
|
| 143 |
+
>>> # The state dict now holds valid values
|
| 144 |
+
>>> lazy_mlp.state_dict()
|
| 145 |
+
OrderedDict([('fc1.weight',
|
| 146 |
+
tensor([[-0.3837],
|
| 147 |
+
[ 0.0907],
|
| 148 |
+
[ 0.6708],
|
| 149 |
+
[-0.5223],
|
| 150 |
+
[-0.9028],
|
| 151 |
+
[ 0.2851],
|
| 152 |
+
[-0.4537],
|
| 153 |
+
[ 0.6813],
|
| 154 |
+
[ 0.5766],
|
| 155 |
+
[-0.8678]])),
|
| 156 |
+
('fc1.bias',
|
| 157 |
+
tensor([-1.8832e+25, 4.5636e-41, -1.8832e+25, 4.5636e-41, -6.1598e-30,
|
| 158 |
+
4.5637e-41, -1.8788e+22, 4.5636e-41, -2.0042e-31, 4.5637e-41])),
|
| 159 |
+
('fc2.weight',
|
| 160 |
+
tensor([[ 0.1320, 0.2938, 0.0679, 0.2793, 0.1088, -0.1795, -0.2301, 0.2807,
|
| 161 |
+
0.2479, 0.1091]])),
|
| 162 |
+
('fc2.bias', tensor([0.0019]))])
|
| 163 |
+
|
| 164 |
+
Note, however, that the loaded parameters will not be replaced when doing a "dry run" if they are initialized
|
| 165 |
+
when the state is loaded. This prevents using initialized modules in different contexts.
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
# modules inheriting from this will change their __class__ to the specified
|
| 169 |
+
# one after they are fully initialized
|
| 170 |
+
cls_to_become: type[Any] | None = None
|
| 171 |
+
|
| 172 |
+
def __init__(self: _LazyProtocol, *args, **kwargs):
|
| 173 |
+
# Mypy doesn't like this super call in a mixin
|
| 174 |
+
super().__init__(*args, **kwargs) # type: ignore[misc]
|
| 175 |
+
# pyrefly: ignore [read-only]
|
| 176 |
+
self._load_hook = self._register_load_state_dict_pre_hook(self._lazy_load_hook)
|
| 177 |
+
# pyrefly: ignore [read-only]
|
| 178 |
+
self._initialize_hook = self.register_forward_pre_hook(
|
| 179 |
+
self._infer_parameters, with_kwargs=True
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def _save_to_state_dict(self: _LazyProtocol, destination, prefix, keep_vars):
|
| 183 |
+
# This should be ideally implemented as a hook,
|
| 184 |
+
# but we should override `detach` in the UninitializedParameter to return itself
|
| 185 |
+
# which is not clean
|
| 186 |
+
for name, param in self._parameters.items():
|
| 187 |
+
if param is not None:
|
| 188 |
+
if not (is_lazy(param) or keep_vars):
|
| 189 |
+
param = param.detach()
|
| 190 |
+
destination[prefix + name] = param
|
| 191 |
+
for name, buf in self._buffers.items():
|
| 192 |
+
if buf is not None and name not in self._non_persistent_buffers_set:
|
| 193 |
+
if not (is_lazy(buf) or keep_vars):
|
| 194 |
+
buf = buf.detach()
|
| 195 |
+
destination[prefix + name] = buf
|
| 196 |
+
|
| 197 |
+
def _lazy_load_hook(
|
| 198 |
+
self: _LazyProtocol,
|
| 199 |
+
state_dict,
|
| 200 |
+
prefix,
|
| 201 |
+
local_metadata,
|
| 202 |
+
strict,
|
| 203 |
+
missing_keys,
|
| 204 |
+
unexpected_keys,
|
| 205 |
+
error_msgs,
|
| 206 |
+
):
|
| 207 |
+
"""load_state_dict pre-hook function for lazy buffers and parameters.
|
| 208 |
+
|
| 209 |
+
The purpose of this hook is to adjust the current state and/or
|
| 210 |
+
``state_dict`` being loaded so that a module instance serialized in
|
| 211 |
+
both un/initialized state can be deserialized onto both un/initialized
|
| 212 |
+
module instance.
|
| 213 |
+
See comment in ``torch.nn.Module._register_load_state_dict_pre_hook``
|
| 214 |
+
for the details of the hook specification.
|
| 215 |
+
"""
|
| 216 |
+
for name, param in itertools.chain(
|
| 217 |
+
self._parameters.items(), self._buffers.items()
|
| 218 |
+
):
|
| 219 |
+
key = prefix + name
|
| 220 |
+
if key in state_dict and param is not None:
|
| 221 |
+
input_param = state_dict[key]
|
| 222 |
+
if is_lazy(param):
|
| 223 |
+
# The current parameter is not initialized but the one being loaded is
|
| 224 |
+
# create a new parameter based on the uninitialized one
|
| 225 |
+
if not is_lazy(input_param):
|
| 226 |
+
with torch.no_grad():
|
| 227 |
+
param.materialize(input_param.shape)
|
| 228 |
+
|
| 229 |
+
def initialize_parameters(self: _LazyProtocol, *args, **kwargs):
|
| 230 |
+
r"""Initialize parameters according to the input batch properties.
|
| 231 |
+
|
| 232 |
+
This adds an interface to isolate parameter initialization from the
|
| 233 |
+
forward pass when doing parameter shape inference.
|
| 234 |
+
"""
|
| 235 |
+
raise NotImplementedError(
|
| 236 |
+
f"initialize_parameters is not implemented for {self.__class__.__name__}"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
def has_uninitialized_params(self: _LazyProtocol):
|
| 240 |
+
r"""Check if a module has parameters that are not initialized."""
|
| 241 |
+
# This is to avoid the JIT to track this parameter and force
|
| 242 |
+
# custom modules __setstate__ to add it
|
| 243 |
+
params = self._parameters.values()
|
| 244 |
+
buffers = self._buffers.values()
|
| 245 |
+
for param in itertools.chain(params, buffers):
|
| 246 |
+
if is_lazy(param):
|
| 247 |
+
return True
|
| 248 |
+
return False
|
| 249 |
+
|
| 250 |
+
# torchrec tests the code consistency with the following code
|
| 251 |
+
# fmt: off
|
| 252 |
+
def _infer_parameters(self: _LazyProtocol, module, args, kwargs=None):
|
| 253 |
+
r"""Infers the size and initializes the parameters according to the provided input batch.
|
| 254 |
+
|
| 255 |
+
Given a module that contains parameters that were declared inferable
|
| 256 |
+
using :class:`torch.nn.parameter.ParameterMode.Infer`, runs a forward pass
|
| 257 |
+
in the complete module using the provided input to initialize all the parameters
|
| 258 |
+
as needed.
|
| 259 |
+
The module is set into evaluation mode before running the forward pass in order
|
| 260 |
+
to avoid saving statistics or calculating gradients
|
| 261 |
+
"""
|
| 262 |
+
kwargs = kwargs if kwargs else {}
|
| 263 |
+
module.initialize_parameters(*args, **kwargs)
|
| 264 |
+
if module.has_uninitialized_params():
|
| 265 |
+
raise RuntimeError(f'module {self._get_name()} has not been fully initialized')
|
| 266 |
+
module._initialize_hook.remove()
|
| 267 |
+
module._load_hook.remove()
|
| 268 |
+
delattr(module, '_initialize_hook')
|
| 269 |
+
delattr(module, '_load_hook')
|
| 270 |
+
if module.cls_to_become is not None:
|
| 271 |
+
module.__class__ = module.cls_to_become
|
| 272 |
+
# fmt: on
|
| 273 |
+
|
| 274 |
+
def _replicate_for_data_parallel(self: _LazyProtocol):
|
| 275 |
+
raise RuntimeError(
|
| 276 |
+
"Modules with uninitialized parameters can't be used with `DataParallel`. "
|
| 277 |
+
"Run a dummy forward pass to correctly initialize the modules"
|
| 278 |
+
)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/linear.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import math
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch import Tensor
|
| 7 |
+
from torch.nn import functional as F, init
|
| 8 |
+
from torch.nn.parameter import Parameter, UninitializedParameter
|
| 9 |
+
|
| 10 |
+
from .lazy import LazyModuleMixin
|
| 11 |
+
from .module import Module
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"Bilinear",
|
| 16 |
+
"Identity",
|
| 17 |
+
"LazyLinear",
|
| 18 |
+
"Linear",
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Identity(Module):
|
| 23 |
+
r"""A placeholder identity operator that is argument-insensitive.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
args: any argument (unused)
|
| 27 |
+
kwargs: any keyword argument (unused)
|
| 28 |
+
|
| 29 |
+
Shape:
|
| 30 |
+
- Input: :math:`(*)`, where :math:`*` means any number of dimensions.
|
| 31 |
+
- Output: :math:`(*)`, same shape as the input.
|
| 32 |
+
|
| 33 |
+
Examples::
|
| 34 |
+
|
| 35 |
+
>>> m = nn.Identity(54, unused_argument1=0.1, unused_argument2=False)
|
| 36 |
+
>>> input = torch.randn(128, 20)
|
| 37 |
+
>>> output = m(input)
|
| 38 |
+
>>> print(output.size())
|
| 39 |
+
torch.Size([128, 20])
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 44 |
+
super().__init__()
|
| 45 |
+
|
| 46 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 47 |
+
"""
|
| 48 |
+
Runs the forward pass.
|
| 49 |
+
"""
|
| 50 |
+
return input
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class Linear(Module):
|
| 54 |
+
r"""Applies an affine linear transformation to the incoming data: :math:`y = xA^T + b`.
|
| 55 |
+
|
| 56 |
+
This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
|
| 57 |
+
|
| 58 |
+
On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
in_features: size of each input sample
|
| 62 |
+
out_features: size of each output sample
|
| 63 |
+
bias: If set to ``False``, the layer will not learn an additive bias.
|
| 64 |
+
Default: ``True``
|
| 65 |
+
|
| 66 |
+
Shape:
|
| 67 |
+
- Input: :math:`(*, H_\text{in})` where :math:`*` means any number of
|
| 68 |
+
dimensions including none and :math:`H_\text{in} = \text{in\_features}`.
|
| 69 |
+
- Output: :math:`(*, H_\text{out})` where all but the last dimension
|
| 70 |
+
are the same shape as the input and :math:`H_\text{out} = \text{out\_features}`.
|
| 71 |
+
|
| 72 |
+
Attributes:
|
| 73 |
+
weight: the learnable weights of the module of shape
|
| 74 |
+
:math:`(\text{out\_features}, \text{in\_features})`. The values are
|
| 75 |
+
initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
|
| 76 |
+
:math:`k = \frac{1}{\text{in\_features}}`
|
| 77 |
+
bias: the learnable bias of the module of shape :math:`(\text{out\_features})`.
|
| 78 |
+
If :attr:`bias` is ``True``, the values are initialized from
|
| 79 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 80 |
+
:math:`k = \frac{1}{\text{in\_features}}`
|
| 81 |
+
|
| 82 |
+
Examples::
|
| 83 |
+
|
| 84 |
+
>>> m = nn.Linear(20, 30)
|
| 85 |
+
>>> input = torch.randn(128, 20)
|
| 86 |
+
>>> output = m(input)
|
| 87 |
+
>>> print(output.size())
|
| 88 |
+
torch.Size([128, 30])
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
__constants__ = ["in_features", "out_features"]
|
| 92 |
+
in_features: int
|
| 93 |
+
out_features: int
|
| 94 |
+
weight: Tensor
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
in_features: int,
|
| 99 |
+
out_features: int,
|
| 100 |
+
bias: bool = True,
|
| 101 |
+
device=None,
|
| 102 |
+
dtype=None,
|
| 103 |
+
) -> None:
|
| 104 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 105 |
+
super().__init__()
|
| 106 |
+
self.in_features = in_features
|
| 107 |
+
self.out_features = out_features
|
| 108 |
+
self.weight = Parameter(
|
| 109 |
+
torch.empty((out_features, in_features), **factory_kwargs)
|
| 110 |
+
)
|
| 111 |
+
if bias:
|
| 112 |
+
self.bias = Parameter(torch.empty(out_features, **factory_kwargs))
|
| 113 |
+
else:
|
| 114 |
+
self.register_parameter("bias", None)
|
| 115 |
+
self.reset_parameters()
|
| 116 |
+
|
| 117 |
+
def reset_parameters(self) -> None:
|
| 118 |
+
"""
|
| 119 |
+
Resets parameters based on their initialization used in ``__init__``.
|
| 120 |
+
"""
|
| 121 |
+
# Setting a=sqrt(5) in kaiming_uniform is the same as initializing with
|
| 122 |
+
# uniform(-1/sqrt(in_features), 1/sqrt(in_features)). For details, see
|
| 123 |
+
# https://github.com/pytorch/pytorch/issues/57109
|
| 124 |
+
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
|
| 125 |
+
if self.bias is not None:
|
| 126 |
+
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
|
| 127 |
+
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
|
| 128 |
+
init.uniform_(self.bias, -bound, bound)
|
| 129 |
+
|
| 130 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 131 |
+
"""
|
| 132 |
+
Runs the forward pass.
|
| 133 |
+
"""
|
| 134 |
+
return F.linear(input, self.weight, self.bias)
|
| 135 |
+
|
| 136 |
+
def extra_repr(self) -> str:
|
| 137 |
+
"""
|
| 138 |
+
Return the extra representation of the module.
|
| 139 |
+
"""
|
| 140 |
+
return f"in_features={self.in_features}, out_features={self.out_features}, bias={self.bias is not None}"
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# This class exists solely to avoid triggering an obscure error when scripting
|
| 144 |
+
# an improperly quantized attention layer. See this issue for details:
|
| 145 |
+
# https://github.com/pytorch/pytorch/issues/58969
|
| 146 |
+
# TODO: fail fast on quantization API usage error, then remove this class
|
| 147 |
+
# and replace uses of it with plain Linear
|
| 148 |
+
class NonDynamicallyQuantizableLinear(Linear):
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
in_features: int,
|
| 152 |
+
out_features: int,
|
| 153 |
+
bias: bool = True,
|
| 154 |
+
device=None,
|
| 155 |
+
dtype=None,
|
| 156 |
+
) -> None:
|
| 157 |
+
super().__init__(
|
| 158 |
+
in_features, out_features, bias=bias, device=device, dtype=dtype
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class Bilinear(Module):
|
| 163 |
+
r"""Applies a bilinear transformation to the incoming data: :math:`y = x_1^T A x_2 + b`.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
in1_features: size of each first input sample, must be > 0
|
| 167 |
+
in2_features: size of each second input sample, must be > 0
|
| 168 |
+
out_features: size of each output sample, must be > 0
|
| 169 |
+
bias: If set to ``False``, the layer will not learn an additive bias.
|
| 170 |
+
Default: ``True``
|
| 171 |
+
|
| 172 |
+
Shape:
|
| 173 |
+
- Input1: :math:`(*, H_\text{in1})` where :math:`H_\text{in1}=\text{in1\_features}` and
|
| 174 |
+
:math:`*` means any number of additional dimensions including none. All but the last dimension
|
| 175 |
+
of the inputs should be the same.
|
| 176 |
+
- Input2: :math:`(*, H_\text{in2})` where :math:`H_\text{in2}=\text{in2\_features}`.
|
| 177 |
+
- Output: :math:`(*, H_\text{out})` where :math:`H_\text{out}=\text{out\_features}`
|
| 178 |
+
and all but the last dimension are the same shape as the input.
|
| 179 |
+
|
| 180 |
+
Attributes:
|
| 181 |
+
weight: the learnable weights of the module of shape
|
| 182 |
+
:math:`(\text{out\_features}, \text{in1\_features}, \text{in2\_features})`.
|
| 183 |
+
The values are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
|
| 184 |
+
:math:`k = \frac{1}{\text{in1\_features}}`
|
| 185 |
+
bias: the learnable bias of the module of shape :math:`(\text{out\_features})`.
|
| 186 |
+
If :attr:`bias` is ``True``, the values are initialized from
|
| 187 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
|
| 188 |
+
:math:`k = \frac{1}{\text{in1\_features}}`
|
| 189 |
+
|
| 190 |
+
Examples::
|
| 191 |
+
|
| 192 |
+
>>> m = nn.Bilinear(20, 30, 40)
|
| 193 |
+
>>> input1 = torch.randn(128, 20)
|
| 194 |
+
>>> input2 = torch.randn(128, 30)
|
| 195 |
+
>>> output = m(input1, input2)
|
| 196 |
+
>>> print(output.size())
|
| 197 |
+
torch.Size([128, 40])
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
__constants__ = ["in1_features", "in2_features", "out_features"]
|
| 201 |
+
in1_features: int
|
| 202 |
+
in2_features: int
|
| 203 |
+
out_features: int
|
| 204 |
+
weight: Tensor
|
| 205 |
+
|
| 206 |
+
def __init__(
|
| 207 |
+
self,
|
| 208 |
+
in1_features: int,
|
| 209 |
+
in2_features: int,
|
| 210 |
+
out_features: int,
|
| 211 |
+
bias: bool = True,
|
| 212 |
+
device=None,
|
| 213 |
+
dtype=None,
|
| 214 |
+
) -> None:
|
| 215 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 216 |
+
super().__init__()
|
| 217 |
+
self.in1_features = in1_features
|
| 218 |
+
self.in2_features = in2_features
|
| 219 |
+
self.out_features = out_features
|
| 220 |
+
self.weight = Parameter(
|
| 221 |
+
torch.empty((out_features, in1_features, in2_features), **factory_kwargs)
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
if bias:
|
| 225 |
+
self.bias = Parameter(torch.empty(out_features, **factory_kwargs))
|
| 226 |
+
else:
|
| 227 |
+
self.register_parameter("bias", None)
|
| 228 |
+
self.reset_parameters()
|
| 229 |
+
|
| 230 |
+
def reset_parameters(self) -> None:
|
| 231 |
+
"""
|
| 232 |
+
Resets parameters based on their initialization used in ``__init__``.
|
| 233 |
+
"""
|
| 234 |
+
if self.in1_features <= 0:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
f"in1_features must be > 0, but got (in1_features={self.in1_features})"
|
| 237 |
+
)
|
| 238 |
+
bound = 1 / math.sqrt(self.weight.size(1))
|
| 239 |
+
init.uniform_(self.weight, -bound, bound)
|
| 240 |
+
if self.bias is not None:
|
| 241 |
+
init.uniform_(self.bias, -bound, bound)
|
| 242 |
+
|
| 243 |
+
def forward(self, input1: Tensor, input2: Tensor) -> Tensor:
|
| 244 |
+
"""
|
| 245 |
+
Runs the forward pass.
|
| 246 |
+
"""
|
| 247 |
+
return F.bilinear(input1, input2, self.weight, self.bias)
|
| 248 |
+
|
| 249 |
+
def extra_repr(self) -> str:
|
| 250 |
+
"""
|
| 251 |
+
Return the extra representation of the module.
|
| 252 |
+
"""
|
| 253 |
+
return (
|
| 254 |
+
f"in1_features={self.in1_features}, in2_features={self.in2_features}, "
|
| 255 |
+
f"out_features={self.out_features}, bias={self.bias is not None}"
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class LazyLinear(LazyModuleMixin, Linear):
|
| 260 |
+
r"""A :class:`torch.nn.Linear` module where `in_features` is inferred.
|
| 261 |
+
|
| 262 |
+
In this module, the `weight` and `bias` are of :class:`torch.nn.UninitializedParameter`
|
| 263 |
+
class. They will be initialized after the first call to ``forward`` is done and the
|
| 264 |
+
module will become a regular :class:`torch.nn.Linear` module. The ``in_features`` argument
|
| 265 |
+
of the :class:`Linear` is inferred from the ``input.shape[-1]``.
|
| 266 |
+
|
| 267 |
+
Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
|
| 268 |
+
on lazy modules and their limitations.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
out_features: size of each output sample
|
| 272 |
+
bias: If set to ``False``, the layer will not learn an additive bias.
|
| 273 |
+
Default: ``True``
|
| 274 |
+
|
| 275 |
+
Attributes:
|
| 276 |
+
weight: the learnable weights of the module of shape
|
| 277 |
+
:math:`(\text{out\_features}, \text{in\_features})`. The values are
|
| 278 |
+
initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where
|
| 279 |
+
:math:`k = \frac{1}{\text{in\_features}}`
|
| 280 |
+
bias: the learnable bias of the module of shape :math:`(\text{out\_features})`.
|
| 281 |
+
If :attr:`bias` is ``True``, the values are initialized from
|
| 282 |
+
:math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
|
| 283 |
+
:math:`k = \frac{1}{\text{in\_features}}`
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
cls_to_become = Linear # type: ignore[assignment]
|
| 289 |
+
# pyrefly: ignore [bad-override]
|
| 290 |
+
weight: UninitializedParameter
|
| 291 |
+
bias: UninitializedParameter # type: ignore[assignment]
|
| 292 |
+
|
| 293 |
+
def __init__(
|
| 294 |
+
self, out_features: int, bias: bool = True, device=None, dtype=None
|
| 295 |
+
) -> None:
|
| 296 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 297 |
+
# bias is hardcoded to False to avoid creating tensor
|
| 298 |
+
# that will soon be overwritten.
|
| 299 |
+
# pyrefly: ignore [bad-argument-type]
|
| 300 |
+
super().__init__(0, 0, False)
|
| 301 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 302 |
+
self.weight = UninitializedParameter(**factory_kwargs)
|
| 303 |
+
self.out_features = out_features
|
| 304 |
+
if bias:
|
| 305 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 306 |
+
self.bias = UninitializedParameter(**factory_kwargs)
|
| 307 |
+
|
| 308 |
+
def reset_parameters(self) -> None:
|
| 309 |
+
"""
|
| 310 |
+
Resets parameters based on their initialization used in ``__init__``.
|
| 311 |
+
"""
|
| 312 |
+
# pyrefly: ignore [bad-argument-type]
|
| 313 |
+
if not self.has_uninitialized_params() and self.in_features != 0:
|
| 314 |
+
super().reset_parameters()
|
| 315 |
+
|
| 316 |
+
def initialize_parameters(self, input) -> None: # type: ignore[override]
|
| 317 |
+
"""
|
| 318 |
+
Infers ``in_features`` based on ``input`` and initializes parameters.
|
| 319 |
+
"""
|
| 320 |
+
# pyrefly: ignore [bad-argument-type]
|
| 321 |
+
if self.has_uninitialized_params():
|
| 322 |
+
with torch.no_grad():
|
| 323 |
+
self.in_features = input.shape[-1]
|
| 324 |
+
self.weight.materialize((self.out_features, self.in_features))
|
| 325 |
+
if self.bias is not None:
|
| 326 |
+
self.bias.materialize((self.out_features,))
|
| 327 |
+
self.reset_parameters()
|
| 328 |
+
if self.in_features == 0:
|
| 329 |
+
if input.shape[-1] != self.weight.shape[-1]:
|
| 330 |
+
raise AssertionError(
|
| 331 |
+
f"The in_features inferred from input: {input.shape[-1]} "
|
| 332 |
+
f"is not equal to in_features from self.weight: "
|
| 333 |
+
f"{self.weight.shape[-1]}"
|
| 334 |
+
)
|
| 335 |
+
self.in_features = input.shape[-1]
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# TODO: PartialLinear - maybe in sparse?
|
.venv/lib/python3.12/site-packages/torch/nn/modules/linear_cross_entropy.py
ADDED
|
@@ -0,0 +1,1480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from functools import cached_property
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = []
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _make_empty(shape, dtype, device, when=True):
|
| 11 |
+
# when=False returns a rank-matching empty (shape (0,)*len(shape)).
|
| 12 |
+
return torch.empty(
|
| 13 |
+
shape if when else (0,) * len(shape),
|
| 14 |
+
device=device,
|
| 15 |
+
dtype=dtype,
|
| 16 |
+
requires_grad=False,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _make_zeros(shape, dtype, device, when=True):
|
| 21 |
+
return torch.zeros(
|
| 22 |
+
shape if when else (0,) * len(shape),
|
| 23 |
+
device=device,
|
| 24 |
+
dtype=dtype,
|
| 25 |
+
requires_grad=False,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _linear_cross_entropy_batch_chunked_setup_context(ctx, inputs, output):
|
| 30 |
+
(
|
| 31 |
+
*_,
|
| 32 |
+
allow_retain_graph,
|
| 33 |
+
compute_input_grad,
|
| 34 |
+
compute_linear_weight_grad,
|
| 35 |
+
compute_linear_bias_grad,
|
| 36 |
+
) = inputs
|
| 37 |
+
# Without this, backward through the loss materializes zero-filled
|
| 38 |
+
# gradients for the three unused grad outputs -- (N, F) + (C, F) + (C,)
|
| 39 |
+
# at input dtype -- silently adding an input+weight-sized transient to
|
| 40 |
+
# every backward peak. The backward only consumes the loss gradient.
|
| 41 |
+
ctx.set_materialize_grads(False)
|
| 42 |
+
ctx.allow_retain_graph = allow_retain_graph
|
| 43 |
+
ctx.compute_input_grad = compute_input_grad
|
| 44 |
+
ctx.compute_linear_weight_grad = compute_linear_weight_grad
|
| 45 |
+
ctx.compute_linear_bias_grad = compute_linear_bias_grad
|
| 46 |
+
_, grad_input, grad_linear_weight, grad_linear_bias = output
|
| 47 |
+
# ``.detach()`` the stashed grads: they are forward OUTPUTS, so they
|
| 48 |
+
# carry ``grad_fn`` back to this custom-op node. Holding them as raw
|
| 49 |
+
# ctx attributes would form a reference cycle (node -> ctx -> grad ->
|
| 50 |
+
# grad_fn -> node) that refcounting can't break, leaking the tensors
|
| 51 |
+
# until a GC pass -- which the CUDA mem-leak check flags. Detaching
|
| 52 |
+
# drops the grad_fn link so the tensors free promptly when the loss's
|
| 53 |
+
# graph is. Backward only multiplies them by the upstream grad, so the
|
| 54 |
+
# lost autograd history is irrelevant (double-backward is unsupported).
|
| 55 |
+
ctx._gi = grad_input.detach() if compute_input_grad else None
|
| 56 |
+
ctx._gw = grad_linear_weight.detach() if compute_linear_weight_grad else None
|
| 57 |
+
ctx._gb = grad_linear_bias.detach() if compute_linear_bias_grad else None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@dataclasses.dataclass
|
| 61 |
+
class _ChunkViews:
|
| 62 |
+
"""Per-iteration tensor views; each property picks the right operand
|
| 63 |
+
or scratch from ctx dispatch flags so call sites read raw.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
ctx: "_ChunkContext"
|
| 67 |
+
bchunk_start: int
|
| 68 |
+
bchunk_size: int
|
| 69 |
+
input_chunk: torch.Tensor
|
| 70 |
+
target_chunk: torch.Tensor
|
| 71 |
+
weight_chunk: torch.Tensor | None # None on the prob path (see prob_wt)
|
| 72 |
+
logits: torch.Tensor
|
| 73 |
+
input_chunk_acc: torch.Tensor
|
| 74 |
+
|
| 75 |
+
@cached_property
|
| 76 |
+
def prob_wt(self) -> torch.Tensor:
|
| 77 |
+
# Prob path: (B, V) weight*target at the logits dtype -- the dense
|
| 78 |
+
# analogue of the index path's per-row ``weight_chunk``. A view of
|
| 79 |
+
# ``target_chunk`` when no scratch is needed.
|
| 80 |
+
ctx = self.ctx
|
| 81 |
+
if not ctx.alloc_prob_target_buf:
|
| 82 |
+
return self.target_chunk
|
| 83 |
+
out = ctx.prob_target_buf.narrow(0, 0, self.bchunk_size)
|
| 84 |
+
if ctx.weight_row is not None:
|
| 85 |
+
torch.mul(self.target_chunk, ctx.weight_row, out=out)
|
| 86 |
+
else:
|
| 87 |
+
out.copy_(self.target_chunk)
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def input(self) -> torch.Tensor:
|
| 92 |
+
return (
|
| 93 |
+
self.input_chunk_acc
|
| 94 |
+
if self.ctx.forward_uses_acc_input
|
| 95 |
+
else self.input_chunk
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def linear_weight(self) -> torch.Tensor:
|
| 100 |
+
ctx = self.ctx
|
| 101 |
+
return (
|
| 102 |
+
ctx.linear_weight
|
| 103 |
+
if ctx.forward_uses_cuda_out_dtype
|
| 104 |
+
else ctx.linear_weight_cast
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def input_grad_logits(self) -> torch.Tensor:
|
| 109 |
+
if self.ctx.input_grad_uses_logits_lw:
|
| 110 |
+
return self.logits_downcast
|
| 111 |
+
return self.logits
|
| 112 |
+
|
| 113 |
+
@property
|
| 114 |
+
def input_grad_linear_weight(self) -> torch.Tensor:
|
| 115 |
+
ctx = self.ctx
|
| 116 |
+
return (
|
| 117 |
+
ctx.linear_weight
|
| 118 |
+
if ctx.input_grad_uses_logits_lw
|
| 119 |
+
else ctx.linear_weight_cast
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def weight_grad_input(self) -> torch.Tensor:
|
| 124 |
+
ctx = self.ctx
|
| 125 |
+
if ctx.is_cuda and not ctx.weight_grad_mm_same_dtype:
|
| 126 |
+
return self.input_chunk
|
| 127 |
+
return self.input_chunk_acc
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def logits_upcast(self) -> torch.Tensor:
|
| 131 |
+
# Non-CUDA mixed-dtype: copy into logits_acc_buf for matching-dtype mm.
|
| 132 |
+
ctx = self.ctx
|
| 133 |
+
if ctx.is_cuda or ctx.weight_grad_mm_same_dtype:
|
| 134 |
+
return self.logits
|
| 135 |
+
return ctx.logits_acc_buf.narrow(0, 0, self.bchunk_size).copy_(self.logits)
|
| 136 |
+
|
| 137 |
+
@cached_property
|
| 138 |
+
def grad_input_chunk(self) -> torch.Tensor:
|
| 139 |
+
# Buf-and-copy commit happens in ctx.chunks() post-yield.
|
| 140 |
+
ctx = self.ctx
|
| 141 |
+
if ctx.alloc_input_grad_acc_buf:
|
| 142 |
+
return ctx.input_grad_acc_buf.narrow(0, 0, self.bchunk_size)
|
| 143 |
+
return ctx.grad_input.narrow(0, self.bchunk_start, self.bchunk_size)
|
| 144 |
+
|
| 145 |
+
@cached_property
|
| 146 |
+
def bias_grad_acc(self) -> torch.Tensor:
|
| 147 |
+
# ``ctx.linear_bias_grad_chunk`` is an acc_dtype scratch that
|
| 148 |
+
# accumulates the per-chunk sum + index_add at acc precision,
|
| 149 |
+
# then commits to ``grad_linear_bias`` (input dtype) via the
|
| 150 |
+
# ``ctx.chunks()`` post-yield hook -- mirrors
|
| 151 |
+
# ``weight_grad_chunk``'s bulk-+-correction pattern for
|
| 152 |
+
# ``grad_linear_weight``. On the non-acc path, accumulation
|
| 153 |
+
# goes directly into ``grad_linear_bias`` (no commit, no
|
| 154 |
+
# post-yield action).
|
| 155 |
+
ctx = self.ctx
|
| 156 |
+
if ctx.alloc_linear_bias_grad_chunk:
|
| 157 |
+
return ctx.linear_bias_grad_chunk
|
| 158 |
+
return ctx.grad_linear_bias
|
| 159 |
+
|
| 160 |
+
@cached_property
|
| 161 |
+
def logits_downcast(self) -> torch.Tensor:
|
| 162 |
+
# Lazy: first access must come AFTER in-place mods to self.logits.
|
| 163 |
+
ctx = self.ctx
|
| 164 |
+
if ctx.loop_caches_logits_downcast:
|
| 165 |
+
return self.logits.to(ctx.linear_weight.dtype)
|
| 166 |
+
return self.logits
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@dataclasses.dataclass
|
| 170 |
+
class _ChunkContext:
|
| 171 |
+
"""Per-call state for the chunked loop, built once via ``build``.
|
| 172 |
+
Methods hide dtype/device/acc_policy dispatch behind single math ops;
|
| 173 |
+
dispatch-free per-iter math is inlined into the loop body. Buffers
|
| 174 |
+
dispatch decided are not needed are rank-matching empty tensors
|
| 175 |
+
(``when=False`` in ``_make_*``) so the dataclass surface stays uniform.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
dtype: torch.dtype
|
| 179 |
+
num_batches: int
|
| 180 |
+
in_features: int
|
| 181 |
+
num_classes: int
|
| 182 |
+
is_cuda: bool
|
| 183 |
+
use_acc_dtype: bool
|
| 184 |
+
|
| 185 |
+
acc_dtype: torch.dtype
|
| 186 |
+
weight_chunk_dtype: torch.dtype
|
| 187 |
+
grad_input_dtype: torch.dtype
|
| 188 |
+
linear_weight_cast_dtype: torch.dtype
|
| 189 |
+
|
| 190 |
+
input: torch.Tensor
|
| 191 |
+
target: torch.Tensor # uncorrected; per-iter slice is from corrected_target
|
| 192 |
+
weight: torch.Tensor | None
|
| 193 |
+
ignore_index: int
|
| 194 |
+
reduction: str
|
| 195 |
+
# Probability (soft-label) target: ``target`` is a floating ``(N, V)``
|
| 196 |
+
# tensor of per-class probabilities. ``loss_scale`` is the positive
|
| 197 |
+
# scalar reduction factor (1/N for "mean" -- the prob-target mean
|
| 198 |
+
# divisor is the row count, not the weight mass -- and 1 for "sum").
|
| 199 |
+
is_prob_target: bool
|
| 200 |
+
loss_scale: float
|
| 201 |
+
linear_weight: torch.Tensor
|
| 202 |
+
linear_bias: torch.Tensor | None
|
| 203 |
+
# reduction='none' backward only: per-sample upstream grad (N,). When
|
| 204 |
+
# set, neg_weight_target folds it in so the shared grad loop produces
|
| 205 |
+
# the grad_output-weighted VJP. None on every other path.
|
| 206 |
+
loss_grad_output: torch.Tensor | None
|
| 207 |
+
|
| 208 |
+
# The optional "when=" buffers (weight_grad_chunk, logits_acc_buf,
|
| 209 |
+
# input_grad_acc_buf, input_chunk_acc_buf, grad_input,
|
| 210 |
+
# grad_linear_weight, grad_linear_bias) are cached_properties below.
|
| 211 |
+
logits_buf: torch.Tensor
|
| 212 |
+
tmp: torch.Tensor
|
| 213 |
+
output: torch.Tensor
|
| 214 |
+
|
| 215 |
+
compute_input_grad: bool
|
| 216 |
+
compute_linear_weight_grad: bool
|
| 217 |
+
compute_linear_bias_grad: bool
|
| 218 |
+
alloc_prob_target_buf: bool
|
| 219 |
+
alloc_weight_grad_chunk: bool
|
| 220 |
+
alloc_linear_bias_grad_chunk: bool
|
| 221 |
+
alloc_input_grad_acc_buf: bool
|
| 222 |
+
alloc_input_chunk_acc_buf: bool
|
| 223 |
+
alloc_logits_acc_buf: bool
|
| 224 |
+
forward_uses_acc_input: bool
|
| 225 |
+
forward_uses_cuda_out_dtype: bool
|
| 226 |
+
weight_grad_mm_same_dtype: bool
|
| 227 |
+
input_grad_uses_logits_lw: bool
|
| 228 |
+
loop_caches_logits_downcast: bool
|
| 229 |
+
weight_grad_uses_logits_buf_temp: bool
|
| 230 |
+
|
| 231 |
+
@cached_property
|
| 232 |
+
def _mask(self) -> torch.Tensor:
|
| 233 |
+
return self.target == self.ignore_index
|
| 234 |
+
|
| 235 |
+
@cached_property
|
| 236 |
+
def corrected_target(self) -> torch.Tensor:
|
| 237 |
+
# Replace out-of-range ignore_index values with 0 lazily so
|
| 238 |
+
# downstream index_select / index_add_ stay in bounds.
|
| 239 |
+
if self.is_prob_target:
|
| 240 |
+
# ignore_index does not apply to probability targets.
|
| 241 |
+
return self.target
|
| 242 |
+
if self.ignore_index < 0 or self.ignore_index >= self.num_classes:
|
| 243 |
+
return torch.where(self._mask, 0, self.target)
|
| 244 |
+
return self.target
|
| 245 |
+
|
| 246 |
+
@cached_property
|
| 247 |
+
def neg_weight_target(self) -> torch.Tensor:
|
| 248 |
+
# Per-row weighting: -(weight[target] if weight else 1) / d on
|
| 249 |
+
# unmasked positions, 0 on masked positions. d = sum of unmasked
|
| 250 |
+
# weights for "mean", 1 for "sum".
|
| 251 |
+
mask = self._mask
|
| 252 |
+
target = self.corrected_target
|
| 253 |
+
weight = self.weight
|
| 254 |
+
weight_chunk_dtype = self.weight_chunk_dtype
|
| 255 |
+
if weight is None:
|
| 256 |
+
neg_weight_target = (~mask).to(weight_chunk_dtype)
|
| 257 |
+
elif target.numel() > weight.numel():
|
| 258 |
+
neg_weight_target = torch.where(
|
| 259 |
+
mask, 0, weight.to(weight_chunk_dtype).index_select(0, target)
|
| 260 |
+
)
|
| 261 |
+
else:
|
| 262 |
+
neg_weight_target = torch.where(
|
| 263 |
+
mask, 0, weight.index_select(0, target).to(weight_chunk_dtype)
|
| 264 |
+
)
|
| 265 |
+
if self.reduction == "mean":
|
| 266 |
+
d = neg_weight_target.sum()
|
| 267 |
+
neg_weight_target.div_(torch.where(d == 0, torch.nan, -d))
|
| 268 |
+
elif self.reduction == "sum":
|
| 269 |
+
neg_weight_target.neg_()
|
| 270 |
+
else: # "none"
|
| 271 |
+
# Forward (loss_grad_output is None) intentionally leaves the
|
| 272 |
+
# bare +W[T] unsigned: the loss-only branch needs the positive
|
| 273 |
+
# per-row loss weight. Only the backward (upstream grad set)
|
| 274 |
+
# negates and folds in grad_output[n] for the VJP -- do NOT add
|
| 275 |
+
# a .neg_() here to mirror the "sum" case.
|
| 276 |
+
if self.loss_grad_output is not None:
|
| 277 |
+
neg_weight_target.neg_().mul_(
|
| 278 |
+
self.loss_grad_output.to(neg_weight_target.dtype)
|
| 279 |
+
)
|
| 280 |
+
return neg_weight_target
|
| 281 |
+
|
| 282 |
+
@cached_property
|
| 283 |
+
def linear_weight_cast(self) -> torch.Tensor:
|
| 284 |
+
if self.linear_weight_cast_dtype != self.dtype:
|
| 285 |
+
return self.linear_weight.to(self.linear_weight_cast_dtype)
|
| 286 |
+
return self.linear_weight
|
| 287 |
+
|
| 288 |
+
@cached_property
|
| 289 |
+
def weight_row(self) -> torch.Tensor | None:
|
| 290 |
+
# (1, V) class-weight row at the logits dtype, broadcast against
|
| 291 |
+
# each (B, V) target chunk on the prob path. None when no class
|
| 292 |
+
# weight was passed.
|
| 293 |
+
if self.weight is None:
|
| 294 |
+
return None
|
| 295 |
+
weight = self.weight
|
| 296 |
+
if weight.dtype != self.logits_buf.dtype:
|
| 297 |
+
weight = weight.to(self.logits_buf.dtype)
|
| 298 |
+
return weight.unsqueeze(0)
|
| 299 |
+
|
| 300 |
+
@cached_property
|
| 301 |
+
def prob_target_buf(self) -> torch.Tensor:
|
| 302 |
+
# (B, V) scratch at the logits dtype holding weight*target per
|
| 303 |
+
# chunk on the prob path; rank-empty when target_chunk is usable
|
| 304 |
+
# directly (no class weight, matching dtype).
|
| 305 |
+
return _make_empty(
|
| 306 |
+
self.logits_buf.shape,
|
| 307 |
+
self.logits_buf.dtype,
|
| 308 |
+
self.input.device,
|
| 309 |
+
when=self.alloc_prob_target_buf,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
@cached_property
|
| 313 |
+
def linear_bias_cast(self) -> torch.Tensor | None:
|
| 314 |
+
# ``linear_bias`` is added to per-chunk logits, so its dtype
|
| 315 |
+
# must match the logits buffer (which may be acc_dtype on the
|
| 316 |
+
# upcast path). ``None`` when the user passed no bias -- the
|
| 317 |
+
# loop skips the add.
|
| 318 |
+
if self.linear_bias is None:
|
| 319 |
+
return None
|
| 320 |
+
if self.linear_bias.dtype != self.logits_buf.dtype:
|
| 321 |
+
return self.linear_bias.to(self.logits_buf.dtype)
|
| 322 |
+
return self.linear_bias
|
| 323 |
+
|
| 324 |
+
@cached_property
|
| 325 |
+
def weight_grad_chunk(self) -> torch.Tensor:
|
| 326 |
+
# (V, F) acc_dtype accumulator for keep-path weight-grad mm;
|
| 327 |
+
# rank-empty on the direct (compact) path.
|
| 328 |
+
return _make_empty(
|
| 329 |
+
(self.num_classes, self.in_features),
|
| 330 |
+
self.acc_dtype,
|
| 331 |
+
self.input.device,
|
| 332 |
+
when=self.alloc_weight_grad_chunk,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@cached_property
|
| 336 |
+
def logits_acc_buf(self) -> torch.Tensor:
|
| 337 |
+
# (B, V) scratch for non-CUDA mixed-dtype logits_upcast.
|
| 338 |
+
return _make_empty(
|
| 339 |
+
(self.logits_buf.shape[0], self.num_classes),
|
| 340 |
+
self.acc_dtype,
|
| 341 |
+
self.input.device,
|
| 342 |
+
when=self.alloc_logits_acc_buf,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
@cached_property
|
| 346 |
+
def input_grad_acc_buf(self) -> torch.Tensor:
|
| 347 |
+
# (B, F) scratch for input-grad addmm on the buf-and-copy path
|
| 348 |
+
# (CPU mixed-dtype, MPS).
|
| 349 |
+
return _make_empty(
|
| 350 |
+
(self.logits_buf.shape[0], self.in_features),
|
| 351 |
+
self.linear_weight_cast_dtype,
|
| 352 |
+
self.input.device,
|
| 353 |
+
when=self.alloc_input_grad_acc_buf,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
@cached_property
|
| 357 |
+
def input_chunk_acc_buf(self) -> torch.Tensor:
|
| 358 |
+
return _make_empty(
|
| 359 |
+
(self.logits_buf.shape[0], self.in_features),
|
| 360 |
+
self.acc_dtype,
|
| 361 |
+
self.input.device,
|
| 362 |
+
when=self.alloc_input_chunk_acc_buf,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
@cached_property
|
| 366 |
+
def grad_input(self) -> torch.Tensor:
|
| 367 |
+
return _make_empty(
|
| 368 |
+
self.input.shape,
|
| 369 |
+
self.grad_input_dtype,
|
| 370 |
+
self.input.device,
|
| 371 |
+
when=self.compute_input_grad,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
@cached_property
|
| 375 |
+
def grad_linear_weight(self) -> torch.Tensor:
|
| 376 |
+
return _make_zeros(
|
| 377 |
+
self.linear_weight.shape,
|
| 378 |
+
self.dtype,
|
| 379 |
+
self.input.device,
|
| 380 |
+
when=self.compute_linear_weight_grad,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
@cached_property
|
| 384 |
+
def grad_linear_bias(self) -> torch.Tensor:
|
| 385 |
+
# Same shape invariant as ``linear_bias``:
|
| 386 |
+
# ``linear_bias.shape == linear_weight.shape[:-1]``. Final
|
| 387 |
+
# accumulator in input dtype to match ``grad_linear_weight``.
|
| 388 |
+
return _make_zeros(
|
| 389 |
+
self.linear_weight.shape[:-1],
|
| 390 |
+
self.dtype,
|
| 391 |
+
self.input.device,
|
| 392 |
+
when=self.compute_linear_bias_grad,
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
@cached_property
|
| 396 |
+
def linear_bias_grad_chunk(self) -> torch.Tensor:
|
| 397 |
+
# ``linear_weight.shape[:-1]`` acc_dtype per-chunk scratch,
|
| 398 |
+
# mirroring ``weight_grad_chunk``'s role for
|
| 399 |
+
# ``grad_linear_weight``: the sub_ + index_add_ pair
|
| 400 |
+
# accumulates per-chunk in acc_dtype, then a single downcast
|
| 401 |
+
# commit (in ``chunks()`` post-yield) lands in
|
| 402 |
+
# ``grad_linear_bias``. ``_make_zeros`` so the first chunk's
|
| 403 |
+
# accumulators start at zero; the post-yield hook zeroes it
|
| 404 |
+
# again for subsequent chunks.
|
| 405 |
+
return _make_zeros(
|
| 406 |
+
self.linear_weight.shape[:-1],
|
| 407 |
+
self.acc_dtype,
|
| 408 |
+
self.input.device,
|
| 409 |
+
when=self.alloc_linear_bias_grad_chunk,
|
| 410 |
+
)
|
| 411 |
+
|
| 412 |
+
@classmethod
|
| 413 |
+
def build(
|
| 414 |
+
cls,
|
| 415 |
+
input: torch.Tensor,
|
| 416 |
+
linear_weight: torch.Tensor,
|
| 417 |
+
target: torch.Tensor,
|
| 418 |
+
linear_bias: torch.Tensor | None,
|
| 419 |
+
weight: torch.Tensor | None,
|
| 420 |
+
reduction: str,
|
| 421 |
+
ignore_index: int,
|
| 422 |
+
label_smoothing: float,
|
| 423 |
+
batch_chunk_size: int,
|
| 424 |
+
acc_policy: str,
|
| 425 |
+
acc_dtype: torch.dtype,
|
| 426 |
+
compute_input_grad: bool,
|
| 427 |
+
compute_linear_weight_grad: bool,
|
| 428 |
+
compute_linear_bias_grad: bool,
|
| 429 |
+
loss_grad_output: torch.Tensor | None = None,
|
| 430 |
+
) -> "_ChunkContext":
|
| 431 |
+
# ===== Validation =====
|
| 432 |
+
is_prob_target = target.dtype.is_floating_point
|
| 433 |
+
if is_prob_target:
|
| 434 |
+
if target.dtype != input.dtype:
|
| 435 |
+
raise TypeError(
|
| 436 |
+
"linear_cross_entropy: probability target dtype must match"
|
| 437 |
+
f" input dtype {input.dtype}, got {target.dtype}."
|
| 438 |
+
)
|
| 439 |
+
if target.shape != (input.shape[0], linear_weight.shape[0]):
|
| 440 |
+
raise RuntimeError(
|
| 441 |
+
"linear_cross_entropy: probability target shape must be "
|
| 442 |
+
f"{(input.shape[0], linear_weight.shape[0])}, got {tuple(target.shape)}."
|
| 443 |
+
)
|
| 444 |
+
if reduction not in {"mean", "sum"}:
|
| 445 |
+
raise NotImplementedError(
|
| 446 |
+
"linear_cross_entropy: probability target requires"
|
| 447 |
+
f" reduction in {{'mean', 'sum'}}, got {reduction!r}"
|
| 448 |
+
)
|
| 449 |
+
elif target.dtype != torch.int64:
|
| 450 |
+
raise TypeError(
|
| 451 |
+
f"linear_cross_entropy: target dtype must be torch.int64, got {target.dtype}."
|
| 452 |
+
)
|
| 453 |
+
if label_smoothing > 0.0:
|
| 454 |
+
raise NotImplementedError(
|
| 455 |
+
"linear_cross_entropy does not support label smoothing"
|
| 456 |
+
)
|
| 457 |
+
if reduction not in {"mean", "sum", "none"}:
|
| 458 |
+
raise NotImplementedError(
|
| 459 |
+
f"linear_cross_entropy does not support {reduction=}"
|
| 460 |
+
)
|
| 461 |
+
if linear_bias is not None and linear_bias.shape != linear_weight.shape[:-1]:
|
| 462 |
+
raise RuntimeError(
|
| 463 |
+
"linear_cross_entropy: expected linear_bias shape "
|
| 464 |
+
f"{tuple(linear_weight.shape[:-1])}, got {tuple(linear_bias.shape)}."
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
device = input.device
|
| 468 |
+
dtype = input.dtype
|
| 469 |
+
num_batches, in_features = input.shape
|
| 470 |
+
num_classes, _ = linear_weight.shape
|
| 471 |
+
# CUDA gates the out_dtype= mm fast path; the non-CUDA path
|
| 472 |
+
# (CPU, MPS, XPU, ...) routes mixed-dtype mm through explicit
|
| 473 |
+
# casts until out_dtype= is validated on those backends.
|
| 474 |
+
is_cuda = device.type == "cuda"
|
| 475 |
+
is_mps = device.type == "mps"
|
| 476 |
+
|
| 477 |
+
if dtype != acc_dtype and not (
|
| 478 |
+
dtype in {torch.float16, torch.bfloat16} and acc_dtype == torch.float32
|
| 479 |
+
):
|
| 480 |
+
raise RuntimeError(
|
| 481 |
+
"linear_cross_entropy supports float32 acc_dtype with"
|
| 482 |
+
f" float16/bfloat16 inputs, but got {acc_dtype} acc_dtype and {dtype} inputs."
|
| 483 |
+
)
|
| 484 |
+
use_acc_dtype = dtype != acc_dtype
|
| 485 |
+
|
| 486 |
+
# Internal dtype layout shared by the memory-like policy. ``compact``'s
|
| 487 |
+
# savings come from skipping the weight_grad_chunk scratch, not dtype.
|
| 488 |
+
is_memory_like = acc_policy == "compact"
|
| 489 |
+
if use_acc_dtype:
|
| 490 |
+
output_dtype = acc_dtype if dtype == torch.float16 else dtype
|
| 491 |
+
grad_input_dtype = dtype if is_memory_like else acc_dtype
|
| 492 |
+
# fp16 + memory-like keeps logits at fp16 (2BC vs 4BC);
|
| 493 |
+
# everything else upcasts for softmax stability.
|
| 494 |
+
logits_buf_dtype = (
|
| 495 |
+
dtype if dtype == torch.float16 and is_memory_like else acc_dtype
|
| 496 |
+
)
|
| 497 |
+
# acc_dtype mandatory: 1/N for reduction="mean" is subnormal
|
| 498 |
+
# in fp16 at N >= 65536.
|
| 499 |
+
weight_chunk_dtype = acc_dtype
|
| 500 |
+
else:
|
| 501 |
+
output_dtype = grad_input_dtype = logits_buf_dtype = weight_chunk_dtype = (
|
| 502 |
+
dtype
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
# ===== Dispatch flags =====
|
| 506 |
+
# CUDA + compact uses cuBLAS out_dtype= directly; no cast.
|
| 507 |
+
needs_linear_weight_cast = use_acc_dtype and (
|
| 508 |
+
not is_cuda or (compute_input_grad and grad_input_dtype == logits_buf_dtype)
|
| 509 |
+
)
|
| 510 |
+
linear_weight_cast_dtype = (
|
| 511 |
+
logits_buf_dtype if needs_linear_weight_cast else dtype
|
| 512 |
+
)
|
| 513 |
+
alloc_weight_grad_chunk = compute_linear_weight_grad and not (
|
| 514 |
+
acc_policy == "compact" and (is_cuda or logits_buf_dtype == dtype)
|
| 515 |
+
)
|
| 516 |
+
# Per-chunk acc_dtype scratch for grad_linear_bias; same
|
| 517 |
+
# bulk-+-correction precision rationale as
|
| 518 |
+
# ``alloc_weight_grad_chunk``. Fires only when there is
|
| 519 |
+
# precision to gain: ``use_acc_dtype`` and the user asked for
|
| 520 |
+
# the bias gradient.
|
| 521 |
+
alloc_linear_bias_grad_chunk = compute_linear_bias_grad and use_acc_dtype
|
| 522 |
+
alloc_input_grad_acc_buf = (
|
| 523 |
+
compute_input_grad
|
| 524 |
+
and not is_cuda
|
| 525 |
+
and (grad_input_dtype != linear_weight_cast_dtype or is_mps)
|
| 526 |
+
)
|
| 527 |
+
alloc_input_chunk_acc_buf = use_acc_dtype and (
|
| 528 |
+
compute_linear_weight_grad or (not is_cuda and dtype != logits_buf_dtype)
|
| 529 |
+
)
|
| 530 |
+
forward_uses_acc_input = (
|
| 531 |
+
use_acc_dtype and not is_cuda and dtype != logits_buf_dtype
|
| 532 |
+
)
|
| 533 |
+
forward_uses_cuda_out_dtype = is_cuda and use_acc_dtype
|
| 534 |
+
weight_grad_mm_same_dtype = logits_buf_dtype == acc_dtype
|
| 535 |
+
# Storage-trick fires when logits' dtype differs from the input-
|
| 536 |
+
# grad accumulator dtype.
|
| 537 |
+
input_grad_uses_logits_lw = (
|
| 538 |
+
is_cuda and compute_input_grad and logits_buf_dtype != grad_input_dtype
|
| 539 |
+
)
|
| 540 |
+
# Per-iter ``logits.to(linear_weight.dtype)`` shared between the
|
| 541 |
+
# inlined input-grad addmm and the inlined direct weight-grad addmm_.
|
| 542 |
+
loop_caches_logits_downcast = input_grad_uses_logits_lw or (
|
| 543 |
+
compute_linear_weight_grad
|
| 544 |
+
and not alloc_weight_grad_chunk
|
| 545 |
+
and logits_buf_dtype != dtype
|
| 546 |
+
)
|
| 547 |
+
alloc_logits_acc_buf = (
|
| 548 |
+
alloc_weight_grad_chunk and not is_cuda and logits_buf_dtype != acc_dtype
|
| 549 |
+
)
|
| 550 |
+
# Direct weight-grad path: reuse logits_buf storage for the
|
| 551 |
+
# acc_dtype->dtype cast when its bytes/row fits the (B, F) cast.
|
| 552 |
+
weight_grad_uses_logits_buf_temp = (
|
| 553 |
+
not alloc_weight_grad_chunk
|
| 554 |
+
and use_acc_dtype
|
| 555 |
+
and num_classes * logits_buf_dtype.itemsize >= in_features * dtype.itemsize
|
| 556 |
+
)
|
| 557 |
+
# Prob path: per-chunk (B, V) scratch for weight*target at the
|
| 558 |
+
# logits dtype. Skipped when target_chunk can be used directly
|
| 559 |
+
# (no class weight and dtype already matches).
|
| 560 |
+
alloc_prob_target_buf = is_prob_target and (
|
| 561 |
+
weight is not None or dtype != logits_buf_dtype
|
| 562 |
+
)
|
| 563 |
+
if is_prob_target and reduction == "mean":
|
| 564 |
+
loss_scale = 1.0 / num_batches if num_batches else float("nan")
|
| 565 |
+
else:
|
| 566 |
+
loss_scale = 1.0
|
| 567 |
+
|
| 568 |
+
return cls(
|
| 569 |
+
dtype=dtype,
|
| 570 |
+
num_batches=num_batches,
|
| 571 |
+
in_features=in_features,
|
| 572 |
+
num_classes=num_classes,
|
| 573 |
+
is_cuda=is_cuda,
|
| 574 |
+
use_acc_dtype=use_acc_dtype,
|
| 575 |
+
acc_dtype=acc_dtype,
|
| 576 |
+
weight_chunk_dtype=weight_chunk_dtype,
|
| 577 |
+
grad_input_dtype=grad_input_dtype,
|
| 578 |
+
linear_weight_cast_dtype=linear_weight_cast_dtype,
|
| 579 |
+
input=input,
|
| 580 |
+
target=target,
|
| 581 |
+
weight=weight,
|
| 582 |
+
ignore_index=ignore_index,
|
| 583 |
+
reduction=reduction,
|
| 584 |
+
is_prob_target=is_prob_target,
|
| 585 |
+
loss_scale=loss_scale,
|
| 586 |
+
linear_weight=linear_weight,
|
| 587 |
+
linear_bias=linear_bias,
|
| 588 |
+
loss_grad_output=loss_grad_output,
|
| 589 |
+
logits_buf=torch.empty(
|
| 590 |
+
(batch_chunk_size, num_classes),
|
| 591 |
+
dtype=logits_buf_dtype,
|
| 592 |
+
device=device,
|
| 593 |
+
requires_grad=False,
|
| 594 |
+
),
|
| 595 |
+
tmp=torch.empty(
|
| 596 |
+
(batch_chunk_size,),
|
| 597 |
+
dtype=logits_buf_dtype,
|
| 598 |
+
device=device,
|
| 599 |
+
requires_grad=False,
|
| 600 |
+
),
|
| 601 |
+
output=_make_zeros((), output_dtype, device),
|
| 602 |
+
compute_input_grad=compute_input_grad,
|
| 603 |
+
compute_linear_weight_grad=compute_linear_weight_grad,
|
| 604 |
+
compute_linear_bias_grad=compute_linear_bias_grad,
|
| 605 |
+
alloc_prob_target_buf=alloc_prob_target_buf,
|
| 606 |
+
alloc_weight_grad_chunk=alloc_weight_grad_chunk,
|
| 607 |
+
alloc_linear_bias_grad_chunk=alloc_linear_bias_grad_chunk,
|
| 608 |
+
alloc_input_grad_acc_buf=alloc_input_grad_acc_buf,
|
| 609 |
+
alloc_input_chunk_acc_buf=alloc_input_chunk_acc_buf,
|
| 610 |
+
alloc_logits_acc_buf=alloc_logits_acc_buf,
|
| 611 |
+
forward_uses_acc_input=forward_uses_acc_input,
|
| 612 |
+
forward_uses_cuda_out_dtype=forward_uses_cuda_out_dtype,
|
| 613 |
+
weight_grad_mm_same_dtype=weight_grad_mm_same_dtype,
|
| 614 |
+
input_grad_uses_logits_lw=input_grad_uses_logits_lw,
|
| 615 |
+
loop_caches_logits_downcast=loop_caches_logits_downcast,
|
| 616 |
+
weight_grad_uses_logits_buf_temp=weight_grad_uses_logits_buf_temp,
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
def chunks(self):
|
| 620 |
+
"""Yield a ``_ChunkViews`` per iter. Post-yield, run the
|
| 621 |
+
scratch-to-final commits that the loop body deferred: the
|
| 622 |
+
buf-and-copy input-grad slice into ``grad_input`` (skipped on
|
| 623 |
+
the fast path where ``grad_input_chunk`` aliases
|
| 624 |
+
``grad_input``), and the acc_dtype linear_bias scratch into
|
| 625 |
+
``grad_linear_bias`` (skipped when accumulation went straight
|
| 626 |
+
into ``grad_linear_bias`` in input dtype).
|
| 627 |
+
"""
|
| 628 |
+
batch_chunk_size = self.logits_buf.shape[0]
|
| 629 |
+
for bchunk_start in range(0, self.num_batches, batch_chunk_size):
|
| 630 |
+
bchunk_size = min(batch_chunk_size, self.num_batches - bchunk_start)
|
| 631 |
+
chunk = self.bind_chunk(bchunk_start, bchunk_size)
|
| 632 |
+
yield chunk
|
| 633 |
+
if self.alloc_input_grad_acc_buf:
|
| 634 |
+
self.grad_input.narrow(0, bchunk_start, bchunk_size).copy_(
|
| 635 |
+
chunk.grad_input_chunk
|
| 636 |
+
)
|
| 637 |
+
if self.alloc_linear_bias_grad_chunk:
|
| 638 |
+
# ``chunk.bias_grad_acc`` aliases ``linear_bias_grad_chunk``
|
| 639 |
+
# here; downcast-commit, then zero for the next chunk.
|
| 640 |
+
self.grad_linear_bias.add_(
|
| 641 |
+
chunk.bias_grad_acc.to(self.grad_linear_bias.dtype)
|
| 642 |
+
)
|
| 643 |
+
chunk.bias_grad_acc.zero_()
|
| 644 |
+
|
| 645 |
+
def bind_chunk(self, bchunk_start: int, bchunk_size: int) -> _ChunkViews:
|
| 646 |
+
input_chunk = self.input.narrow(0, bchunk_start, bchunk_size)
|
| 647 |
+
target_chunk = self.corrected_target.narrow(0, bchunk_start, bchunk_size)
|
| 648 |
+
# The prob loop derives its per-chunk row weighting from
|
| 649 |
+
# ``prob_wt`` instead of the per-row ``neg_weight_target``.
|
| 650 |
+
weight_chunk = (
|
| 651 |
+
None
|
| 652 |
+
if self.is_prob_target
|
| 653 |
+
else self.neg_weight_target.narrow(0, bchunk_start, bchunk_size)
|
| 654 |
+
)
|
| 655 |
+
logits = self.logits_buf.narrow(0, 0, bchunk_size)
|
| 656 |
+
input_chunk_acc = (
|
| 657 |
+
self.input_chunk_acc_buf.narrow(0, 0, bchunk_size).copy_(input_chunk)
|
| 658 |
+
if self.alloc_input_chunk_acc_buf
|
| 659 |
+
else input_chunk
|
| 660 |
+
)
|
| 661 |
+
return _ChunkViews(
|
| 662 |
+
ctx=self,
|
| 663 |
+
bchunk_start=bchunk_start,
|
| 664 |
+
bchunk_size=bchunk_size,
|
| 665 |
+
input_chunk=input_chunk,
|
| 666 |
+
target_chunk=target_chunk,
|
| 667 |
+
weight_chunk=weight_chunk,
|
| 668 |
+
logits=logits,
|
| 669 |
+
input_chunk_acc=input_chunk_acc,
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
def mm(self, mat1: torch.Tensor, mat2: torch.Tensor, *, out: torch.Tensor) -> None:
|
| 673 |
+
# Mismatched dtype: cuBLAS ``out_dtype=`` upcasts inside the matmul.
|
| 674 |
+
if mat1.dtype == out.dtype:
|
| 675 |
+
torch.mm(mat1, mat2, out=out)
|
| 676 |
+
else:
|
| 677 |
+
torch.mm(mat1, mat2, out_dtype=out.dtype, out=out)
|
| 678 |
+
|
| 679 |
+
def shifted_logits(self, chunk: _ChunkViews) -> torch.Tensor:
|
| 680 |
+
# Per-chunk forward prelude shared by all three chunk loops (none /
|
| 681 |
+
# prob / index): logits = input @ weight.T (+ bias), shifted by the
|
| 682 |
+
# per-row max for softmax stability. Writes into ``chunk.logits``.
|
| 683 |
+
logits = chunk.logits
|
| 684 |
+
self.mm(chunk.input, chunk.linear_weight.T, out=logits)
|
| 685 |
+
if self.linear_bias_cast is not None:
|
| 686 |
+
logits.add_(self.linear_bias_cast)
|
| 687 |
+
# Subtract the per-row max in place; ``self.tmp`` is reused scratch.
|
| 688 |
+
row_max = self.tmp.narrow(0, 0, logits.shape[0]).unsqueeze(1)
|
| 689 |
+
torch.amax(logits, dim=1, keepdim=True, out=row_max)
|
| 690 |
+
logits.sub_(row_max)
|
| 691 |
+
return logits
|
| 692 |
+
|
| 693 |
+
def dotgather(
|
| 694 |
+
self, weight: torch.Tensor, x: torch.Tensor, indices: torch.Tensor
|
| 695 |
+
) -> torch.Tensor:
|
| 696 |
+
return weight.dot(x.gather(1, indices.unsqueeze(1)).squeeze(1).to(weight.dtype))
|
| 697 |
+
|
| 698 |
+
def sumexp_(self, x: torch.Tensor, dim: int) -> torch.Tensor:
|
| 699 |
+
# The denom sums num_classes terms in (0, 1] (shifted logits <= 0).
|
| 700 |
+
# fp16: accumulate in fp32 -- the sum overflows fp16's 65504 for a large
|
| 701 |
+
# vocabulary (-> inf). bf16 stays in acc_dtype: it shares fp32's exponent
|
| 702 |
+
# range so it cannot overflow, and computing the denom in fp32 vs bf16
|
| 703 |
+
# was measured to move the bf16-stored log(denom) / (1/denom) by <=1 ULP,
|
| 704 |
+
# so there is no gain to justify it (and it would re-calibrate bf16 caps).
|
| 705 |
+
reduce_dtype = torch.float32 if self.dtype == torch.float16 else self.acc_dtype
|
| 706 |
+
return x.exp_().sum(dim, dtype=reduce_dtype)
|
| 707 |
+
|
| 708 |
+
def sum(self, x: torch.Tensor, dim: int) -> torch.Tensor:
|
| 709 |
+
# Reduce ``x`` along ``dim`` at acc_dtype on mixed-precision
|
| 710 |
+
# paths and at input dtype otherwise -- the precision
|
| 711 |
+
# contract callers see is "as accurate as the active policy
|
| 712 |
+
# allows". Currently used by the bias-grad path so the per-
|
| 713 |
+
# chunk sum carries full precision before the post-yield
|
| 714 |
+
# downcast commit to grad_linear_bias.
|
| 715 |
+
target_dtype = self.acc_dtype if self.use_acc_dtype else self.dtype
|
| 716 |
+
return x.sum(dim, dtype=target_dtype)
|
| 717 |
+
|
| 718 |
+
def div(self, num: torch.Tensor, den: torch.Tensor) -> torch.Tensor:
|
| 719 |
+
factor = self.tmp.narrow(0, 0, num.shape[0])
|
| 720 |
+
# MPS lacks fused cross-dtype torch.div(out=); copy_ fallback.
|
| 721 |
+
if self.input.device.type == "mps" and (
|
| 722 |
+
num.dtype != factor.dtype or den.dtype != factor.dtype
|
| 723 |
+
):
|
| 724 |
+
factor.copy_(num / den)
|
| 725 |
+
else:
|
| 726 |
+
torch.div(num, den, out=factor)
|
| 727 |
+
return factor
|
| 728 |
+
|
| 729 |
+
def mul(self, x: torch.Tensor, w: torch.Tensor) -> torch.Tensor:
|
| 730 |
+
# Pick a destination from in-flight scratch when possible.
|
| 731 |
+
if self.use_acc_dtype:
|
| 732 |
+
return x.mul_(w.unsqueeze(1))
|
| 733 |
+
if self.num_classes >= self.in_features:
|
| 734 |
+
return torch.mul(
|
| 735 |
+
x,
|
| 736 |
+
w.unsqueeze(1),
|
| 737 |
+
out=self.logits_buf.narrow(0, 0, x.shape[0]).narrow(
|
| 738 |
+
1, 0, self.in_features
|
| 739 |
+
),
|
| 740 |
+
)
|
| 741 |
+
return x * w.unsqueeze(1)
|
| 742 |
+
|
| 743 |
+
def to(self, x: torch.Tensor, *, dtype: torch.dtype) -> torch.Tensor:
|
| 744 |
+
# Reuse logits_buf storage as cast destination when its bytes/row fits.
|
| 745 |
+
if x.dtype == dtype:
|
| 746 |
+
return x
|
| 747 |
+
if self.weight_grad_uses_logits_buf_temp:
|
| 748 |
+
x = (
|
| 749 |
+
self.logits_buf.view(dtype)
|
| 750 |
+
.narrow(0, 0, x.shape[0])
|
| 751 |
+
.narrow(1, 0, x.shape[1])
|
| 752 |
+
.copy_(x)
|
| 753 |
+
)
|
| 754 |
+
return x
|
| 755 |
+
return x.to(dtype)
|
| 756 |
+
|
| 757 |
+
|
| 758 |
+
def _linear_cross_entropy_batch_chunked_accumulator(
|
| 759 |
+
input: torch.Tensor,
|
| 760 |
+
linear_weight: torch.Tensor,
|
| 761 |
+
target: torch.Tensor,
|
| 762 |
+
linear_bias: torch.Tensor | None,
|
| 763 |
+
weight: torch.Tensor | None,
|
| 764 |
+
reduction: str,
|
| 765 |
+
ignore_index: int,
|
| 766 |
+
label_smoothing: float,
|
| 767 |
+
batch_chunk_size: int,
|
| 768 |
+
acc_policy: str,
|
| 769 |
+
acc_dtype: torch.dtype,
|
| 770 |
+
compute_input_grad: bool,
|
| 771 |
+
compute_linear_weight_grad: bool,
|
| 772 |
+
compute_linear_bias_grad: bool,
|
| 773 |
+
loss_grad_output: torch.Tensor | None = None,
|
| 774 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 775 |
+
"""Chunked loop shared by all three custom-op entry points; returns
|
| 776 |
+
``(loss, grad_input, grad_linear_weight, grad_linear_bias)``.
|
| 777 |
+
|
| 778 |
+
Caller -> branch:
|
| 779 |
+
scalar-op forward (reduction in {mean,sum}) -> main grad loop
|
| 780 |
+
scalar-op forward, probability target -> prob loop
|
| 781 |
+
no_reduction forward (none, loss_grad_output None) -> loss-only branch
|
| 782 |
+
no_reduction backward (none, loss_grad_output set) -> main grad loop
|
| 783 |
+
|
| 784 |
+
- ``_linear_cross_entropy_batch_chunked`` (scalar reduction): the
|
| 785 |
+
forward precomputes the scalar loss and all gradients in one pass;
|
| 786 |
+
backward just scales the stashed grads by the upstream gradient.
|
| 787 |
+
- ``_linear_cross_entropy_batch_chunked_no_reduction`` (forward):
|
| 788 |
+
``reduction='none'`` with ``loss_grad_output is None`` takes the
|
| 789 |
+
loss-only branch, returning the per-sample loss ``(N,)`` and no
|
| 790 |
+
gradients (they are recomputed in its backward instead).
|
| 791 |
+
- ``_linear_cross_entropy_batch_chunked_no_reduction`` (backward):
|
| 792 |
+
``loss_grad_output`` set folds the per-sample upstream grad into
|
| 793 |
+
``neg_weight_target``, so this same loop recomputes the chunked
|
| 794 |
+
grads as the grad_output-weighted VJP (the scalar loss it also
|
| 795 |
+
accumulates is then meaningless and ignored).
|
| 796 |
+
|
| 797 |
+
Dispatch contract
|
| 798 |
+
-----------------
|
| 799 |
+
The chunked loop body is the mathematical description of the
|
| 800 |
+
algorithm. All policy / device / dtype dispatch lives in
|
| 801 |
+
``_ChunkContext`` (and its ``_ChunkViews`` peers):
|
| 802 |
+
|
| 803 |
+
- **Buffer choices** -- whether a per-chunk acc_dtype scratch is
|
| 804 |
+
used or accumulation runs directly into the final tensor -- live
|
| 805 |
+
in ``alloc_*`` flags computed in ``_ChunkContext.build`` and
|
| 806 |
+
surfaced as ``_ChunkViews`` properties (e.g.
|
| 807 |
+
``grad_input_chunk``, ``bias_grad_acc``).
|
| 808 |
+
- **Scratch-to-final commits** for those buffers live in
|
| 809 |
+
``_ChunkContext.chunks()`` post-yield hooks (e.g. the
|
| 810 |
+
``grad_input`` buf-and-copy commit, the ``grad_linear_bias``
|
| 811 |
+
downcast-and-zero commit).
|
| 812 |
+
- **Dtype dispatch on individual math operations** lives in
|
| 813 |
+
``_ChunkContext`` methods that mirror PyTorch ops --
|
| 814 |
+
``mm``, ``amax``, ``dotgather``, ``sumexp_``, ``sum``, ``div``,
|
| 815 |
+
``mul``, ``to`` -- each one hiding ``out_dtype=`` / acc-dtype /
|
| 816 |
+
buffer-reuse decisions behind a single math call.
|
| 817 |
+
|
| 818 |
+
The function body therefore should not introduce inline
|
| 819 |
+
``if ctx.use_acc_dtype`` / ``if ctx.is_cuda`` / etc. branches; new
|
| 820 |
+
policy-aware behaviour belongs in one of the three locations
|
| 821 |
+
above. The two existing inline branches (``if compute_input_grad``,
|
| 822 |
+
``if compute_linear_weight_grad``, etc.) gate optional outputs,
|
| 823 |
+
not dispatch.
|
| 824 |
+
"""
|
| 825 |
+
# Direct callers must resolve "auto" / None via _adjust first.
|
| 826 |
+
if acc_policy == "auto" or acc_dtype is None:
|
| 827 |
+
raise RuntimeError(
|
| 828 |
+
f"unresolved acc_policy={acc_policy!r} or acc_dtype={acc_dtype!r};"
|
| 829 |
+
" use F.linear_cross_entropy."
|
| 830 |
+
)
|
| 831 |
+
ctx = _ChunkContext.build(
|
| 832 |
+
input,
|
| 833 |
+
linear_weight,
|
| 834 |
+
target,
|
| 835 |
+
linear_bias,
|
| 836 |
+
weight,
|
| 837 |
+
reduction,
|
| 838 |
+
ignore_index,
|
| 839 |
+
label_smoothing,
|
| 840 |
+
batch_chunk_size,
|
| 841 |
+
acc_policy,
|
| 842 |
+
acc_dtype,
|
| 843 |
+
compute_input_grad,
|
| 844 |
+
compute_linear_weight_grad,
|
| 845 |
+
compute_linear_bias_grad,
|
| 846 |
+
loss_grad_output=loss_grad_output,
|
| 847 |
+
)
|
| 848 |
+
dtype = ctx.dtype
|
| 849 |
+
# reduction='none' forward (no upstream grad yet): per-sample loss
|
| 850 |
+
# into an (N,) output, no gradient precompute. ``chunk.weight_chunk``
|
| 851 |
+
# is the unsigned masked class weight here (neg_weight_target's "none"
|
| 852 |
+
# forward form), so each row's loss is W[T[n]] * (log denom -
|
| 853 |
+
# shifted_logit[T[n]]) = W[T[n]] * (-log_softmax). The "none" backward
|
| 854 |
+
# (loss_grad_output set) routes through the grad loop below instead.
|
| 855 |
+
if reduction == "none" and loss_grad_output is None:
|
| 856 |
+
out = torch.empty(ctx.num_batches, dtype=dtype, device=ctx.input.device)
|
| 857 |
+
for chunk in ctx.chunks():
|
| 858 |
+
logits = ctx.shifted_logits(chunk)
|
| 859 |
+
# Read the target logit BEFORE ``sumexp_`` -- it does ``exp_()``
|
| 860 |
+
# in place, overwriting logits with exp(shifted).
|
| 861 |
+
ls_target = logits.gather(1, chunk.target_chunk.unsqueeze(1)).squeeze(1)
|
| 862 |
+
softmax_denom = ctx.sumexp_(logits, dim=1)
|
| 863 |
+
loss_chunk = softmax_denom.log_().sub_(ls_target.to(softmax_denom.dtype))
|
| 864 |
+
loss_chunk.mul_(chunk.weight_chunk.to(softmax_denom.dtype))
|
| 865 |
+
out.narrow(0, chunk.bchunk_start, chunk.bchunk_size).copy_(loss_chunk)
|
| 866 |
+
return (
|
| 867 |
+
out,
|
| 868 |
+
ctx.grad_input.to(dtype),
|
| 869 |
+
ctx.grad_linear_weight,
|
| 870 |
+
ctx.grad_linear_bias,
|
| 871 |
+
)
|
| 872 |
+
output = ctx.output
|
| 873 |
+
grad_input = ctx.grad_input
|
| 874 |
+
grad_linear_weight = ctx.grad_linear_weight
|
| 875 |
+
grad_linear_bias = ctx.grad_linear_bias
|
| 876 |
+
weight_grad_chunk = ctx.weight_grad_chunk
|
| 877 |
+
linear_weight_cast = ctx.linear_weight_cast
|
| 878 |
+
|
| 879 |
+
if reduction == "mean" and ctx.num_batches == 0:
|
| 880 |
+
output.fill_(torch.nan)
|
| 881 |
+
|
| 882 |
+
compute_grads = (
|
| 883 |
+
compute_input_grad or compute_linear_weight_grad or compute_linear_bias_grad
|
| 884 |
+
)
|
| 885 |
+
|
| 886 |
+
if ctx.is_prob_target:
|
| 887 |
+
# Probability-target loop. The per-row weighting is the dense
|
| 888 |
+
# (B, V) ``prob_wt`` (= class_weight * target) instead of the
|
| 889 |
+
# index path's gathered per-row scalar: the loss target term is
|
| 890 |
+
# a flat dot, the softmax scaling uses the per-chunk row mass
|
| 891 |
+
# s_n = sum_c (w*t)[n, c], and the gradient correction is a
|
| 892 |
+
# dense subtraction -- no gather / index_add_ / index_select.
|
| 893 |
+
# Signs are direct (positive ``loss_scale``), unlike the index
|
| 894 |
+
# loop's negated ``neg_weight_target`` convention.
|
| 895 |
+
loss_scale = ctx.loss_scale
|
| 896 |
+
for chunk in ctx.chunks():
|
| 897 |
+
logits = ctx.shifted_logits(chunk)
|
| 898 |
+
wt = chunk.prob_wt
|
| 899 |
+
# Loss target term sum_{n,c} (w*t)*x_shifted, read BEFORE
|
| 900 |
+
# ``sumexp_`` (it ``exp_``s logits in place). torch.dot returns its
|
| 901 |
+
# scalar at the operand dtype, so when the logits buffer is fp16
|
| 902 |
+
# (CUDA compact) the sum overflows fp16 (>65504) for a
|
| 903 |
+
# large batch of max-shifted (<=0) logits; a per-row einsum summed
|
| 904 |
+
# across rows in fp32 stays finite (same cost as the dot). bf16/fp32
|
| 905 |
+
# operands return a wide-enough scalar, so keep the flat dot.
|
| 906 |
+
if logits.dtype == torch.float16:
|
| 907 |
+
per_row = torch.einsum("bv,bv->b", wt, logits)
|
| 908 |
+
loss_term = per_row.sum(dtype=torch.float32)
|
| 909 |
+
else:
|
| 910 |
+
loss_term = torch.dot(wt.reshape(-1), logits.reshape(-1))
|
| 911 |
+
# ``output`` is fp16 when acc_dtype is fp16 (e.g. MPS). MPS narrows
|
| 912 |
+
# the large fp32 loss_term to fp16 (-> inf) BEFORE applying alpha,
|
| 913 |
+
# unlike the documented type-promoted in-place subtract other
|
| 914 |
+
# backends do; scale first there so the operand stays in fp16 range.
|
| 915 |
+
if output.device.type == "mps":
|
| 916 |
+
output.sub_(loss_term * loss_scale)
|
| 917 |
+
else:
|
| 918 |
+
output.sub_(loss_term, alpha=loss_scale)
|
| 919 |
+
# Per-row weight mass with the reduction factor folded in.
|
| 920 |
+
s = wt.sum(1, dtype=ctx.weight_chunk_dtype).mul_(loss_scale)
|
| 921 |
+
softmax_denom = ctx.sumexp_(logits, dim=1)
|
| 922 |
+
if compute_grads:
|
| 923 |
+
# logits *= s/denom (= loss_scale * softmax(x) * s_n)
|
| 924 |
+
torch.mul(
|
| 925 |
+
logits,
|
| 926 |
+
ctx.div(s, softmax_denom).unsqueeze(1),
|
| 927 |
+
out=logits,
|
| 928 |
+
)
|
| 929 |
+
# output += <s, log denom> (loss_scale already in s)
|
| 930 |
+
output.add_(s.to(softmax_denom.dtype).dot(softmax_denom.log_()))
|
| 931 |
+
if compute_grads:
|
| 932 |
+
# grad_logits = loss_scale * (softmax*s_n - w*t); from
|
| 933 |
+
# here every gradient is a single dense op.
|
| 934 |
+
logits.sub_(wt, alpha=loss_scale)
|
| 935 |
+
if compute_linear_bias_grad:
|
| 936 |
+
chunk.bias_grad_acc.add_(ctx.sum(logits, dim=0))
|
| 937 |
+
if compute_input_grad:
|
| 938 |
+
ctx.mm(
|
| 939 |
+
chunk.input_grad_logits,
|
| 940 |
+
chunk.input_grad_linear_weight,
|
| 941 |
+
out=chunk.grad_input_chunk,
|
| 942 |
+
)
|
| 943 |
+
if compute_linear_weight_grad:
|
| 944 |
+
if ctx.alloc_weight_grad_chunk:
|
| 945 |
+
ctx.mm(
|
| 946 |
+
chunk.logits_upcast.T,
|
| 947 |
+
chunk.weight_grad_input,
|
| 948 |
+
out=weight_grad_chunk,
|
| 949 |
+
)
|
| 950 |
+
grad_linear_weight.add_(weight_grad_chunk)
|
| 951 |
+
else:
|
| 952 |
+
grad_linear_weight.addmm_(
|
| 953 |
+
chunk.logits_downcast.T, chunk.input_chunk, alpha=1
|
| 954 |
+
)
|
| 955 |
+
return (
|
| 956 |
+
output.to(dtype),
|
| 957 |
+
grad_input.to(dtype),
|
| 958 |
+
grad_linear_weight,
|
| 959 |
+
grad_linear_bias,
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
# Do not ``break`` from this loop -- ``ctx.chunks()`` runs a
|
| 963 |
+
# post-yield grad_input commit that the in-flight chunk needs.
|
| 964 |
+
for chunk in ctx.chunks():
|
| 965 |
+
logits = ctx.shifted_logits(chunk)
|
| 966 |
+
weight_chunk = chunk.weight_chunk
|
| 967 |
+
target_chunk = chunk.target_chunk
|
| 968 |
+
# output += <weight_chunk, logits[:, target_chunk]>
|
| 969 |
+
output.add_(ctx.dotgather(weight_chunk, logits, target_chunk))
|
| 970 |
+
softmax_denom = ctx.sumexp_(logits, dim=1)
|
| 971 |
+
if compute_grads:
|
| 972 |
+
# logits *= weight_chunk / softmax_denom (= softmax(logits) * w)
|
| 973 |
+
# MPS: in-place mul_ on a narrow view of logits_buf doesn't
|
| 974 |
+
# propagate to parent storage; the out= form does.
|
| 975 |
+
torch.mul(
|
| 976 |
+
logits,
|
| 977 |
+
ctx.div(weight_chunk, softmax_denom).unsqueeze(1),
|
| 978 |
+
out=logits,
|
| 979 |
+
)
|
| 980 |
+
# output -= <weight_chunk, log(softmax_denom)>
|
| 981 |
+
# softmax_denom is in acc_dtype (see ``sumexp_``); promote weight_chunk
|
| 982 |
+
# for the dot rather than rounding the wider denominator down.
|
| 983 |
+
output.sub_(weight_chunk.to(softmax_denom.dtype).dot(softmax_denom.log_()))
|
| 984 |
+
|
| 985 |
+
if compute_grads:
|
| 986 |
+
if compute_linear_bias_grad:
|
| 987 |
+
# Must run BEFORE the linear-weight-grad branch below.
|
| 988 |
+
# The ordering invariant is defensive across all
|
| 989 |
+
# ``ctx.mul`` paths: only the (not use_acc_dtype &&
|
| 990 |
+
# num_classes >= in_features) branch overwrites the
|
| 991 |
+
# first ``in_features`` columns of ``logits_buf`` via a
|
| 992 |
+
# narrow ``out=`` view today, but ``ctx.mul``'s contract
|
| 993 |
+
# does not promise to leave ``logits_buf`` untouched on
|
| 994 |
+
# other paths -- placing the bias-grad read here keeps
|
| 995 |
+
# the loop correct regardless of which ``ctx.mul``
|
| 996 |
+
# variant fires.
|
| 997 |
+
#
|
| 998 |
+
# The inline form expresses
|
| 999 |
+
# dL/db_j = sum_n W[T[n]] * (softmax(X)[n, j] - delta(T[n], j))
|
| 1000 |
+
# as ``-logits.sum(dim=0)`` (the softmax-weighted term)
|
| 1001 |
+
# plus ``index_add_(0, target_chunk, weight_chunk)``
|
| 1002 |
+
# (the one-hot-weighted correction). ``logits`` is
|
| 1003 |
+
# ``softmax(X) * weight_chunk[n]`` here; ``weight_chunk``
|
| 1004 |
+
# already carries the sign and the 1/d mean
|
| 1005 |
+
# normalization (``W`` here is the CE class weight, not
|
| 1006 |
+
# ``linear_weight``), so no extra scaling is needed.
|
| 1007 |
+
bias_grad_acc = chunk.bias_grad_acc
|
| 1008 |
+
bias_grad_acc.sub_(ctx.sum(logits, dim=0))
|
| 1009 |
+
bias_grad_acc.index_add_(0, target_chunk, weight_chunk)
|
| 1010 |
+
if compute_input_grad:
|
| 1011 |
+
grad_input_chunk = chunk.grad_input_chunk
|
| 1012 |
+
input_grad_logits = chunk.input_grad_logits
|
| 1013 |
+
input_grad_linear_weight = chunk.input_grad_linear_weight
|
| 1014 |
+
|
| 1015 |
+
# grad_input_chunk = linear_weight_cast[target_chunk] * weight_chunk
|
| 1016 |
+
torch.mul(
|
| 1017 |
+
torch.index_select(linear_weight_cast, 0, target_chunk),
|
| 1018 |
+
weight_chunk.to(grad_input_chunk.dtype).unsqueeze(1),
|
| 1019 |
+
out=grad_input_chunk,
|
| 1020 |
+
)
|
| 1021 |
+
# grad_input_chunk -= input_grad_logits @ input_grad_linear_weight
|
| 1022 |
+
torch.addmm(
|
| 1023 |
+
grad_input_chunk,
|
| 1024 |
+
input_grad_logits,
|
| 1025 |
+
input_grad_linear_weight,
|
| 1026 |
+
alpha=-1,
|
| 1027 |
+
out=grad_input_chunk,
|
| 1028 |
+
)
|
| 1029 |
+
if compute_linear_weight_grad:
|
| 1030 |
+
input_chunk_acc = chunk.input_chunk_acc
|
| 1031 |
+
|
| 1032 |
+
# grad_linear_weight += per-chunk weight grad
|
| 1033 |
+
# (= -logits.T @ input + input*weight scattered at target rows)
|
| 1034 |
+
if ctx.alloc_weight_grad_chunk:
|
| 1035 |
+
# Stage per-chunk weight grad in acc_dtype scratch;
|
| 1036 |
+
# one sub_ commit keeps bulk-minus-correction in fp32.
|
| 1037 |
+
logits_upcast = chunk.logits_upcast
|
| 1038 |
+
weight_grad_input = chunk.weight_grad_input
|
| 1039 |
+
ctx.mm(
|
| 1040 |
+
logits_upcast.T,
|
| 1041 |
+
weight_grad_input,
|
| 1042 |
+
out=weight_grad_chunk,
|
| 1043 |
+
)
|
| 1044 |
+
temp = ctx.mul(input_chunk_acc, weight_chunk)
|
| 1045 |
+
weight_grad_chunk.index_add_(0, target_chunk, temp, alpha=-1)
|
| 1046 |
+
grad_linear_weight.sub_(weight_grad_chunk)
|
| 1047 |
+
else:
|
| 1048 |
+
# Stream bulk + correction directly into grad_lw without
|
| 1049 |
+
# a (V, F) scratch (the compact path).
|
| 1050 |
+
grad_linear_weight.addmm_(
|
| 1051 |
+
chunk.logits_downcast.T, chunk.input_chunk, alpha=-1
|
| 1052 |
+
)
|
| 1053 |
+
temp = ctx.to(
|
| 1054 |
+
ctx.mul(input_chunk_acc, weight_chunk),
|
| 1055 |
+
dtype=grad_linear_weight.dtype,
|
| 1056 |
+
)
|
| 1057 |
+
grad_linear_weight.index_add_(0, target_chunk, temp, alpha=1)
|
| 1058 |
+
|
| 1059 |
+
return (
|
| 1060 |
+
output.to(dtype),
|
| 1061 |
+
grad_input.to(dtype),
|
| 1062 |
+
grad_linear_weight,
|
| 1063 |
+
grad_linear_bias,
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
|
| 1067 |
+
# Scalar-reduction (mean/sum) op. Returns
|
| 1068 |
+
# ``(loss, grad_input, grad_linear_weight, grad_linear_bias)`` with grads
|
| 1069 |
+
# precomputed in forward (the accumulator runs the full grad loop) and
|
| 1070 |
+
# stashed on ctx by ``setup_context``; backward mutates them in place via
|
| 1071 |
+
# ``.mul_()`` by the upstream gradient. ``torch.library.register_autograd``
|
| 1072 |
+
# has no ``save_for_backward``-style state, hence the return-tuple +
|
| 1073 |
+
# ctx-stash dance. ``mutates_args=()`` reflects that inputs are not mutated.
|
| 1074 |
+
# Shape invariants: grad_input.shape == input.shape,
|
| 1075 |
+
# grad_linear_weight.shape == linear_weight.shape, grad_linear_bias.shape ==
|
| 1076 |
+
# linear_weight.shape[:-1] (here (C,), since the upstream gate requires
|
| 1077 |
+
# out_features == ()).
|
| 1078 |
+
@torch.library.custom_op(
|
| 1079 |
+
"torch_nn::_linear_cross_entropy_batch_chunked", mutates_args=()
|
| 1080 |
+
)
|
| 1081 |
+
def _linear_cross_entropy_batch_chunked(
|
| 1082 |
+
input: torch.Tensor,
|
| 1083 |
+
linear_weight: torch.Tensor,
|
| 1084 |
+
target: torch.Tensor,
|
| 1085 |
+
linear_bias: torch.Tensor | None,
|
| 1086 |
+
weight: torch.Tensor | None,
|
| 1087 |
+
reduction: str,
|
| 1088 |
+
ignore_index: int,
|
| 1089 |
+
label_smoothing: float,
|
| 1090 |
+
batch_chunk_size: int,
|
| 1091 |
+
acc_policy: str,
|
| 1092 |
+
acc_dtype: torch.dtype,
|
| 1093 |
+
allow_retain_graph: bool,
|
| 1094 |
+
compute_input_grad: bool,
|
| 1095 |
+
compute_linear_weight_grad: bool,
|
| 1096 |
+
compute_linear_bias_grad: bool,
|
| 1097 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 1098 |
+
"""Scalar-reduction (mean/sum) chunked op: precomputes the loss and
|
| 1099 |
+
gradients in forward, backward scales by the upstream gradient. The
|
| 1100 |
+
chunked math lives in ``_linear_cross_entropy_batch_chunked_accumulator``.
|
| 1101 |
+
"""
|
| 1102 |
+
# AOTAutograd/AOTInductor bake compute_*_grad at trace time; catch
|
| 1103 |
+
# the silent-corruption case (False at trace, but grad-enabled at
|
| 1104 |
+
# runtime with a requires_grad leaf). These guards are specific to
|
| 1105 |
+
# the precompute path -- the reduction='none' op recomputes grads in
|
| 1106 |
+
# its own backward, so it does not route through here.
|
| 1107 |
+
grad_enabled = torch.is_grad_enabled()
|
| 1108 |
+
if not compute_input_grad and input.requires_grad and grad_enabled:
|
| 1109 |
+
raise RuntimeError(
|
| 1110 |
+
"linear_cross_entropy chunked op: compute_input_grad was False at "
|
| 1111 |
+
"trace time but input.requires_grad is True at runtime; recompile "
|
| 1112 |
+
"the graph with the desired requires_grad."
|
| 1113 |
+
)
|
| 1114 |
+
if not compute_linear_weight_grad and linear_weight.requires_grad and grad_enabled:
|
| 1115 |
+
raise RuntimeError(
|
| 1116 |
+
"linear_cross_entropy chunked op: compute_linear_weight_grad was "
|
| 1117 |
+
"False at trace time but linear_weight.requires_grad is True at "
|
| 1118 |
+
"runtime; recompile the graph with the desired requires_grad."
|
| 1119 |
+
)
|
| 1120 |
+
if (
|
| 1121 |
+
not compute_linear_bias_grad
|
| 1122 |
+
and linear_bias is not None
|
| 1123 |
+
and linear_bias.requires_grad
|
| 1124 |
+
and grad_enabled
|
| 1125 |
+
):
|
| 1126 |
+
raise RuntimeError(
|
| 1127 |
+
"linear_cross_entropy chunked op: compute_linear_bias_grad was False at "
|
| 1128 |
+
"trace time but linear_bias.requires_grad is True at runtime; recompile "
|
| 1129 |
+
"the graph with the desired requires_grad."
|
| 1130 |
+
)
|
| 1131 |
+
if target.dtype.is_floating_point and target.requires_grad and grad_enabled:
|
| 1132 |
+
# No gradient slot is produced for target; without this guard a
|
| 1133 |
+
# probability target requiring grad would silently get none.
|
| 1134 |
+
raise RuntimeError(
|
| 1135 |
+
"linear_cross_entropy chunked op: gradients w.r.t. a probability "
|
| 1136 |
+
"target are not supported on the chunked path; use options=None."
|
| 1137 |
+
)
|
| 1138 |
+
return _linear_cross_entropy_batch_chunked_accumulator(
|
| 1139 |
+
input,
|
| 1140 |
+
linear_weight,
|
| 1141 |
+
target,
|
| 1142 |
+
linear_bias,
|
| 1143 |
+
weight,
|
| 1144 |
+
reduction,
|
| 1145 |
+
ignore_index,
|
| 1146 |
+
label_smoothing,
|
| 1147 |
+
batch_chunk_size,
|
| 1148 |
+
acc_policy,
|
| 1149 |
+
acc_dtype,
|
| 1150 |
+
compute_input_grad,
|
| 1151 |
+
compute_linear_weight_grad,
|
| 1152 |
+
compute_linear_bias_grad,
|
| 1153 |
+
)
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
# Op arg count; backward returns this many slots. Hand-maintained
|
| 1157 |
+
# because CustomOpDef has no public arg-introspection. Update on
|
| 1158 |
+
# signature change.
|
| 1159 |
+
_NUM_OP_INPUTS = 15
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
@_linear_cross_entropy_batch_chunked.register_fake
|
| 1163 |
+
def _(
|
| 1164 |
+
input,
|
| 1165 |
+
linear_weight,
|
| 1166 |
+
target,
|
| 1167 |
+
linear_bias,
|
| 1168 |
+
weight,
|
| 1169 |
+
reduction,
|
| 1170 |
+
ignore_index,
|
| 1171 |
+
label_smoothing,
|
| 1172 |
+
batch_chunk_size,
|
| 1173 |
+
acc_policy: str,
|
| 1174 |
+
acc_dtype,
|
| 1175 |
+
allow_retain_graph,
|
| 1176 |
+
compute_input_grad,
|
| 1177 |
+
compute_linear_weight_grad,
|
| 1178 |
+
compute_linear_bias_grad,
|
| 1179 |
+
):
|
| 1180 |
+
if reduction in {"mean", "sum"}:
|
| 1181 |
+
result = torch.empty((), dtype=input.dtype, device=input.device)
|
| 1182 |
+
else:
|
| 1183 |
+
raise NotImplementedError(f"linear_cross_entropy does not support {reduction=}")
|
| 1184 |
+
grad_input_shape = input.shape if compute_input_grad else (0, 0)
|
| 1185 |
+
grad_linear_weight_shape = (
|
| 1186 |
+
linear_weight.shape if compute_linear_weight_grad else (0, 0)
|
| 1187 |
+
)
|
| 1188 |
+
# ``linear_bias.shape == linear_weight.shape[:-1]`` (the (C, *out_features)
|
| 1189 |
+
# invariant); on this code path ``out_features == ()`` so it reduces
|
| 1190 |
+
# to (C,), but expressing it this way keeps the relationship visible.
|
| 1191 |
+
grad_linear_bias_shape = (
|
| 1192 |
+
linear_weight.shape[:-1] if compute_linear_bias_grad else (0,)
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
grad_input = torch.empty(
|
| 1196 |
+
grad_input_shape,
|
| 1197 |
+
dtype=input.dtype,
|
| 1198 |
+
device=input.device,
|
| 1199 |
+
requires_grad=False,
|
| 1200 |
+
)
|
| 1201 |
+
# The real implementation allocates ``grad_linear_weight`` and
|
| 1202 |
+
# ``grad_linear_bias`` in ``self.dtype = input.dtype`` (chunked op
|
| 1203 |
+
# supports mixed-precision: ``input.dtype`` may differ from
|
| 1204 |
+
# ``linear_weight.dtype``). Mirror that here so the fake-tensor
|
| 1205 |
+
# shape/dtype matches what eager produces.
|
| 1206 |
+
grad_linear_weight = torch.empty(
|
| 1207 |
+
grad_linear_weight_shape,
|
| 1208 |
+
dtype=input.dtype,
|
| 1209 |
+
device=linear_weight.device,
|
| 1210 |
+
requires_grad=False,
|
| 1211 |
+
)
|
| 1212 |
+
grad_linear_bias = torch.empty(
|
| 1213 |
+
grad_linear_bias_shape,
|
| 1214 |
+
dtype=input.dtype,
|
| 1215 |
+
device=input.device,
|
| 1216 |
+
requires_grad=False,
|
| 1217 |
+
)
|
| 1218 |
+
return result, grad_input, grad_linear_weight, grad_linear_bias
|
| 1219 |
+
|
| 1220 |
+
|
| 1221 |
+
@_linear_cross_entropy_batch_chunked.register_vmap
|
| 1222 |
+
def _vmap(info, in_dims, *args):
|
| 1223 |
+
"""vmap rule (slow path: per-sample Python loop). A fold-into-num_batches
|
| 1224 |
+
fast path is now possible for both ops via the reduction='none' chunked op
|
| 1225 |
+
(``_linear_cross_entropy_batch_chunked_no_reduction``); left as a follow-up.
|
| 1226 |
+
"""
|
| 1227 |
+
batch_size = info.batch_size
|
| 1228 |
+
|
| 1229 |
+
moved_args = [
|
| 1230 |
+
arg.movedim(in_dim, 0)
|
| 1231 |
+
if in_dim is not None and isinstance(arg, torch.Tensor)
|
| 1232 |
+
else arg
|
| 1233 |
+
for arg, in_dim in zip(args, in_dims)
|
| 1234 |
+
]
|
| 1235 |
+
|
| 1236 |
+
outputs = [
|
| 1237 |
+
_linear_cross_entropy_batch_chunked(
|
| 1238 |
+
*[
|
| 1239 |
+
arg[i] if in_dim is not None and isinstance(arg, torch.Tensor) else arg
|
| 1240 |
+
for arg, in_dim in zip(moved_args, in_dims)
|
| 1241 |
+
]
|
| 1242 |
+
)
|
| 1243 |
+
for i in range(batch_size)
|
| 1244 |
+
]
|
| 1245 |
+
losses = torch.stack([o[0] for o in outputs])
|
| 1246 |
+
grad_inputs = torch.stack([o[1] for o in outputs])
|
| 1247 |
+
grad_linear_weights = torch.stack([o[2] for o in outputs])
|
| 1248 |
+
grad_linear_biases = torch.stack([o[3] for o in outputs])
|
| 1249 |
+
return (losses, grad_inputs, grad_linear_weights, grad_linear_biases), (0, 0, 0, 0)
|
| 1250 |
+
|
| 1251 |
+
|
| 1252 |
+
def _linear_cross_entropy_batch_chunked_backward(
|
| 1253 |
+
ctx, grad_output, _gi_grad, _gw_grad, _gb_grad
|
| 1254 |
+
):
|
| 1255 |
+
result = [None] * _NUM_OP_INPUTS
|
| 1256 |
+
# set_materialize_grads(False): grad_output is None when backward is
|
| 1257 |
+
# driven only through the (unsupported) grad outputs -- no gradient
|
| 1258 |
+
# flows through the loss, so none flow to the inputs.
|
| 1259 |
+
if grad_output is None:
|
| 1260 |
+
return tuple(result)
|
| 1261 |
+
if ctx.compute_input_grad:
|
| 1262 |
+
if ctx.allow_retain_graph:
|
| 1263 |
+
result[0] = ctx._gi * grad_output
|
| 1264 |
+
else:
|
| 1265 |
+
gi, ctx._gi = ctx._gi, None
|
| 1266 |
+
if gi is None:
|
| 1267 |
+
raise RuntimeError(
|
| 1268 |
+
"linear_cross_entropy chunked backward called twice; "
|
| 1269 |
+
"retain_graph=True / double backward are not supported."
|
| 1270 |
+
)
|
| 1271 |
+
result[0] = gi.mul_(grad_output)
|
| 1272 |
+
|
| 1273 |
+
if ctx.compute_linear_weight_grad:
|
| 1274 |
+
if ctx.allow_retain_graph:
|
| 1275 |
+
result[1] = ctx._gw * grad_output
|
| 1276 |
+
else:
|
| 1277 |
+
gw, ctx._gw = ctx._gw, None
|
| 1278 |
+
if gw is None:
|
| 1279 |
+
raise RuntimeError(
|
| 1280 |
+
"linear_cross_entropy chunked backward called twice; "
|
| 1281 |
+
"retain_graph=True / double backward are not supported."
|
| 1282 |
+
)
|
| 1283 |
+
result[1] = gw.mul_(grad_output)
|
| 1284 |
+
|
| 1285 |
+
# ``linear_bias`` is forward arg position 3 (after input, linear_weight, target).
|
| 1286 |
+
if ctx.compute_linear_bias_grad:
|
| 1287 |
+
if ctx.allow_retain_graph:
|
| 1288 |
+
result[3] = ctx._gb * grad_output
|
| 1289 |
+
else:
|
| 1290 |
+
gb, ctx._gb = ctx._gb, None
|
| 1291 |
+
if gb is None:
|
| 1292 |
+
raise RuntimeError(
|
| 1293 |
+
"linear_cross_entropy chunked backward called twice; "
|
| 1294 |
+
"retain_graph=True / double backward are not supported."
|
| 1295 |
+
)
|
| 1296 |
+
result[3] = gb.mul_(grad_output)
|
| 1297 |
+
return tuple(result)
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
_linear_cross_entropy_batch_chunked.register_autograd(
|
| 1301 |
+
_linear_cross_entropy_batch_chunked_backward,
|
| 1302 |
+
setup_context=_linear_cross_entropy_batch_chunked_setup_context,
|
| 1303 |
+
)
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
# reduction='none' op. Separate from the scalar-reduction op because the
|
| 1307 |
+
# autograd model differs: per-sample loss makes ``grad_output`` a vector,
|
| 1308 |
+
# so grad_linear_weight / grad_linear_bias cannot be precomputed in forward
|
| 1309 |
+
# (they need the per-sample upstream grad before summing over the batch, and
|
| 1310 |
+
# storing the per-sample (N, V) softmax would defeat chunking). Instead the
|
| 1311 |
+
# forward returns only the loss and saves its inputs; backward recomputes the
|
| 1312 |
+
# chunked grads with ``grad_output`` folded into ``weight_chunk`` (both share
|
| 1313 |
+
# ``_linear_cross_entropy_batch_chunked_accumulator``). Peak memory stays bounded to
|
| 1314 |
+
# (batch_chunk_size, num_classes); the cost is one recomputed logits matmul
|
| 1315 |
+
# per chunk in backward. Recompute-from-saved-inputs supports retain_graph
|
| 1316 |
+
# naturally (no consumed buffers), so no allow_retain_graph flag is needed.
|
| 1317 |
+
@torch.library.custom_op(
|
| 1318 |
+
"torch_nn::_linear_cross_entropy_batch_chunked_no_reduction", mutates_args=()
|
| 1319 |
+
)
|
| 1320 |
+
def _linear_cross_entropy_batch_chunked_no_reduction(
|
| 1321 |
+
input: torch.Tensor,
|
| 1322 |
+
linear_weight: torch.Tensor,
|
| 1323 |
+
target: torch.Tensor,
|
| 1324 |
+
linear_bias: torch.Tensor | None,
|
| 1325 |
+
weight: torch.Tensor | None,
|
| 1326 |
+
ignore_index: int,
|
| 1327 |
+
batch_chunk_size: int,
|
| 1328 |
+
acc_policy: str,
|
| 1329 |
+
acc_dtype: torch.dtype,
|
| 1330 |
+
) -> torch.Tensor:
|
| 1331 |
+
"""reduction='none' chunked forward: returns per-sample loss ``(N,)``.
|
| 1332 |
+
|
| 1333 |
+
Gradients are not precomputed (the per-sample upstream grad is
|
| 1334 |
+
unknown at forward); the accumulator's loss-only branch runs here,
|
| 1335 |
+
and the backward recomputes the chunked grads. See
|
| 1336 |
+
``_linear_cross_entropy_batch_chunked_accumulator``.
|
| 1337 |
+
"""
|
| 1338 |
+
# loss_grad_output=None -> the accumulator's reduction='none' forward
|
| 1339 |
+
# (loss-only) branch; compute_*=False since nothing is precomputed.
|
| 1340 |
+
return _linear_cross_entropy_batch_chunked_accumulator(
|
| 1341 |
+
input,
|
| 1342 |
+
linear_weight,
|
| 1343 |
+
target,
|
| 1344 |
+
linear_bias,
|
| 1345 |
+
weight,
|
| 1346 |
+
"none",
|
| 1347 |
+
ignore_index,
|
| 1348 |
+
0.0,
|
| 1349 |
+
batch_chunk_size,
|
| 1350 |
+
acc_policy,
|
| 1351 |
+
acc_dtype,
|
| 1352 |
+
compute_input_grad=False,
|
| 1353 |
+
compute_linear_weight_grad=False,
|
| 1354 |
+
compute_linear_bias_grad=False,
|
| 1355 |
+
)[0]
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def _linear_cross_entropy_batch_chunked_no_reduction_setup_context(ctx, inputs, output):
|
| 1359 |
+
(
|
| 1360 |
+
input,
|
| 1361 |
+
linear_weight,
|
| 1362 |
+
target,
|
| 1363 |
+
linear_bias,
|
| 1364 |
+
weight,
|
| 1365 |
+
ignore_index,
|
| 1366 |
+
batch_chunk_size,
|
| 1367 |
+
acc_policy,
|
| 1368 |
+
acc_dtype,
|
| 1369 |
+
) = inputs
|
| 1370 |
+
# Detach before saving: the backward recomputes the grads analytically
|
| 1371 |
+
# from these values (it does not differentiate through them), and saving
|
| 1372 |
+
# ``linear_weight`` -- a differentiable ``reshape`` view of the
|
| 1373 |
+
# ``nn.Linear`` weight -- would make its SavedVariable retain the base
|
| 1374 |
+
# parameter, inflating its use_count past backward and breaking
|
| 1375 |
+
# swap-based ``module.to()`` (the custom-op node keeps saved tensors
|
| 1376 |
+
# alive while the loss output is still referenced).
|
| 1377 |
+
ctx.save_for_backward(
|
| 1378 |
+
input.detach(),
|
| 1379 |
+
linear_weight.detach(),
|
| 1380 |
+
target,
|
| 1381 |
+
linear_bias.detach() if linear_bias is not None else None,
|
| 1382 |
+
weight.detach() if weight is not None else None,
|
| 1383 |
+
)
|
| 1384 |
+
ctx._ignore_index = ignore_index
|
| 1385 |
+
ctx._batch_chunk_size = batch_chunk_size
|
| 1386 |
+
ctx._acc_policy = acc_policy
|
| 1387 |
+
ctx._acc_dtype = acc_dtype
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
@_linear_cross_entropy_batch_chunked_no_reduction.register_fake
|
| 1391 |
+
def _(
|
| 1392 |
+
input,
|
| 1393 |
+
linear_weight,
|
| 1394 |
+
target,
|
| 1395 |
+
linear_bias,
|
| 1396 |
+
weight,
|
| 1397 |
+
ignore_index,
|
| 1398 |
+
batch_chunk_size,
|
| 1399 |
+
acc_policy: str,
|
| 1400 |
+
acc_dtype,
|
| 1401 |
+
):
|
| 1402 |
+
return torch.empty(
|
| 1403 |
+
input.shape[:1], dtype=input.dtype, device=input.device, requires_grad=False
|
| 1404 |
+
)
|
| 1405 |
+
|
| 1406 |
+
|
| 1407 |
+
@_linear_cross_entropy_batch_chunked_no_reduction.register_vmap
|
| 1408 |
+
def _vmap_no_reduction(info, in_dims, *args):
|
| 1409 |
+
"""vmap rule (slow path: per-sample Python loop, mirrors the
|
| 1410 |
+
scalar-reduction op). Stacks the per-sample ``(N,)`` losses.
|
| 1411 |
+
"""
|
| 1412 |
+
batch_size = info.batch_size
|
| 1413 |
+
moved_args = [
|
| 1414 |
+
arg.movedim(in_dim, 0)
|
| 1415 |
+
if in_dim is not None and isinstance(arg, torch.Tensor)
|
| 1416 |
+
else arg
|
| 1417 |
+
for arg, in_dim in zip(args, in_dims)
|
| 1418 |
+
]
|
| 1419 |
+
outputs = [
|
| 1420 |
+
_linear_cross_entropy_batch_chunked_no_reduction(
|
| 1421 |
+
*[
|
| 1422 |
+
arg[i] if in_dim is not None and isinstance(arg, torch.Tensor) else arg
|
| 1423 |
+
for arg, in_dim in zip(moved_args, in_dims)
|
| 1424 |
+
]
|
| 1425 |
+
)
|
| 1426 |
+
for i in range(batch_size)
|
| 1427 |
+
]
|
| 1428 |
+
return torch.stack(outputs), 0
|
| 1429 |
+
|
| 1430 |
+
|
| 1431 |
+
def _linear_cross_entropy_batch_chunked_no_reduction_backward(ctx, grad_output):
|
| 1432 |
+
# grad_output is the per-sample upstream grad (N,). Forward arg order:
|
| 1433 |
+
# (input, linear_weight, target, linear_bias, weight, ignore_index,
|
| 1434 |
+
# batch_chunk_size, acc_policy, acc_dtype).
|
| 1435 |
+
input, linear_weight, target, linear_bias, weight = ctx.saved_tensors
|
| 1436 |
+
needs = ctx.needs_input_grad
|
| 1437 |
+
compute_input_grad = needs[0]
|
| 1438 |
+
compute_linear_weight_grad = needs[1]
|
| 1439 |
+
compute_linear_bias_grad = linear_bias is not None and needs[3]
|
| 1440 |
+
result: list[torch.Tensor | None] = [None] * 9
|
| 1441 |
+
if not (
|
| 1442 |
+
compute_input_grad or compute_linear_weight_grad or compute_linear_bias_grad
|
| 1443 |
+
):
|
| 1444 |
+
return tuple(result)
|
| 1445 |
+
# loss_grad_output=grad_output -> the accumulator's grad loop with the
|
| 1446 |
+
# per-sample upstream grad folded into neg_weight_target (the "none"
|
| 1447 |
+
# backward path), recomputing the chunked grads as the VJP. The loss
|
| 1448 |
+
# (result[0]) it also returns is the meaningless scalar and dropped.
|
| 1449 |
+
_, grad_input, grad_linear_weight, grad_linear_bias = (
|
| 1450 |
+
_linear_cross_entropy_batch_chunked_accumulator(
|
| 1451 |
+
input,
|
| 1452 |
+
linear_weight,
|
| 1453 |
+
target,
|
| 1454 |
+
linear_bias,
|
| 1455 |
+
weight,
|
| 1456 |
+
"none",
|
| 1457 |
+
ctx._ignore_index,
|
| 1458 |
+
0.0, # label_smoothing
|
| 1459 |
+
ctx._batch_chunk_size,
|
| 1460 |
+
ctx._acc_policy,
|
| 1461 |
+
ctx._acc_dtype,
|
| 1462 |
+
compute_input_grad,
|
| 1463 |
+
compute_linear_weight_grad,
|
| 1464 |
+
compute_linear_bias_grad,
|
| 1465 |
+
loss_grad_output=grad_output,
|
| 1466 |
+
)
|
| 1467 |
+
)
|
| 1468 |
+
if compute_input_grad:
|
| 1469 |
+
result[0] = grad_input
|
| 1470 |
+
if compute_linear_weight_grad:
|
| 1471 |
+
result[1] = grad_linear_weight
|
| 1472 |
+
if compute_linear_bias_grad:
|
| 1473 |
+
result[3] = grad_linear_bias
|
| 1474 |
+
return tuple(result)
|
| 1475 |
+
|
| 1476 |
+
|
| 1477 |
+
_linear_cross_entropy_batch_chunked_no_reduction.register_autograd(
|
| 1478 |
+
_linear_cross_entropy_batch_chunked_no_reduction_backward,
|
| 1479 |
+
setup_context=_linear_cross_entropy_batch_chunked_no_reduction_setup_context,
|
| 1480 |
+
)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/linear_cross_entropy_options.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
from typing import Literal
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["LinearCrossEntropyOptions"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
_VALID_ACC_POLICIES = ("auto", "accurate", "compact")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _auto_acc_policy(device_type: str | None, dtype: torch.dtype) -> str:
|
| 14 |
+
"""Resolve the ``acc_policy`` ``"auto"`` sentinel from device and dtype.
|
| 15 |
+
|
| 16 |
+
Only CPU + low-precision input (fp16/bf16) picks ``"accurate"``: there
|
| 17 |
+
``compact`` runs the weight-grad GEMM in the input dtype,
|
| 18 |
+
hitting CPU's emulated low-precision matmul (~20-50x slower), so
|
| 19 |
+
``"accurate"`` keeps it in fp32. Everything else picks ``"compact"`` --
|
| 20 |
+
accelerators have hardware-native low-precision GEMMs, and for fp32/fp64
|
| 21 |
+
the GEMM is native at any policy (``"accurate"`` would only add a
|
| 22 |
+
weight-grad scratch, no benefit).
|
| 23 |
+
"""
|
| 24 |
+
if device_type == "cpu" and dtype in (torch.float16, torch.bfloat16):
|
| 25 |
+
return "accurate"
|
| 26 |
+
return "compact"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclasses.dataclass(slots=True, frozen=True)
|
| 30 |
+
class LinearCrossEntropyOptions:
|
| 31 |
+
"""Configuration for the chunked implementation of
|
| 32 |
+
:func:`linear_cross_entropy`.
|
| 33 |
+
|
| 34 |
+
The chunked implementation processes the batch dimension in pieces, so
|
| 35 |
+
the full ``(num_batches, num_classes)`` logits tensor is never
|
| 36 |
+
materialized -- useful when ``num_classes`` is much larger than
|
| 37 |
+
``in_features`` (e.g. LLM vocabulary heads). Pass ``options=None`` to
|
| 38 |
+
use the reference path; pass an instance of this class to opt in.
|
| 39 |
+
|
| 40 |
+
Zero-argument ``LinearCrossEntropyOptions()`` leaves :attr:`acc_policy`
|
| 41 |
+
and :attr:`chunking_method` at ``"auto"``, resolved per (device, dtype) at
|
| 42 |
+
call time -- see the field docs below.
|
| 43 |
+
|
| 44 |
+
Supports a subset of :func:`linear_cross_entropy`; unsupported
|
| 45 |
+
configurations fall through to the reference path with a warning.
|
| 46 |
+
|
| 47 |
+
Chunking is a win when ``num_batches >= in_features`` and
|
| 48 |
+
``num_classes > in_features``; below that, the reference path is
|
| 49 |
+
cheaper.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
allow_retain_graph: bool = False
|
| 53 |
+
"""Allow ``retain_graph=True`` on backward. Applies only to the scalar
|
| 54 |
+
reductions (``"mean"`` / ``"sum"``).
|
| 55 |
+
|
| 56 |
+
When ``False`` (default), their backward consumes pre-computed gradient
|
| 57 |
+
buffers in place; a second ``.backward()`` raises ``RuntimeError``.
|
| 58 |
+
|
| 59 |
+
When ``True``, the buffers are preserved at the cost of one extra
|
| 60 |
+
gradient-sized allocation per call.
|
| 61 |
+
|
| 62 |
+
``reduction="none"`` ignores this field: its backward recomputes the
|
| 63 |
+
chunked gradients from the saved inputs, so ``retain_graph=True`` works
|
| 64 |
+
unconditionally with no extra allocation.
|
| 65 |
+
|
| 66 |
+
Higher-order autograd (gradgrad, forward-mode AD) is unsupported.
|
| 67 |
+
|
| 68 |
+
Under :func:`torch.compile` this field is auto-promoted to ``True`` for
|
| 69 |
+
the scalar reductions because the default-mode second-backward guard
|
| 70 |
+
relies on a ctx mutation Dynamo doesn't preserve; the wrapper warns on
|
| 71 |
+
the promotion.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
batch_chunk_size: int | None = None
|
| 75 |
+
"""Batch rows per chunk. The op loops over
|
| 76 |
+
``ceil(num_batches / batch_chunk_size)`` chunks; smaller values cut
|
| 77 |
+
peak memory but launch more kernels. Default ``None`` means a single
|
| 78 |
+
chunk. Cannot be combined with :attr:`chunking_method` -- if both are
|
| 79 |
+
set and disagree, ``ValueError`` is raised.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
chunking_method: str | None = "auto"
|
| 83 |
+
"""Heuristic for picking :attr:`batch_chunk_size`.
|
| 84 |
+
|
| 85 |
+
- ``"auto"`` (default) -- resolves to ``"aspect_ratio"`` (factor 1),
|
| 86 |
+
with the compact path additionally capped at a per-target ``B_ref``
|
| 87 |
+
in :meth:`_adjust` so the chunked peak never exceeds the unchunked
|
| 88 |
+
reference in the budget regime (``in_features >= num_classes``).
|
| 89 |
+
- ``"aspect_ratio"`` -- sizes each chunk so its
|
| 90 |
+
``(batch_chunk_size, num_classes)`` logits buffer matches the
|
| 91 |
+
``(num_batches, in_features)`` input in memory:
|
| 92 |
+
``next_pow2(ceil(num_batches / ceil(num_classes / in_features)))``.
|
| 93 |
+
Best when ``num_classes >> in_features`` (LLM vocab heads).
|
| 94 |
+
- ``"aspect_ratio:N"`` (``N >= 1``) -- same, divided by ``N``.
|
| 95 |
+
~N times less peak memory at the cost of N times more chunks.
|
| 96 |
+
- ``None`` -- disables the heuristic; uses :attr:`batch_chunk_size`.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
acc_policy: Literal[
|
| 100 |
+
"accurate",
|
| 101 |
+
"compact",
|
| 102 |
+
"auto",
|
| 103 |
+
] = "auto"
|
| 104 |
+
"""Precision/memory trade-off for the chunked path. Controls which
|
| 105 |
+
intermediates are kept in :attr:`acc_dtype` vs. the input dtype, and
|
| 106 |
+
whether the per-chunk weight-gradient scratch buffer is materialized.
|
| 107 |
+
|
| 108 |
+
- ``"auto"`` (default) -- ``"accurate"`` for CPU low-precision input
|
| 109 |
+
(fp16/bf16), ``"compact"`` otherwise (:func:`_auto_acc_policy`). Pass
|
| 110 |
+
``"accurate"`` explicitly on any other backend that emulates fp16/bf16
|
| 111 |
+
GEMMs via fp32 upcast.
|
| 112 |
+
- ``"accurate"`` -- broadest use of :attr:`acc_dtype`; noticeably
|
| 113 |
+
better input-grad accuracy when chunk size is large relative to
|
| 114 |
+
``num_classes``. Highest peak memory and slowest of the chunked
|
| 115 |
+
policies on CUDA. Only chunked policy whose weight-grad matmul
|
| 116 |
+
runs in fp32 on CPU (other policies hit CPU's emulated
|
| 117 |
+
low-precision path, ~20-50x slower).
|
| 118 |
+
- ``"compact"`` -- :attr:`acc_dtype` only where needed for gradient
|
| 119 |
+
correctness; accumulates the weight gradient per chunk directly via
|
| 120 |
+
``addmm_`` instead of a ``(num_classes, in_features)``
|
| 121 |
+
:attr:`acc_dtype` scratch (on CUDA cuBLAS uses an fp32 internal
|
| 122 |
+
accumulator, so bulk precision is unchanged). Saves
|
| 123 |
+
``num_classes * in_features * sizeof(acc_dtype)`` -- typically
|
| 124 |
+
several hundred MB for an LLM head. On non-CUDA mixed-precision it
|
| 125 |
+
retains that scratch for the cross-chunk accumulation.
|
| 126 |
+
|
| 127 |
+
The precision difference between ``"compact"`` and ``"accurate"`` is
|
| 128 |
+
visible only when :attr:`acc_dtype` differs from the input dtype;
|
| 129 |
+
``"compact"`` saves memory in both regimes.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
acc_dtype: torch.dtype | None = None
|
| 133 |
+
"""Dtype for internal accumulation. ``None`` resolves at call time
|
| 134 |
+
to ``torch.float32`` under ``acc_policy="auto"`` with fp16/bf16
|
| 135 |
+
input on hardware with mixed-precision mm (CUDA SM 7.0+ for fp16,
|
| 136 |
+
SM 8.0+ for bf16, and CPU); otherwise to the input dtype.
|
| 137 |
+
Mixed-precision currently requires fp16/bf16 input with
|
| 138 |
+
``acc_dtype=torch.float32``.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
def __post_init__(self):
|
| 142 |
+
if self.acc_policy not in _VALID_ACC_POLICIES:
|
| 143 |
+
raise ValueError(
|
| 144 |
+
f"invalid acc_policy: {self.acc_policy!r}; expected one of "
|
| 145 |
+
f"{', '.join(map(repr, _VALID_ACC_POLICIES))}"
|
| 146 |
+
)
|
| 147 |
+
if self.chunking_method is not None and self.chunking_method != "auto":
|
| 148 |
+
name, sep, factor = self.chunking_method.partition(":")
|
| 149 |
+
if not sep:
|
| 150 |
+
factor = "1"
|
| 151 |
+
if not (name == "aspect_ratio" and factor.isdigit() and int(factor) > 0):
|
| 152 |
+
raise ValueError(f"invalid chunking_method: {self.chunking_method!r}")
|
| 153 |
+
if not (
|
| 154 |
+
self.batch_chunk_size is None
|
| 155 |
+
or (isinstance(self.batch_chunk_size, int) and self.batch_chunk_size > 0)
|
| 156 |
+
):
|
| 157 |
+
raise ValueError(
|
| 158 |
+
f"batch_chunk_size must be positive int or None, got {self.batch_chunk_size!r}"
|
| 159 |
+
)
|
| 160 |
+
# fp64 is allowed for the internal ``_adjust`` path (fp64 inputs).
|
| 161 |
+
_SUPPORTED_ACC_DTYPES = {
|
| 162 |
+
torch.float16,
|
| 163 |
+
torch.bfloat16,
|
| 164 |
+
torch.float32,
|
| 165 |
+
torch.float64,
|
| 166 |
+
}
|
| 167 |
+
if self.acc_dtype is not None and self.acc_dtype not in _SUPPORTED_ACC_DTYPES:
|
| 168 |
+
raise ValueError(
|
| 169 |
+
f"acc_dtype must be one of {{None, torch.float16, torch.bfloat16, "
|
| 170 |
+
f"torch.float32, torch.float64}}, got {self.acc_dtype!r}. Pass "
|
| 171 |
+
"acc_dtype=None to let the op pick automatically."
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
@staticmethod
|
| 175 |
+
def _ceil_div(a: int, b: int) -> int:
|
| 176 |
+
"""ceil(a / b) for non-negative integers."""
|
| 177 |
+
return -(-a // b)
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def _resolve_auto_acc_dtype(
|
| 181 |
+
dtype: torch.dtype, device: torch.device | None
|
| 182 |
+
) -> torch.dtype | None:
|
| 183 |
+
"""Return fp32 for fp16/bf16 input on hardware with a working
|
| 184 |
+
mixed-precision mm path (CUDA SM 7.0+ for fp16, SM 8.0+ for bf16,
|
| 185 |
+
and CPU); ``None`` otherwise (caller falls back to input dtype).
|
| 186 |
+
"""
|
| 187 |
+
if device is None or dtype not in (torch.float16, torch.bfloat16):
|
| 188 |
+
return None
|
| 189 |
+
if device.type == "cuda":
|
| 190 |
+
if not torch.cuda.is_available():
|
| 191 |
+
return None
|
| 192 |
+
major, _ = torch.cuda.get_device_capability(device)
|
| 193 |
+
if dtype == torch.bfloat16 and major < 8:
|
| 194 |
+
return None
|
| 195 |
+
if dtype == torch.float16 and major < 7:
|
| 196 |
+
return None
|
| 197 |
+
return torch.float32
|
| 198 |
+
if device.type == "cpu":
|
| 199 |
+
return torch.float32
|
| 200 |
+
return None
|
| 201 |
+
|
| 202 |
+
def _compute_batch_chunk_size(
|
| 203 |
+
self,
|
| 204 |
+
num_batches: int,
|
| 205 |
+
in_features: int,
|
| 206 |
+
num_classes: int,
|
| 207 |
+
method: str | None = None,
|
| 208 |
+
) -> int:
|
| 209 |
+
"""Compute batch_chunk_size from chunking_method given input shapes.
|
| 210 |
+
|
| 211 |
+
Pass ``method`` to use a post-``_adjust`` resolved value (e.g. when
|
| 212 |
+
``self.chunking_method == "auto"``); otherwise uses ``self.chunking_method``.
|
| 213 |
+
To add a method: extend the if/elif chain plus ``__post_init__`` validation.
|
| 214 |
+
"""
|
| 215 |
+
method = str(method if method is not None else self.chunking_method)
|
| 216 |
+
|
| 217 |
+
if method.startswith("aspect_ratio"):
|
| 218 |
+
factor = int(method.split(":", 1)[1]) if ":" in method else 1
|
| 219 |
+
# See LinearCrossEntropyOptions.chunking_method docstring.
|
| 220 |
+
inc_factor = self._ceil_div(num_classes, in_features)
|
| 221 |
+
target = self._ceil_div(num_batches, inc_factor)
|
| 222 |
+
chunk_size = 1 << (target - 1).bit_length() # next power of 2 >= target
|
| 223 |
+
return min(chunk_size // factor, num_batches)
|
| 224 |
+
|
| 225 |
+
# __post_init__ validates the method, so this is unreachable.
|
| 226 |
+
raise AssertionError(f"unhandled chunking_method: {method!r}")
|
| 227 |
+
|
| 228 |
+
def _adjust(
|
| 229 |
+
self,
|
| 230 |
+
num_batches,
|
| 231 |
+
in_features,
|
| 232 |
+
num_classes,
|
| 233 |
+
dtype,
|
| 234 |
+
device=None,
|
| 235 |
+
prob_target=False,
|
| 236 |
+
):
|
| 237 |
+
"""Resolve ``"auto"`` sentinels and ``None`` defaults against a
|
| 238 |
+
specific call site; returns a fully concrete options instance.
|
| 239 |
+
|
| 240 |
+
Internal API consumed by ``F.linear_cross_entropy``'s chunked
|
| 241 |
+
dispatch and a handful of test call sites. ``device=None`` forces the
|
| 242 |
+
``"compact"`` fallback instead of the per-device acc_policy pick.
|
| 243 |
+
``prob_target`` selects the per-target memory cap (``N/2`` vs
|
| 244 |
+
``N*V/4D``).
|
| 245 |
+
"""
|
| 246 |
+
acc_policy = self.acc_policy
|
| 247 |
+
chunking_method = self.chunking_method
|
| 248 |
+
chunking_was_auto = chunking_method == "auto"
|
| 249 |
+
# Honour an explicit batch_chunk_size by disabling auto chunking
|
| 250 |
+
# (it would conflict with the user's size); acc_policy="auto" is
|
| 251 |
+
# unaffected.
|
| 252 |
+
if chunking_method == "auto" and self.batch_chunk_size is not None:
|
| 253 |
+
chunking_method = None
|
| 254 |
+
if acc_policy == "auto":
|
| 255 |
+
acc_policy = _auto_acc_policy(
|
| 256 |
+
device.type if device is not None else None, dtype
|
| 257 |
+
)
|
| 258 |
+
if chunking_method == "auto":
|
| 259 |
+
chunking_method = "aspect_ratio"
|
| 260 |
+
|
| 261 |
+
if self.batch_chunk_size is None:
|
| 262 |
+
batch_chunk_size = num_batches
|
| 263 |
+
else:
|
| 264 |
+
batch_chunk_size = min(self.batch_chunk_size, num_batches)
|
| 265 |
+
|
| 266 |
+
if chunking_method is not None:
|
| 267 |
+
batch_chunk_size = self._compute_batch_chunk_size(
|
| 268 |
+
num_batches,
|
| 269 |
+
in_features,
|
| 270 |
+
num_classes,
|
| 271 |
+
chunking_method,
|
| 272 |
+
)
|
| 273 |
+
# Memory cap for the auto compact path. aspect_ratio degenerates to
|
| 274 |
+
# a single chunk when in_features >= num_classes, where the chunked
|
| 275 |
+
# peak exceeds the unchunked reference. ``b_ref`` is the largest
|
| 276 |
+
# chunk staying at or below reference -- ``N*V/(4*D)`` for index
|
| 277 |
+
# targets, ``N/2`` for prob (whose reference also materializes the
|
| 278 |
+
# soft target, so the single-chunk excess clears with two chunks);
|
| 279 |
+
# both device- and dtype-independent. Floored to a power of two so
|
| 280 |
+
# the cap never lands above ``b_ref``.
|
| 281 |
+
if chunking_was_auto and acc_policy == "compact":
|
| 282 |
+
if prob_target:
|
| 283 |
+
b_ref = num_batches // 2
|
| 284 |
+
else:
|
| 285 |
+
b_ref = num_batches * num_classes // (4 * in_features)
|
| 286 |
+
b_ref = 1 << (b_ref.bit_length() - 1) if b_ref >= 1 else 1
|
| 287 |
+
batch_chunk_size = max(1, min(batch_chunk_size, b_ref))
|
| 288 |
+
if (
|
| 289 |
+
self.batch_chunk_size is not None
|
| 290 |
+
and self.batch_chunk_size != batch_chunk_size
|
| 291 |
+
):
|
| 292 |
+
raise ValueError(
|
| 293 |
+
f"batch_chunk_size (={self.batch_chunk_size}) and "
|
| 294 |
+
f"chunking_method ('{chunking_method}') give different "
|
| 295 |
+
f"chunk sizes ({self.batch_chunk_size} vs {batch_chunk_size}); "
|
| 296 |
+
f"pass only one."
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if self.acc_dtype is None:
|
| 300 |
+
# Under "auto" prefer fp32 on hardware that supports the
|
| 301 |
+
# mixed-precision mm path; otherwise fall back to input dtype.
|
| 302 |
+
auto_acc = (
|
| 303 |
+
self._resolve_auto_acc_dtype(dtype, device)
|
| 304 |
+
if self.acc_policy == "auto"
|
| 305 |
+
else None
|
| 306 |
+
)
|
| 307 |
+
acc_dtype = auto_acc if auto_acc is not None else dtype
|
| 308 |
+
else:
|
| 309 |
+
acc_dtype = self.acc_dtype
|
| 310 |
+
return dataclasses.replace(
|
| 311 |
+
self,
|
| 312 |
+
acc_policy=acc_policy,
|
| 313 |
+
chunking_method=chunking_method,
|
| 314 |
+
batch_chunk_size=max(1, batch_chunk_size),
|
| 315 |
+
acc_dtype=acc_dtype,
|
| 316 |
+
)
|
.venv/lib/python3.12/site-packages/torch/nn/modules/loss.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/module.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.venv/lib/python3.12/site-packages/torch/nn/modules/normalization.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import numbers
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch import Size, Tensor
|
| 6 |
+
from torch.nn import functional as F, init
|
| 7 |
+
from torch.nn.parameter import Parameter
|
| 8 |
+
|
| 9 |
+
from ._functions import CrossMapLRN2d as _cross_map_lrn2d
|
| 10 |
+
from .module import Module
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
__all__ = ["LocalResponseNorm", "CrossMapLRN2d", "LayerNorm", "GroupNorm", "RMSNorm"]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LocalResponseNorm(Module):
|
| 17 |
+
r"""Applies local response normalization over an input signal.
|
| 18 |
+
|
| 19 |
+
The input signal is composed of several input planes, where channels occupy the second dimension.
|
| 20 |
+
Applies normalization across channels.
|
| 21 |
+
|
| 22 |
+
.. math::
|
| 23 |
+
b_{c} = a_{c}\left(k + \frac{\alpha}{n}
|
| 24 |
+
\sum_{c'=\max(0, c-n/2)}^{\min(N-1,c+n/2)}a_{c'}^2\right)^{-\beta}
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
size: amount of neighbouring channels used for normalization
|
| 28 |
+
alpha: multiplicative factor. Default: 0.0001
|
| 29 |
+
beta: exponent. Default: 0.75
|
| 30 |
+
k: additive factor. Default: 1
|
| 31 |
+
|
| 32 |
+
Shape:
|
| 33 |
+
- Input: :math:`(N, C, *)`
|
| 34 |
+
- Output: :math:`(N, C, *)` (same shape as input)
|
| 35 |
+
|
| 36 |
+
Examples::
|
| 37 |
+
|
| 38 |
+
>>> lrn = nn.LocalResponseNorm(2)
|
| 39 |
+
>>> signal_2d = torch.randn(32, 5, 24, 24)
|
| 40 |
+
>>> signal_4d = torch.randn(16, 5, 7, 7, 7, 7)
|
| 41 |
+
>>> output_2d = lrn(signal_2d)
|
| 42 |
+
>>> output_4d = lrn(signal_4d)
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
__constants__ = ["size", "alpha", "beta", "k"]
|
| 47 |
+
size: int
|
| 48 |
+
alpha: float
|
| 49 |
+
beta: float
|
| 50 |
+
k: float
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self, size: int, alpha: float = 1e-4, beta: float = 0.75, k: float = 1.0
|
| 54 |
+
) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.size = size
|
| 57 |
+
self.alpha = alpha
|
| 58 |
+
self.beta = beta
|
| 59 |
+
self.k = k
|
| 60 |
+
|
| 61 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 62 |
+
"""
|
| 63 |
+
Runs the forward pass.
|
| 64 |
+
"""
|
| 65 |
+
return F.local_response_norm(input, self.size, self.alpha, self.beta, self.k)
|
| 66 |
+
|
| 67 |
+
def extra_repr(self):
|
| 68 |
+
"""
|
| 69 |
+
Return the extra representation of the module.
|
| 70 |
+
"""
|
| 71 |
+
return "{size}, alpha={alpha}, beta={beta}, k={k}".format(**self.__dict__)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class CrossMapLRN2d(Module):
|
| 75 |
+
size: int
|
| 76 |
+
alpha: float
|
| 77 |
+
beta: float
|
| 78 |
+
k: float
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self, size: int, alpha: float = 1e-4, beta: float = 0.75, k: float = 1
|
| 82 |
+
) -> None:
|
| 83 |
+
super().__init__()
|
| 84 |
+
self.size = size
|
| 85 |
+
self.alpha = alpha
|
| 86 |
+
self.beta = beta
|
| 87 |
+
self.k = k
|
| 88 |
+
|
| 89 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 90 |
+
"""
|
| 91 |
+
Runs the forward pass.
|
| 92 |
+
"""
|
| 93 |
+
return _cross_map_lrn2d.apply(input, self.size, self.alpha, self.beta, self.k)
|
| 94 |
+
|
| 95 |
+
def extra_repr(self) -> str:
|
| 96 |
+
"""
|
| 97 |
+
Return the extra representation of the module.
|
| 98 |
+
"""
|
| 99 |
+
return "{size}, alpha={alpha}, beta={beta}, k={k}".format(**self.__dict__)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
_shape_t = int | list[int] | Size
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class LayerNorm(Module):
|
| 106 |
+
r"""Applies Layer Normalization over a mini-batch of inputs.
|
| 107 |
+
|
| 108 |
+
This layer implements the operation as described in
|
| 109 |
+
the paper `Layer Normalization <https://arxiv.org/abs/1607.06450>`__
|
| 110 |
+
|
| 111 |
+
.. math::
|
| 112 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 113 |
+
|
| 114 |
+
The mean and standard-deviation are calculated over the last `D` dimensions, where `D`
|
| 115 |
+
is the dimension of :attr:`normalized_shape`. For example, if :attr:`normalized_shape`
|
| 116 |
+
is ``(3, 5)`` (a 2-dimensional shape), the mean and standard-deviation are computed over
|
| 117 |
+
the last 2 dimensions of the input (i.e. ``input.mean((-2, -1))``).
|
| 118 |
+
:math:`\gamma` and :math:`\beta` are learnable affine transform parameters of
|
| 119 |
+
:attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``.
|
| 120 |
+
The variance is calculated via the biased estimator, equivalent to
|
| 121 |
+
`torch.var(input, correction=0)`.
|
| 122 |
+
|
| 123 |
+
.. note::
|
| 124 |
+
Unlike Batch Normalization and Instance Normalization, which applies
|
| 125 |
+
scalar scale and bias for each entire channel/plane with the
|
| 126 |
+
:attr:`affine` option, Layer Normalization applies per-element scale and
|
| 127 |
+
bias with :attr:`elementwise_affine`.
|
| 128 |
+
|
| 129 |
+
This layer uses statistics computed from input data in both training and
|
| 130 |
+
evaluation modes.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
normalized_shape (int or list or torch.Size): input shape from an expected input
|
| 134 |
+
of size
|
| 135 |
+
|
| 136 |
+
.. math::
|
| 137 |
+
[* \times \text{normalized\_shape}[0] \times \text{normalized\_shape}[1]
|
| 138 |
+
\times \ldots \times \text{normalized\_shape}[-1]]
|
| 139 |
+
|
| 140 |
+
If a single integer is used, it is treated as a singleton list, and this module will
|
| 141 |
+
normalize over the last dimension which is expected to be of that specific size.
|
| 142 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 143 |
+
elementwise_affine: a boolean value that when set to ``True``, this module
|
| 144 |
+
has learnable per-element affine parameters initialized to ones (for weights)
|
| 145 |
+
and zeros (for biases). Default: ``True``
|
| 146 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 147 |
+
:attr:`elementwise_affine` is ``True``). Default: ``True``
|
| 148 |
+
|
| 149 |
+
Attributes:
|
| 150 |
+
weight: the learnable weights of the module of shape
|
| 151 |
+
:math:`\text{normalized\_shape}` when :attr:`elementwise_affine` is set to ``True``.
|
| 152 |
+
The values are initialized to 1.
|
| 153 |
+
bias: the learnable bias of the module of shape
|
| 154 |
+
:math:`\text{normalized\_shape}` when :attr:`elementwise_affine` is set to ``True``.
|
| 155 |
+
The values are initialized to 0.
|
| 156 |
+
|
| 157 |
+
Shape:
|
| 158 |
+
- Input: :math:`(N, *)`
|
| 159 |
+
- Output: :math:`(N, *)` (same shape as input)
|
| 160 |
+
|
| 161 |
+
Examples::
|
| 162 |
+
|
| 163 |
+
>>> # NLP Example
|
| 164 |
+
>>> batch, sentence_length, embedding_dim = 20, 5, 10
|
| 165 |
+
>>> embedding = torch.randn(batch, sentence_length, embedding_dim)
|
| 166 |
+
>>> layer_norm = nn.LayerNorm(embedding_dim)
|
| 167 |
+
>>> # Activate module
|
| 168 |
+
>>> layer_norm(embedding)
|
| 169 |
+
>>>
|
| 170 |
+
>>> # Image Example
|
| 171 |
+
>>> N, C, H, W = 20, 5, 10, 10
|
| 172 |
+
>>> input = torch.randn(N, C, H, W)
|
| 173 |
+
>>> # Normalize over the last three dimensions (i.e. the channel and spatial dimensions)
|
| 174 |
+
>>> # as shown in the image below
|
| 175 |
+
>>> layer_norm = nn.LayerNorm([C, H, W])
|
| 176 |
+
>>> output = layer_norm(input)
|
| 177 |
+
|
| 178 |
+
.. image:: ../_static/img/nn/layer_norm.jpg
|
| 179 |
+
:scale: 50 %
|
| 180 |
+
|
| 181 |
+
"""
|
| 182 |
+
|
| 183 |
+
__constants__ = ["normalized_shape", "eps", "elementwise_affine"]
|
| 184 |
+
normalized_shape: tuple[int, ...]
|
| 185 |
+
eps: float
|
| 186 |
+
elementwise_affine: bool
|
| 187 |
+
|
| 188 |
+
def __init__(
|
| 189 |
+
self,
|
| 190 |
+
normalized_shape: _shape_t,
|
| 191 |
+
eps: float = 1e-5,
|
| 192 |
+
elementwise_affine: bool = True,
|
| 193 |
+
bias: bool = True,
|
| 194 |
+
device=None,
|
| 195 |
+
dtype=None,
|
| 196 |
+
) -> None:
|
| 197 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 198 |
+
super().__init__()
|
| 199 |
+
if isinstance(normalized_shape, numbers.Integral):
|
| 200 |
+
# mypy error: incompatible types in assignment
|
| 201 |
+
normalized_shape = (normalized_shape,) # type: ignore[assignment]
|
| 202 |
+
self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type]
|
| 203 |
+
self.eps = eps
|
| 204 |
+
self.elementwise_affine = elementwise_affine
|
| 205 |
+
if self.elementwise_affine:
|
| 206 |
+
self.weight = Parameter(
|
| 207 |
+
torch.empty(self.normalized_shape, **factory_kwargs)
|
| 208 |
+
)
|
| 209 |
+
if bias:
|
| 210 |
+
self.bias = Parameter(
|
| 211 |
+
torch.empty(self.normalized_shape, **factory_kwargs)
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
self.register_parameter("bias", None)
|
| 215 |
+
else:
|
| 216 |
+
self.register_parameter("weight", None)
|
| 217 |
+
self.register_parameter("bias", None)
|
| 218 |
+
|
| 219 |
+
self.reset_parameters()
|
| 220 |
+
|
| 221 |
+
def reset_parameters(self) -> None:
|
| 222 |
+
if self.elementwise_affine:
|
| 223 |
+
init.ones_(self.weight)
|
| 224 |
+
if self.bias is not None:
|
| 225 |
+
init.zeros_(self.bias)
|
| 226 |
+
|
| 227 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 228 |
+
return F.layer_norm(
|
| 229 |
+
input, self.normalized_shape, self.weight, self.bias, self.eps
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def extra_repr(self) -> str:
|
| 233 |
+
return (
|
| 234 |
+
"{normalized_shape}, eps={eps}, elementwise_affine={elementwise_affine}, "
|
| 235 |
+
"bias={use_bias}".format(**self.__dict__, use_bias=self.bias is not None)
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class GroupNorm(Module):
|
| 240 |
+
r"""Applies Group Normalization over a mini-batch of inputs.
|
| 241 |
+
|
| 242 |
+
This layer implements the operation as described in
|
| 243 |
+
the paper `Group Normalization <https://arxiv.org/abs/1803.08494>`__
|
| 244 |
+
|
| 245 |
+
.. math::
|
| 246 |
+
y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta
|
| 247 |
+
|
| 248 |
+
The input channels are separated into :attr:`num_groups` groups, each containing
|
| 249 |
+
``num_channels / num_groups`` channels. :attr:`num_channels` must be divisible by
|
| 250 |
+
:attr:`num_groups`. The mean and standard-deviation are calculated
|
| 251 |
+
separately over each group. :math:`\gamma` and :math:`\beta` are learnable
|
| 252 |
+
per-channel affine transform parameter vectors of size :attr:`num_channels` if
|
| 253 |
+
:attr:`affine` is ``True``.
|
| 254 |
+
The variance is calculated via the biased estimator, equivalent to
|
| 255 |
+
`torch.var(input, correction=0)`.
|
| 256 |
+
|
| 257 |
+
This layer uses statistics computed from input data in both training and
|
| 258 |
+
evaluation modes.
|
| 259 |
+
|
| 260 |
+
Args:
|
| 261 |
+
num_groups (int): number of groups to separate the channels into
|
| 262 |
+
num_channels (int): number of channels expected in input
|
| 263 |
+
eps: a value added to the denominator for numerical stability. Default: 1e-5
|
| 264 |
+
affine: a boolean value that when set to ``True``, this module
|
| 265 |
+
has learnable per-channel affine parameters initialized to ones (for weights)
|
| 266 |
+
and zeros (for biases). Default: ``True``
|
| 267 |
+
bias: If set to ``False``, the layer will not learn an additive bias (only relevant if
|
| 268 |
+
:attr:`affine` is ``True``). Default: ``True``
|
| 269 |
+
|
| 270 |
+
Shape:
|
| 271 |
+
- Input: :math:`(N, C, *)` where :math:`C=\text{num\_channels}`
|
| 272 |
+
- Output: :math:`(N, C, *)` (same shape as input)
|
| 273 |
+
|
| 274 |
+
Examples::
|
| 275 |
+
|
| 276 |
+
>>> input = torch.randn(20, 6, 10, 10)
|
| 277 |
+
>>> # Separate 6 channels into 3 groups
|
| 278 |
+
>>> m = nn.GroupNorm(3, 6)
|
| 279 |
+
>>> # Separate 6 channels into 6 groups (equivalent with InstanceNorm)
|
| 280 |
+
>>> m = nn.GroupNorm(6, 6)
|
| 281 |
+
>>> # Put all 6 channels into a single group (equivalent with LayerNorm)
|
| 282 |
+
>>> m = nn.GroupNorm(1, 6)
|
| 283 |
+
>>> # Activating the module
|
| 284 |
+
>>> output = m(input)
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
__constants__ = ["num_groups", "num_channels", "eps", "affine"]
|
| 288 |
+
num_groups: int
|
| 289 |
+
num_channels: int
|
| 290 |
+
eps: float
|
| 291 |
+
affine: bool
|
| 292 |
+
|
| 293 |
+
def __init__(
|
| 294 |
+
self,
|
| 295 |
+
num_groups: int,
|
| 296 |
+
num_channels: int,
|
| 297 |
+
eps: float = 1e-5,
|
| 298 |
+
affine: bool = True,
|
| 299 |
+
device=None,
|
| 300 |
+
dtype=None,
|
| 301 |
+
*,
|
| 302 |
+
bias: bool = True,
|
| 303 |
+
) -> None:
|
| 304 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 305 |
+
super().__init__()
|
| 306 |
+
if num_channels % num_groups != 0:
|
| 307 |
+
raise ValueError(
|
| 308 |
+
f"num_channels ({num_channels}) must be divisible by num_groups ({num_groups})"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
self.num_groups = num_groups
|
| 312 |
+
self.num_channels = num_channels
|
| 313 |
+
self.eps = eps
|
| 314 |
+
self.affine = affine
|
| 315 |
+
if self.affine:
|
| 316 |
+
self.weight = Parameter(torch.empty(num_channels, **factory_kwargs))
|
| 317 |
+
if bias:
|
| 318 |
+
self.bias = Parameter(torch.empty(num_channels, **factory_kwargs))
|
| 319 |
+
else:
|
| 320 |
+
self.register_parameter("bias", None)
|
| 321 |
+
else:
|
| 322 |
+
self.register_parameter("weight", None)
|
| 323 |
+
self.register_parameter("bias", None)
|
| 324 |
+
|
| 325 |
+
self.reset_parameters()
|
| 326 |
+
|
| 327 |
+
def reset_parameters(self) -> None:
|
| 328 |
+
if self.affine:
|
| 329 |
+
init.ones_(self.weight)
|
| 330 |
+
if self.bias is not None:
|
| 331 |
+
init.zeros_(self.bias)
|
| 332 |
+
|
| 333 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 334 |
+
return F.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
|
| 335 |
+
|
| 336 |
+
def extra_repr(self) -> str:
|
| 337 |
+
return (
|
| 338 |
+
"{num_groups}, {num_channels}, eps={eps}, affine={affine}, "
|
| 339 |
+
"bias={use_bias}".format(**self.__dict__, use_bias=self.bias is not None)
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class RMSNorm(Module):
|
| 344 |
+
r"""Applies Root Mean Square Layer Normalization over a mini-batch of inputs.
|
| 345 |
+
|
| 346 |
+
This layer implements the operation as described in
|
| 347 |
+
the paper `Root Mean Square Layer Normalization <https://arxiv.org/pdf/1910.07467.pdf>`__
|
| 348 |
+
|
| 349 |
+
.. math::
|
| 350 |
+
y_i = \frac{x_i}{\mathrm{RMS}(x)} * \gamma_i, \quad
|
| 351 |
+
\text{where} \quad \text{RMS}(x) = \sqrt{\epsilon + \frac{1}{n} \sum_{i=1}^{n} x_i^2}
|
| 352 |
+
|
| 353 |
+
The RMS is taken over the last ``D`` dimensions, where ``D``
|
| 354 |
+
is the dimension of :attr:`normalized_shape`. For example, if :attr:`normalized_shape`
|
| 355 |
+
is ``(3, 5)`` (a 2-dimensional shape), the RMS is computed over
|
| 356 |
+
the last 2 dimensions of the input.
|
| 357 |
+
|
| 358 |
+
Args:
|
| 359 |
+
normalized_shape (int or list or torch.Size): input shape from an expected input
|
| 360 |
+
of size
|
| 361 |
+
|
| 362 |
+
.. math::
|
| 363 |
+
[* \times \text{normalized\_shape}[0] \times \text{normalized\_shape}[1]
|
| 364 |
+
\times \ldots \times \text{normalized\_shape}[-1]]
|
| 365 |
+
|
| 366 |
+
If a single integer is used, it is treated as a singleton list, and this module will
|
| 367 |
+
normalize over the last dimension which is expected to be of that specific size.
|
| 368 |
+
eps (float, optional): a value added to the denominator for numerical stability.
|
| 369 |
+
If not specified, uses the machine epsilon of the computation (opmath) type:
|
| 370 |
+
fp16/bf16 and fp32 inputs use ``torch.finfo(torch.float32).eps``, while fp64
|
| 371 |
+
inputs use ``torch.finfo(torch.float64).eps``. Default: ``None``
|
| 372 |
+
elementwise_affine: a boolean value that when set to ``True``, this module
|
| 373 |
+
has learnable per-element affine parameters initialized to ones (for weights). Default: ``True``.
|
| 374 |
+
|
| 375 |
+
Shape:
|
| 376 |
+
- Input: :math:`(N, *)`
|
| 377 |
+
- Output: :math:`(N, *)` (same shape as input)
|
| 378 |
+
|
| 379 |
+
Examples::
|
| 380 |
+
|
| 381 |
+
>>> rms_norm = nn.RMSNorm([2, 3])
|
| 382 |
+
>>> input = torch.randn(2, 2, 3)
|
| 383 |
+
>>> rms_norm(input)
|
| 384 |
+
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
__constants__ = ["normalized_shape", "eps", "elementwise_affine"]
|
| 388 |
+
normalized_shape: tuple[int, ...]
|
| 389 |
+
eps: float | None
|
| 390 |
+
elementwise_affine: bool
|
| 391 |
+
|
| 392 |
+
def __init__(
|
| 393 |
+
self,
|
| 394 |
+
normalized_shape: _shape_t,
|
| 395 |
+
eps: float | None = None,
|
| 396 |
+
elementwise_affine: bool = True,
|
| 397 |
+
device=None,
|
| 398 |
+
dtype=None,
|
| 399 |
+
) -> None:
|
| 400 |
+
factory_kwargs = {"device": device, "dtype": dtype}
|
| 401 |
+
super().__init__()
|
| 402 |
+
if isinstance(normalized_shape, numbers.Integral):
|
| 403 |
+
# mypy error: incompatible types in assignment
|
| 404 |
+
normalized_shape = (normalized_shape,) # type: ignore[assignment]
|
| 405 |
+
self.normalized_shape = tuple(normalized_shape) # type: ignore[arg-type]
|
| 406 |
+
self.eps = eps
|
| 407 |
+
self.elementwise_affine = elementwise_affine
|
| 408 |
+
if self.elementwise_affine:
|
| 409 |
+
self.weight = Parameter(
|
| 410 |
+
torch.empty(self.normalized_shape, **factory_kwargs)
|
| 411 |
+
)
|
| 412 |
+
else:
|
| 413 |
+
self.register_parameter("weight", None)
|
| 414 |
+
self.reset_parameters()
|
| 415 |
+
|
| 416 |
+
def reset_parameters(self) -> None:
|
| 417 |
+
"""
|
| 418 |
+
Resets parameters based on their initialization used in __init__.
|
| 419 |
+
"""
|
| 420 |
+
if self.elementwise_affine:
|
| 421 |
+
init.ones_(self.weight)
|
| 422 |
+
|
| 423 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 424 |
+
"""
|
| 425 |
+
Runs the forward pass.
|
| 426 |
+
"""
|
| 427 |
+
return F.rms_norm(x, self.normalized_shape, self.weight, self.eps)
|
| 428 |
+
|
| 429 |
+
def extra_repr(self) -> str:
|
| 430 |
+
"""
|
| 431 |
+
Return the extra representation of the module.
|
| 432 |
+
"""
|
| 433 |
+
return (
|
| 434 |
+
"{normalized_shape}, eps={eps}, "
|
| 435 |
+
"elementwise_affine={elementwise_affine}".format(**self.__dict__)
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
# TODO: ContrastiveNorm2d
|
| 440 |
+
# TODO: DivisiveNorm2d
|
| 441 |
+
# TODO: SubtractiveNorm2d
|
.venv/lib/python3.12/site-packages/torch/nn/modules/padding.py
ADDED
|
@@ -0,0 +1,842 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Sequence
|
| 3 |
+
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch import Tensor
|
| 6 |
+
from torch.nn.common_types import _size_2_t, _size_4_t, _size_6_t
|
| 7 |
+
|
| 8 |
+
from .module import Module
|
| 9 |
+
from .utils import _ntuple, _pair, _quadruple
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# TODO: grad_output size asserts in THNN
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"CircularPad1d",
|
| 16 |
+
"CircularPad2d",
|
| 17 |
+
"CircularPad3d",
|
| 18 |
+
"ConstantPad1d",
|
| 19 |
+
"ConstantPad2d",
|
| 20 |
+
"ConstantPad3d",
|
| 21 |
+
"ReflectionPad1d",
|
| 22 |
+
"ReflectionPad2d",
|
| 23 |
+
"ReflectionPad3d",
|
| 24 |
+
"ReplicationPad1d",
|
| 25 |
+
"ReplicationPad2d",
|
| 26 |
+
"ReplicationPad3d",
|
| 27 |
+
"ZeroPad1d",
|
| 28 |
+
"ZeroPad2d",
|
| 29 |
+
"ZeroPad3d",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class _CircularPadNd(Module):
|
| 34 |
+
__constants__ = ["padding"]
|
| 35 |
+
padding: Sequence[int]
|
| 36 |
+
|
| 37 |
+
def _check_input_dim(self, input):
|
| 38 |
+
raise NotImplementedError
|
| 39 |
+
|
| 40 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 41 |
+
self._check_input_dim(input)
|
| 42 |
+
return F.pad(input, self.padding, "circular")
|
| 43 |
+
|
| 44 |
+
def extra_repr(self) -> str:
|
| 45 |
+
return f"{self.padding}"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class CircularPad1d(_CircularPadNd):
|
| 49 |
+
r"""Pads the input tensor using circular padding of the input boundary.
|
| 50 |
+
|
| 51 |
+
Tensor values at the beginning of the dimension are used to pad the end,
|
| 52 |
+
and values at the end are used to pad the beginning. If negative padding is
|
| 53 |
+
applied then the ends of the tensor get removed.
|
| 54 |
+
|
| 55 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 59 |
+
padding in all boundaries. If a 2-`tuple`, uses
|
| 60 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`)
|
| 61 |
+
Note that padding size should be less than or equal to the corresponding input dimension.
|
| 62 |
+
|
| 63 |
+
Shape:
|
| 64 |
+
- Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`.
|
| 65 |
+
- Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where
|
| 66 |
+
|
| 67 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 68 |
+
|
| 69 |
+
Examples::
|
| 70 |
+
|
| 71 |
+
>>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this")
|
| 72 |
+
>>> m = nn.CircularPad1d(2)
|
| 73 |
+
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4)
|
| 74 |
+
>>> input
|
| 75 |
+
tensor([[[0., 1., 2., 3.],
|
| 76 |
+
[4., 5., 6., 7.]]])
|
| 77 |
+
>>> m(input)
|
| 78 |
+
tensor([[[2., 3., 0., 1., 2., 3., 0., 1.],
|
| 79 |
+
[6., 7., 4., 5., 6., 7., 4., 5.]]])
|
| 80 |
+
>>> # using different paddings for different sides
|
| 81 |
+
>>> m = nn.CircularPad1d((3, 1))
|
| 82 |
+
>>> m(input)
|
| 83 |
+
tensor([[[1., 2., 3., 0., 1., 2., 3., 0.],
|
| 84 |
+
[5., 6., 7., 4., 5., 6., 7., 4.]]])
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
# pyrefly: ignore [bad-override]
|
| 88 |
+
padding: tuple[int, int]
|
| 89 |
+
|
| 90 |
+
def __init__(self, padding: _size_2_t) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.padding = _pair(padding)
|
| 93 |
+
|
| 94 |
+
def _check_input_dim(self, input) -> None:
|
| 95 |
+
if input.dim() != 2 and input.dim() != 3:
|
| 96 |
+
raise ValueError(f"expected 2D or 3D input (got {input.dim()}D input)")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class CircularPad2d(_CircularPadNd):
|
| 100 |
+
r"""Pads the input tensor using circular padding of the input boundary.
|
| 101 |
+
|
| 102 |
+
Tensor values at the beginning of the dimension are used to pad the end,
|
| 103 |
+
and values at the end are used to pad the beginning. If negative padding is
|
| 104 |
+
applied then the ends of the tensor get removed.
|
| 105 |
+
|
| 106 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 110 |
+
padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`,
|
| 111 |
+
:math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`)
|
| 112 |
+
Note that padding size should be less than or equal to the corresponding input dimension.
|
| 113 |
+
|
| 114 |
+
Shape:
|
| 115 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 116 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 117 |
+
|
| 118 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 119 |
+
|
| 120 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 121 |
+
|
| 122 |
+
Examples::
|
| 123 |
+
|
| 124 |
+
>>> m = nn.CircularPad2d(2)
|
| 125 |
+
>>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3)
|
| 126 |
+
>>> input
|
| 127 |
+
tensor([[[[0., 1., 2.],
|
| 128 |
+
[3., 4., 5.],
|
| 129 |
+
[6., 7., 8.]]]])
|
| 130 |
+
>>> m(input)
|
| 131 |
+
tensor([[[[4., 5., 3., 4., 5., 3., 4.],
|
| 132 |
+
[7., 8., 6., 7., 8., 6., 7.],
|
| 133 |
+
[1., 2., 0., 1., 2., 0., 1.],
|
| 134 |
+
[4., 5., 3., 4., 5., 3., 4.],
|
| 135 |
+
[7., 8., 6., 7., 8., 6., 7.],
|
| 136 |
+
[1., 2., 0., 1., 2., 0., 1.],
|
| 137 |
+
[4., 5., 3., 4., 5., 3., 4.]]]])
|
| 138 |
+
>>> # using different paddings for different sides
|
| 139 |
+
>>> m = nn.CircularPad2d((1, 1, 2, 0))
|
| 140 |
+
>>> m(input)
|
| 141 |
+
tensor([[[[5., 3., 4., 5., 3.],
|
| 142 |
+
[8., 6., 7., 8., 6.],
|
| 143 |
+
[2., 0., 1., 2., 0.],
|
| 144 |
+
[5., 3., 4., 5., 3.],
|
| 145 |
+
[8., 6., 7., 8., 6.]]]])
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
# pyrefly: ignore [bad-override]
|
| 149 |
+
padding: tuple[int, int, int, int]
|
| 150 |
+
|
| 151 |
+
def __init__(self, padding: _size_4_t) -> None:
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.padding = _quadruple(padding)
|
| 154 |
+
|
| 155 |
+
def _check_input_dim(self, input) -> None:
|
| 156 |
+
if input.dim() != 3 and input.dim() != 4:
|
| 157 |
+
raise ValueError(f"expected 3D or 4D input (got {input.dim()}D input)")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class CircularPad3d(_CircularPadNd):
|
| 161 |
+
r"""Pads the input tensor using circular padding of the input boundary.
|
| 162 |
+
|
| 163 |
+
Tensor values at the beginning of the dimension are used to pad the end,
|
| 164 |
+
and values at the end are used to pad the beginning. If negative padding is
|
| 165 |
+
applied then the ends of the tensor get removed.
|
| 166 |
+
|
| 167 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 171 |
+
padding in all boundaries. If a 6-`tuple`, uses
|
| 172 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`,
|
| 173 |
+
:math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`,
|
| 174 |
+
:math:`\text{padding\_front}`, :math:`\text{padding\_back}`)
|
| 175 |
+
Note that padding size should be less than or equal to the corresponding input dimension.
|
| 176 |
+
|
| 177 |
+
Shape:
|
| 178 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 179 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`,
|
| 180 |
+
where
|
| 181 |
+
|
| 182 |
+
:math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}`
|
| 183 |
+
|
| 184 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 185 |
+
|
| 186 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 187 |
+
|
| 188 |
+
Examples::
|
| 189 |
+
|
| 190 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 191 |
+
>>> m = nn.CircularPad3d(3)
|
| 192 |
+
>>> input = torch.randn(16, 3, 8, 320, 480)
|
| 193 |
+
>>> output = m(input)
|
| 194 |
+
>>> # using different paddings for different sides
|
| 195 |
+
>>> m = nn.CircularPad3d((3, 3, 6, 6, 1, 1))
|
| 196 |
+
>>> output = m(input)
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
# pyrefly: ignore [bad-override]
|
| 200 |
+
padding: tuple[int, int, int, int, int, int]
|
| 201 |
+
|
| 202 |
+
def __init__(self, padding: _size_6_t) -> None:
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.padding = _ntuple(6)(padding)
|
| 205 |
+
|
| 206 |
+
def _check_input_dim(self, input) -> None:
|
| 207 |
+
if input.dim() != 4 and input.dim() != 5:
|
| 208 |
+
raise ValueError(f"expected 4D or 5D input (got {input.dim()}D input)")
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class _ConstantPadNd(Module):
|
| 212 |
+
__constants__ = ["padding", "value"]
|
| 213 |
+
value: float
|
| 214 |
+
padding: Sequence[int]
|
| 215 |
+
|
| 216 |
+
def __init__(self, value: float) -> None:
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.value = value
|
| 219 |
+
|
| 220 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 221 |
+
return F.pad(input, self.padding, "constant", self.value)
|
| 222 |
+
|
| 223 |
+
def extra_repr(self) -> str:
|
| 224 |
+
return f"padding={self.padding}, value={self.value}"
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class ConstantPad1d(_ConstantPadNd):
|
| 228 |
+
r"""Pads the input tensor boundaries with a constant value.
|
| 229 |
+
|
| 230 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 234 |
+
padding in both boundaries. If a 2-`tuple`, uses
|
| 235 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`)
|
| 236 |
+
|
| 237 |
+
Shape:
|
| 238 |
+
- Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`.
|
| 239 |
+
- Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where
|
| 240 |
+
|
| 241 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 242 |
+
|
| 243 |
+
Examples::
|
| 244 |
+
|
| 245 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 246 |
+
>>> m = nn.ConstantPad1d(2, 3.5)
|
| 247 |
+
>>> input = torch.randn(1, 2, 4)
|
| 248 |
+
>>> input
|
| 249 |
+
tensor([[[-1.0491, -0.7152, -0.0749, 0.8530],
|
| 250 |
+
[-1.3287, 1.8966, 0.1466, -0.2771]]])
|
| 251 |
+
>>> m(input)
|
| 252 |
+
tensor([[[ 3.5000, 3.5000, -1.0491, -0.7152, -0.0749, 0.8530, 3.5000,
|
| 253 |
+
3.5000],
|
| 254 |
+
[ 3.5000, 3.5000, -1.3287, 1.8966, 0.1466, -0.2771, 3.5000,
|
| 255 |
+
3.5000]]])
|
| 256 |
+
>>> m = nn.ConstantPad1d(2, 3.5)
|
| 257 |
+
>>> input = torch.randn(1, 2, 3)
|
| 258 |
+
>>> input
|
| 259 |
+
tensor([[[ 1.6616, 1.4523, -1.1255],
|
| 260 |
+
[-3.6372, 0.1182, -1.8652]]])
|
| 261 |
+
>>> m(input)
|
| 262 |
+
tensor([[[ 3.5000, 3.5000, 1.6616, 1.4523, -1.1255, 3.5000, 3.5000],
|
| 263 |
+
[ 3.5000, 3.5000, -3.6372, 0.1182, -1.8652, 3.5000, 3.5000]]])
|
| 264 |
+
>>> # using different paddings for different sides
|
| 265 |
+
>>> m = nn.ConstantPad1d((3, 1), 3.5)
|
| 266 |
+
>>> m(input)
|
| 267 |
+
tensor([[[ 3.5000, 3.5000, 3.5000, 1.6616, 1.4523, -1.1255, 3.5000],
|
| 268 |
+
[ 3.5000, 3.5000, 3.5000, -3.6372, 0.1182, -1.8652, 3.5000]]])
|
| 269 |
+
"""
|
| 270 |
+
|
| 271 |
+
# pyrefly: ignore [bad-override]
|
| 272 |
+
padding: tuple[int, int]
|
| 273 |
+
|
| 274 |
+
def __init__(self, padding: _size_2_t, value: float) -> None:
|
| 275 |
+
super().__init__(value)
|
| 276 |
+
self.padding = _pair(padding)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class ConstantPad2d(_ConstantPadNd):
|
| 280 |
+
r"""Pads the input tensor boundaries with a constant value.
|
| 281 |
+
|
| 282 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 286 |
+
padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`,
|
| 287 |
+
:math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`)
|
| 288 |
+
|
| 289 |
+
Shape:
|
| 290 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 291 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 292 |
+
|
| 293 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 294 |
+
|
| 295 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 296 |
+
|
| 297 |
+
Examples::
|
| 298 |
+
|
| 299 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 300 |
+
>>> m = nn.ConstantPad2d(2, 3.5)
|
| 301 |
+
>>> input = torch.randn(1, 2, 2)
|
| 302 |
+
>>> input
|
| 303 |
+
tensor([[[ 1.6585, 0.4320],
|
| 304 |
+
[-0.8701, -0.4649]]])
|
| 305 |
+
>>> m(input)
|
| 306 |
+
tensor([[[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
|
| 307 |
+
[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
|
| 308 |
+
[ 3.5000, 3.5000, 1.6585, 0.4320, 3.5000, 3.5000],
|
| 309 |
+
[ 3.5000, 3.5000, -0.8701, -0.4649, 3.5000, 3.5000],
|
| 310 |
+
[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
|
| 311 |
+
[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000, 3.5000]]])
|
| 312 |
+
>>> # using different paddings for different sides
|
| 313 |
+
>>> m = nn.ConstantPad2d((3, 0, 2, 1), 3.5)
|
| 314 |
+
>>> m(input)
|
| 315 |
+
tensor([[[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
|
| 316 |
+
[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000],
|
| 317 |
+
[ 3.5000, 3.5000, 3.5000, 1.6585, 0.4320],
|
| 318 |
+
[ 3.5000, 3.5000, 3.5000, -0.8701, -0.4649],
|
| 319 |
+
[ 3.5000, 3.5000, 3.5000, 3.5000, 3.5000]]])
|
| 320 |
+
"""
|
| 321 |
+
|
| 322 |
+
__constants__ = ["padding", "value"]
|
| 323 |
+
# pyrefly: ignore [bad-override]
|
| 324 |
+
padding: tuple[int, int, int, int]
|
| 325 |
+
|
| 326 |
+
def __init__(self, padding: _size_4_t, value: float) -> None:
|
| 327 |
+
super().__init__(value)
|
| 328 |
+
self.padding = _quadruple(padding)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class ConstantPad3d(_ConstantPadNd):
|
| 332 |
+
r"""Pads the input tensor boundaries with a constant value.
|
| 333 |
+
|
| 334 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 338 |
+
padding in all boundaries. If a 6-`tuple`, uses
|
| 339 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`,
|
| 340 |
+
:math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`,
|
| 341 |
+
:math:`\text{padding\_front}`, :math:`\text{padding\_back}`)
|
| 342 |
+
|
| 343 |
+
Shape:
|
| 344 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 345 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or
|
| 346 |
+
:math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 347 |
+
|
| 348 |
+
:math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}`
|
| 349 |
+
|
| 350 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 351 |
+
|
| 352 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 353 |
+
|
| 354 |
+
Examples::
|
| 355 |
+
|
| 356 |
+
>>> m = nn.ConstantPad3d(3, 3.5)
|
| 357 |
+
>>> input = torch.randn(16, 3, 10, 20, 30)
|
| 358 |
+
>>> output = m(input)
|
| 359 |
+
>>> # using different paddings for different sides
|
| 360 |
+
>>> m = nn.ConstantPad3d((3, 3, 6, 6, 0, 1), 3.5)
|
| 361 |
+
>>> output = m(input)
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
# pyrefly: ignore [bad-override]
|
| 365 |
+
padding: tuple[int, int, int, int, int, int]
|
| 366 |
+
|
| 367 |
+
def __init__(self, padding: _size_6_t, value: float) -> None:
|
| 368 |
+
super().__init__(value)
|
| 369 |
+
self.padding = _ntuple(6)(padding)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class _ReflectionPadNd(Module):
|
| 373 |
+
__constants__ = ["padding"]
|
| 374 |
+
padding: Sequence[int]
|
| 375 |
+
|
| 376 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 377 |
+
return F.pad(input, self.padding, "reflect")
|
| 378 |
+
|
| 379 |
+
def extra_repr(self) -> str:
|
| 380 |
+
return f"{self.padding}"
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class ReflectionPad1d(_ReflectionPadNd):
|
| 384 |
+
r"""Pads the input tensor using the reflection of the input boundary.
|
| 385 |
+
|
| 386 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 387 |
+
|
| 388 |
+
Args:
|
| 389 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 390 |
+
padding in all boundaries. If a 2-`tuple`, uses
|
| 391 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`)
|
| 392 |
+
Note that padding size should be less than the corresponding input dimension.
|
| 393 |
+
|
| 394 |
+
Shape:
|
| 395 |
+
- Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`.
|
| 396 |
+
- Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where
|
| 397 |
+
|
| 398 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 399 |
+
|
| 400 |
+
Examples::
|
| 401 |
+
|
| 402 |
+
>>> m = nn.ReflectionPad1d(2)
|
| 403 |
+
>>> # xdoctest: +IGNORE_WANT("other tests seem to modify printing styles")
|
| 404 |
+
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4)
|
| 405 |
+
>>> input
|
| 406 |
+
tensor([[[0., 1., 2., 3.],
|
| 407 |
+
[4., 5., 6., 7.]]])
|
| 408 |
+
>>> m(input)
|
| 409 |
+
tensor([[[2., 1., 0., 1., 2., 3., 2., 1.],
|
| 410 |
+
[6., 5., 4., 5., 6., 7., 6., 5.]]])
|
| 411 |
+
>>> # using different paddings for different sides
|
| 412 |
+
>>> m = nn.ReflectionPad1d((3, 1))
|
| 413 |
+
>>> m(input)
|
| 414 |
+
tensor([[[3., 2., 1., 0., 1., 2., 3., 2.],
|
| 415 |
+
[7., 6., 5., 4., 5., 6., 7., 6.]]])
|
| 416 |
+
"""
|
| 417 |
+
|
| 418 |
+
# pyrefly: ignore [bad-override]
|
| 419 |
+
padding: tuple[int, int]
|
| 420 |
+
|
| 421 |
+
def __init__(self, padding: _size_2_t) -> None:
|
| 422 |
+
super().__init__()
|
| 423 |
+
self.padding = _pair(padding)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class ReflectionPad2d(_ReflectionPadNd):
|
| 427 |
+
r"""Pads the input tensor using the reflection of the input boundary.
|
| 428 |
+
|
| 429 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 430 |
+
|
| 431 |
+
Args:
|
| 432 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 433 |
+
padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`,
|
| 434 |
+
:math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`)
|
| 435 |
+
Note that padding size should be less than the corresponding input dimension.
|
| 436 |
+
|
| 437 |
+
Shape:
|
| 438 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 439 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})` where
|
| 440 |
+
|
| 441 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 442 |
+
|
| 443 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 444 |
+
|
| 445 |
+
Examples::
|
| 446 |
+
|
| 447 |
+
>>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this")
|
| 448 |
+
>>> m = nn.ReflectionPad2d(2)
|
| 449 |
+
>>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3)
|
| 450 |
+
>>> input
|
| 451 |
+
tensor([[[[0., 1., 2.],
|
| 452 |
+
[3., 4., 5.],
|
| 453 |
+
[6., 7., 8.]]]])
|
| 454 |
+
>>> m(input)
|
| 455 |
+
tensor([[[[8., 7., 6., 7., 8., 7., 6.],
|
| 456 |
+
[5., 4., 3., 4., 5., 4., 3.],
|
| 457 |
+
[2., 1., 0., 1., 2., 1., 0.],
|
| 458 |
+
[5., 4., 3., 4., 5., 4., 3.],
|
| 459 |
+
[8., 7., 6., 7., 8., 7., 6.],
|
| 460 |
+
[5., 4., 3., 4., 5., 4., 3.],
|
| 461 |
+
[2., 1., 0., 1., 2., 1., 0.]]]])
|
| 462 |
+
>>> # using different paddings for different sides
|
| 463 |
+
>>> m = nn.ReflectionPad2d((1, 1, 2, 0))
|
| 464 |
+
>>> m(input)
|
| 465 |
+
tensor([[[[7., 6., 7., 8., 7.],
|
| 466 |
+
[4., 3., 4., 5., 4.],
|
| 467 |
+
[1., 0., 1., 2., 1.],
|
| 468 |
+
[4., 3., 4., 5., 4.],
|
| 469 |
+
[7., 6., 7., 8., 7.]]]])
|
| 470 |
+
"""
|
| 471 |
+
|
| 472 |
+
# pyrefly: ignore [bad-override]
|
| 473 |
+
padding: tuple[int, int, int, int]
|
| 474 |
+
|
| 475 |
+
def __init__(self, padding: _size_4_t) -> None:
|
| 476 |
+
super().__init__()
|
| 477 |
+
self.padding = _quadruple(padding)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
class ReflectionPad3d(_ReflectionPadNd):
|
| 481 |
+
r"""Pads the input tensor using the reflection of the input boundary.
|
| 482 |
+
|
| 483 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 484 |
+
|
| 485 |
+
Args:
|
| 486 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 487 |
+
padding in all boundaries. If a 6-`tuple`, uses
|
| 488 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`,
|
| 489 |
+
:math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`,
|
| 490 |
+
:math:`\text{padding\_front}`, :math:`\text{padding\_back}`)
|
| 491 |
+
Note that padding size should be less than the corresponding input dimension.
|
| 492 |
+
|
| 493 |
+
Shape:
|
| 494 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 495 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`,
|
| 496 |
+
where
|
| 497 |
+
|
| 498 |
+
:math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}`
|
| 499 |
+
|
| 500 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 501 |
+
|
| 502 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 503 |
+
|
| 504 |
+
Examples::
|
| 505 |
+
|
| 506 |
+
>>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this")
|
| 507 |
+
>>> m = nn.ReflectionPad3d(1)
|
| 508 |
+
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 1, 2, 2, 2)
|
| 509 |
+
>>> m(input)
|
| 510 |
+
tensor([[[[[7., 6., 7., 6.],
|
| 511 |
+
[5., 4., 5., 4.],
|
| 512 |
+
[7., 6., 7., 6.],
|
| 513 |
+
[5., 4., 5., 4.]],
|
| 514 |
+
[[3., 2., 3., 2.],
|
| 515 |
+
[1., 0., 1., 0.],
|
| 516 |
+
[3., 2., 3., 2.],
|
| 517 |
+
[1., 0., 1., 0.]],
|
| 518 |
+
[[7., 6., 7., 6.],
|
| 519 |
+
[5., 4., 5., 4.],
|
| 520 |
+
[7., 6., 7., 6.],
|
| 521 |
+
[5., 4., 5., 4.]],
|
| 522 |
+
[[3., 2., 3., 2.],
|
| 523 |
+
[1., 0., 1., 0.],
|
| 524 |
+
[3., 2., 3., 2.],
|
| 525 |
+
[1., 0., 1., 0.]]]]])
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
# pyrefly: ignore [bad-override]
|
| 529 |
+
padding: tuple[int, int, int, int, int, int]
|
| 530 |
+
|
| 531 |
+
def __init__(self, padding: _size_6_t) -> None:
|
| 532 |
+
super().__init__()
|
| 533 |
+
self.padding = _ntuple(6)(padding)
|
| 534 |
+
|
| 535 |
+
|
| 536 |
+
class _ReplicationPadNd(Module):
|
| 537 |
+
__constants__ = ["padding"]
|
| 538 |
+
padding: Sequence[int]
|
| 539 |
+
|
| 540 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 541 |
+
return F.pad(input, self.padding, "replicate")
|
| 542 |
+
|
| 543 |
+
def extra_repr(self) -> str:
|
| 544 |
+
return f"{self.padding}"
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
class ReplicationPad1d(_ReplicationPadNd):
|
| 548 |
+
r"""Pads the input tensor using replication of the input boundary.
|
| 549 |
+
|
| 550 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 551 |
+
|
| 552 |
+
Args:
|
| 553 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 554 |
+
padding in all boundaries. If a 2-`tuple`, uses
|
| 555 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`)
|
| 556 |
+
Note that the output dimensions must remain positive.
|
| 557 |
+
|
| 558 |
+
Shape:
|
| 559 |
+
- Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`.
|
| 560 |
+
- Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where
|
| 561 |
+
|
| 562 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 563 |
+
|
| 564 |
+
Examples::
|
| 565 |
+
|
| 566 |
+
>>> # xdoctest: +IGNORE_WANT("not sure why xdoctest is choking on this")
|
| 567 |
+
>>> m = nn.ReplicationPad1d(2)
|
| 568 |
+
>>> input = torch.arange(8, dtype=torch.float).reshape(1, 2, 4)
|
| 569 |
+
>>> input
|
| 570 |
+
tensor([[[0., 1., 2., 3.],
|
| 571 |
+
[4., 5., 6., 7.]]])
|
| 572 |
+
>>> m(input)
|
| 573 |
+
tensor([[[0., 0., 0., 1., 2., 3., 3., 3.],
|
| 574 |
+
[4., 4., 4., 5., 6., 7., 7., 7.]]])
|
| 575 |
+
>>> # using different paddings for different sides
|
| 576 |
+
>>> m = nn.ReplicationPad1d((3, 1))
|
| 577 |
+
>>> m(input)
|
| 578 |
+
tensor([[[0., 0., 0., 0., 1., 2., 3., 3.],
|
| 579 |
+
[4., 4., 4., 4., 5., 6., 7., 7.]]])
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
# pyrefly: ignore [bad-override]
|
| 583 |
+
padding: tuple[int, int]
|
| 584 |
+
|
| 585 |
+
def __init__(self, padding: _size_2_t) -> None:
|
| 586 |
+
super().__init__()
|
| 587 |
+
self.padding = _pair(padding)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class ReplicationPad2d(_ReplicationPadNd):
|
| 591 |
+
r"""Pads the input tensor using replication of the input boundary.
|
| 592 |
+
|
| 593 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 594 |
+
|
| 595 |
+
Args:
|
| 596 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 597 |
+
padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`,
|
| 598 |
+
:math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`)
|
| 599 |
+
Note that the output dimensions must remain positive.
|
| 600 |
+
|
| 601 |
+
Shape:
|
| 602 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 603 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 604 |
+
|
| 605 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 606 |
+
|
| 607 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 608 |
+
|
| 609 |
+
Examples::
|
| 610 |
+
|
| 611 |
+
>>> m = nn.ReplicationPad2d(2)
|
| 612 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 613 |
+
>>> input = torch.arange(9, dtype=torch.float).reshape(1, 1, 3, 3)
|
| 614 |
+
>>> input
|
| 615 |
+
tensor([[[[0., 1., 2.],
|
| 616 |
+
[3., 4., 5.],
|
| 617 |
+
[6., 7., 8.]]]])
|
| 618 |
+
>>> m(input)
|
| 619 |
+
tensor([[[[0., 0., 0., 1., 2., 2., 2.],
|
| 620 |
+
[0., 0., 0., 1., 2., 2., 2.],
|
| 621 |
+
[0., 0., 0., 1., 2., 2., 2.],
|
| 622 |
+
[3., 3., 3., 4., 5., 5., 5.],
|
| 623 |
+
[6., 6., 6., 7., 8., 8., 8.],
|
| 624 |
+
[6., 6., 6., 7., 8., 8., 8.],
|
| 625 |
+
[6., 6., 6., 7., 8., 8., 8.]]]])
|
| 626 |
+
>>> # using different paddings for different sides
|
| 627 |
+
>>> m = nn.ReplicationPad2d((1, 1, 2, 0))
|
| 628 |
+
>>> m(input)
|
| 629 |
+
tensor([[[[0., 0., 1., 2., 2.],
|
| 630 |
+
[0., 0., 1., 2., 2.],
|
| 631 |
+
[0., 0., 1., 2., 2.],
|
| 632 |
+
[3., 3., 4., 5., 5.],
|
| 633 |
+
[6., 6., 7., 8., 8.]]]])
|
| 634 |
+
"""
|
| 635 |
+
|
| 636 |
+
# pyrefly: ignore [bad-override]
|
| 637 |
+
padding: tuple[int, int, int, int]
|
| 638 |
+
|
| 639 |
+
def __init__(self, padding: _size_4_t) -> None:
|
| 640 |
+
super().__init__()
|
| 641 |
+
self.padding = _quadruple(padding)
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
class ReplicationPad3d(_ReplicationPadNd):
|
| 645 |
+
r"""Pads the input tensor using replication of the input boundary.
|
| 646 |
+
|
| 647 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 648 |
+
|
| 649 |
+
Args:
|
| 650 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 651 |
+
padding in all boundaries. If a 6-`tuple`, uses
|
| 652 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`,
|
| 653 |
+
:math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`,
|
| 654 |
+
:math:`\text{padding\_front}`, :math:`\text{padding\_back}`)
|
| 655 |
+
Note that the output dimensions must remain positive.
|
| 656 |
+
|
| 657 |
+
Shape:
|
| 658 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 659 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`,
|
| 660 |
+
where
|
| 661 |
+
|
| 662 |
+
:math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}`
|
| 663 |
+
|
| 664 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 665 |
+
|
| 666 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 667 |
+
|
| 668 |
+
Examples::
|
| 669 |
+
|
| 670 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 671 |
+
>>> m = nn.ReplicationPad3d(3)
|
| 672 |
+
>>> input = torch.randn(16, 3, 8, 320, 480)
|
| 673 |
+
>>> output = m(input)
|
| 674 |
+
>>> # using different paddings for different sides
|
| 675 |
+
>>> m = nn.ReplicationPad3d((3, 3, 6, 6, 1, 1))
|
| 676 |
+
>>> output = m(input)
|
| 677 |
+
"""
|
| 678 |
+
|
| 679 |
+
# pyrefly: ignore [bad-override]
|
| 680 |
+
padding: tuple[int, int, int, int, int, int]
|
| 681 |
+
|
| 682 |
+
def __init__(self, padding: _size_6_t) -> None:
|
| 683 |
+
super().__init__()
|
| 684 |
+
self.padding = _ntuple(6)(padding)
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
class ZeroPad1d(ConstantPad1d):
|
| 688 |
+
r"""Pads the input tensor boundaries with zero.
|
| 689 |
+
|
| 690 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 691 |
+
|
| 692 |
+
Args:
|
| 693 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 694 |
+
padding in both boundaries. If a 2-`tuple`, uses
|
| 695 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`)
|
| 696 |
+
|
| 697 |
+
Shape:
|
| 698 |
+
- Input: :math:`(C, W_{in})` or :math:`(N, C, W_{in})`.
|
| 699 |
+
- Output: :math:`(C, W_{out})` or :math:`(N, C, W_{out})`, where
|
| 700 |
+
|
| 701 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 702 |
+
|
| 703 |
+
Examples::
|
| 704 |
+
|
| 705 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 706 |
+
>>> m = nn.ZeroPad1d(2)
|
| 707 |
+
>>> input = torch.randn(1, 2, 4)
|
| 708 |
+
>>> input
|
| 709 |
+
tensor([[[-1.0491, -0.7152, -0.0749, 0.8530],
|
| 710 |
+
[-1.3287, 1.8966, 0.1466, -0.2771]]])
|
| 711 |
+
>>> m(input)
|
| 712 |
+
tensor([[[ 0.0000, 0.0000, -1.0491, -0.7152, -0.0749, 0.8530, 0.0000,
|
| 713 |
+
0.0000],
|
| 714 |
+
[ 0.0000, 0.0000, -1.3287, 1.8966, 0.1466, -0.2771, 0.0000,
|
| 715 |
+
0.0000]]])
|
| 716 |
+
>>> m = nn.ZeroPad1d(2)
|
| 717 |
+
>>> input = torch.randn(1, 2, 3)
|
| 718 |
+
>>> input
|
| 719 |
+
tensor([[[ 1.6616, 1.4523, -1.1255],
|
| 720 |
+
[-3.6372, 0.1182, -1.8652]]])
|
| 721 |
+
>>> m(input)
|
| 722 |
+
tensor([[[ 0.0000, 0.0000, 1.6616, 1.4523, -1.1255, 0.0000, 0.0000],
|
| 723 |
+
[ 0.0000, 0.0000, -3.6372, 0.1182, -1.8652, 0.0000, 0.0000]]])
|
| 724 |
+
>>> # using different paddings for different sides
|
| 725 |
+
>>> m = nn.ZeroPad1d((3, 1))
|
| 726 |
+
>>> m(input)
|
| 727 |
+
tensor([[[ 0.0000, 0.0000, 0.0000, 1.6616, 1.4523, -1.1255, 0.0000],
|
| 728 |
+
[ 0.0000, 0.0000, 0.0000, -3.6372, 0.1182, -1.8652, 0.0000]]])
|
| 729 |
+
"""
|
| 730 |
+
|
| 731 |
+
padding: tuple[int, int]
|
| 732 |
+
|
| 733 |
+
def __init__(self, padding: _size_2_t) -> None:
|
| 734 |
+
super().__init__(padding, 0.0)
|
| 735 |
+
|
| 736 |
+
def extra_repr(self) -> str:
|
| 737 |
+
"""
|
| 738 |
+
Return the extra representation of the module.
|
| 739 |
+
"""
|
| 740 |
+
return f"{self.padding}"
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class ZeroPad2d(ConstantPad2d):
|
| 744 |
+
r"""Pads the input tensor boundaries with zero.
|
| 745 |
+
|
| 746 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 747 |
+
|
| 748 |
+
Args:
|
| 749 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 750 |
+
padding in all boundaries. If a 4-`tuple`, uses (:math:`\text{padding\_left}`,
|
| 751 |
+
:math:`\text{padding\_right}`, :math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`)
|
| 752 |
+
|
| 753 |
+
Shape:
|
| 754 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 755 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 756 |
+
|
| 757 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 758 |
+
|
| 759 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 760 |
+
|
| 761 |
+
Examples::
|
| 762 |
+
|
| 763 |
+
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
|
| 764 |
+
>>> m = nn.ZeroPad2d(2)
|
| 765 |
+
>>> input = torch.randn(1, 1, 3, 3)
|
| 766 |
+
>>> input
|
| 767 |
+
tensor([[[[-0.1678, -0.4418, 1.9466],
|
| 768 |
+
[ 0.9604, -0.4219, -0.5241],
|
| 769 |
+
[-0.9162, -0.5436, -0.6446]]]])
|
| 770 |
+
>>> m(input)
|
| 771 |
+
tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 772 |
+
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 773 |
+
[ 0.0000, 0.0000, -0.1678, -0.4418, 1.9466, 0.0000, 0.0000],
|
| 774 |
+
[ 0.0000, 0.0000, 0.9604, -0.4219, -0.5241, 0.0000, 0.0000],
|
| 775 |
+
[ 0.0000, 0.0000, -0.9162, -0.5436, -0.6446, 0.0000, 0.0000],
|
| 776 |
+
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 777 |
+
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]])
|
| 778 |
+
>>> # using different paddings for different sides
|
| 779 |
+
>>> m = nn.ZeroPad2d((1, 1, 2, 0))
|
| 780 |
+
>>> m(input)
|
| 781 |
+
tensor([[[[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 782 |
+
[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
|
| 783 |
+
[ 0.0000, -0.1678, -0.4418, 1.9466, 0.0000],
|
| 784 |
+
[ 0.0000, 0.9604, -0.4219, -0.5241, 0.0000],
|
| 785 |
+
[ 0.0000, -0.9162, -0.5436, -0.6446, 0.0000]]]])
|
| 786 |
+
"""
|
| 787 |
+
|
| 788 |
+
padding: tuple[int, int, int, int]
|
| 789 |
+
|
| 790 |
+
def __init__(self, padding: _size_4_t) -> None:
|
| 791 |
+
super().__init__(padding, 0.0)
|
| 792 |
+
|
| 793 |
+
def extra_repr(self) -> str:
|
| 794 |
+
"""
|
| 795 |
+
Return the extra representation of the module.
|
| 796 |
+
"""
|
| 797 |
+
return f"{self.padding}"
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
class ZeroPad3d(ConstantPad3d):
|
| 801 |
+
r"""Pads the input tensor boundaries with zero.
|
| 802 |
+
|
| 803 |
+
For `N`-dimensional padding, use :func:`torch.nn.functional.pad()`.
|
| 804 |
+
|
| 805 |
+
Args:
|
| 806 |
+
padding (int, tuple): the size of the padding. If it is `int`, uses the same
|
| 807 |
+
padding in all boundaries. If a 6-`tuple`, uses
|
| 808 |
+
(:math:`\text{padding\_left}`, :math:`\text{padding\_right}`,
|
| 809 |
+
:math:`\text{padding\_top}`, :math:`\text{padding\_bottom}`,
|
| 810 |
+
:math:`\text{padding\_front}`, :math:`\text{padding\_back}`)
|
| 811 |
+
|
| 812 |
+
Shape:
|
| 813 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 814 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or
|
| 815 |
+
:math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 816 |
+
|
| 817 |
+
:math:`D_{out} = D_{in} + \text{padding\_front} + \text{padding\_back}`
|
| 818 |
+
|
| 819 |
+
:math:`H_{out} = H_{in} + \text{padding\_top} + \text{padding\_bottom}`
|
| 820 |
+
|
| 821 |
+
:math:`W_{out} = W_{in} + \text{padding\_left} + \text{padding\_right}`
|
| 822 |
+
|
| 823 |
+
Examples::
|
| 824 |
+
|
| 825 |
+
>>> m = nn.ZeroPad3d(3)
|
| 826 |
+
>>> input = torch.randn(16, 3, 10, 20, 30)
|
| 827 |
+
>>> output = m(input)
|
| 828 |
+
>>> # using different paddings for different sides
|
| 829 |
+
>>> m = nn.ZeroPad3d((3, 3, 6, 6, 0, 1))
|
| 830 |
+
>>> output = m(input)
|
| 831 |
+
"""
|
| 832 |
+
|
| 833 |
+
padding: tuple[int, int, int, int, int, int]
|
| 834 |
+
|
| 835 |
+
def __init__(self, padding: _size_6_t) -> None:
|
| 836 |
+
super().__init__(padding, 0.0)
|
| 837 |
+
|
| 838 |
+
def extra_repr(self) -> str:
|
| 839 |
+
"""
|
| 840 |
+
Return the extra representation of the module.
|
| 841 |
+
"""
|
| 842 |
+
return f"{self.padding}"
|
.venv/lib/python3.12/site-packages/torch/nn/modules/pixelshuffle.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
|
| 4 |
+
from .module import Module
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
__all__ = ["PixelShuffle", "PixelUnshuffle"]
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class PixelShuffle(Module):
|
| 11 |
+
r"""Rearrange elements in a tensor according to an upscaling factor.
|
| 12 |
+
|
| 13 |
+
Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)`
|
| 14 |
+
to a tensor of shape :math:`(*, C, H \times r, W \times r)`, where r is an upscale factor.
|
| 15 |
+
|
| 16 |
+
This is useful for implementing efficient sub-pixel convolution
|
| 17 |
+
with a stride of :math:`1/r`.
|
| 18 |
+
|
| 19 |
+
See the paper:
|
| 20 |
+
`Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network`_
|
| 21 |
+
by Shi et al. (2016) for more details.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
upscale_factor (int): factor to increase spatial resolution by
|
| 25 |
+
|
| 26 |
+
Shape:
|
| 27 |
+
- Input: :math:`(*, C_{in}, H_{in}, W_{in})`, where * is zero or more batch dimensions
|
| 28 |
+
- Output: :math:`(*, C_{out}, H_{out}, W_{out})`, where
|
| 29 |
+
|
| 30 |
+
.. math::
|
| 31 |
+
C_{out} = C_{in} \div \text{upscale\_factor}^2
|
| 32 |
+
|
| 33 |
+
.. math::
|
| 34 |
+
H_{out} = H_{in} \times \text{upscale\_factor}
|
| 35 |
+
|
| 36 |
+
.. math::
|
| 37 |
+
W_{out} = W_{in} \times \text{upscale\_factor}
|
| 38 |
+
|
| 39 |
+
Examples::
|
| 40 |
+
|
| 41 |
+
>>> pixel_shuffle = nn.PixelShuffle(3)
|
| 42 |
+
>>> input = torch.randn(1, 9, 4, 4)
|
| 43 |
+
>>> output = pixel_shuffle(input)
|
| 44 |
+
>>> print(output.size())
|
| 45 |
+
torch.Size([1, 1, 12, 12])
|
| 46 |
+
|
| 47 |
+
.. _Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network:
|
| 48 |
+
https://arxiv.org/abs/1609.05158
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
__constants__ = ["upscale_factor"]
|
| 52 |
+
upscale_factor: int
|
| 53 |
+
|
| 54 |
+
def __init__(self, upscale_factor: int) -> None:
|
| 55 |
+
super().__init__()
|
| 56 |
+
self.upscale_factor = upscale_factor
|
| 57 |
+
|
| 58 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 59 |
+
"""
|
| 60 |
+
Runs the forward pass.
|
| 61 |
+
"""
|
| 62 |
+
return F.pixel_shuffle(input, self.upscale_factor)
|
| 63 |
+
|
| 64 |
+
def extra_repr(self) -> str:
|
| 65 |
+
"""
|
| 66 |
+
Return the extra representation of the module.
|
| 67 |
+
"""
|
| 68 |
+
return f"upscale_factor={self.upscale_factor}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class PixelUnshuffle(Module):
|
| 72 |
+
r"""Reverse the PixelShuffle operation.
|
| 73 |
+
|
| 74 |
+
Reverses the :class:`~torch.nn.PixelShuffle` operation by rearranging elements
|
| 75 |
+
in a tensor of shape :math:`(*, C, H \times r, W \times r)` to a tensor of shape
|
| 76 |
+
:math:`(*, C \times r^2, H, W)`, where r is a downscale factor.
|
| 77 |
+
|
| 78 |
+
See the paper:
|
| 79 |
+
`Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network`_
|
| 80 |
+
by Shi et al. (2016) for more details.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
downscale_factor (int): factor to decrease spatial resolution by
|
| 84 |
+
|
| 85 |
+
Shape:
|
| 86 |
+
- Input: :math:`(*, C_{in}, H_{in}, W_{in})`, where * is zero or more batch dimensions
|
| 87 |
+
- Output: :math:`(*, C_{out}, H_{out}, W_{out})`, where
|
| 88 |
+
|
| 89 |
+
.. math::
|
| 90 |
+
C_{out} = C_{in} \times \text{downscale\_factor}^2
|
| 91 |
+
|
| 92 |
+
.. math::
|
| 93 |
+
H_{out} = H_{in} \div \text{downscale\_factor}
|
| 94 |
+
|
| 95 |
+
.. math::
|
| 96 |
+
W_{out} = W_{in} \div \text{downscale\_factor}
|
| 97 |
+
|
| 98 |
+
Examples::
|
| 99 |
+
|
| 100 |
+
>>> pixel_unshuffle = nn.PixelUnshuffle(3)
|
| 101 |
+
>>> input = torch.randn(1, 1, 12, 12)
|
| 102 |
+
>>> output = pixel_unshuffle(input)
|
| 103 |
+
>>> print(output.size())
|
| 104 |
+
torch.Size([1, 9, 4, 4])
|
| 105 |
+
|
| 106 |
+
.. _Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network:
|
| 107 |
+
https://arxiv.org/abs/1609.05158
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
__constants__ = ["downscale_factor"]
|
| 111 |
+
downscale_factor: int
|
| 112 |
+
|
| 113 |
+
def __init__(self, downscale_factor: int) -> None:
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.downscale_factor = downscale_factor
|
| 116 |
+
|
| 117 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 118 |
+
"""
|
| 119 |
+
Runs the forward pass.
|
| 120 |
+
"""
|
| 121 |
+
return F.pixel_unshuffle(input, self.downscale_factor)
|
| 122 |
+
|
| 123 |
+
def extra_repr(self) -> str:
|
| 124 |
+
"""
|
| 125 |
+
Return the extra representation of the module.
|
| 126 |
+
"""
|
| 127 |
+
return f"downscale_factor={self.downscale_factor}"
|
.venv/lib/python3.12/site-packages/torch/nn/modules/pooling.py
ADDED
|
@@ -0,0 +1,1554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn.functional as F
|
| 2 |
+
from torch import Tensor
|
| 3 |
+
from torch.nn.common_types import (
|
| 4 |
+
_ratio_2_t,
|
| 5 |
+
_ratio_3_t,
|
| 6 |
+
_size_1_t,
|
| 7 |
+
_size_2_opt_t,
|
| 8 |
+
_size_2_t,
|
| 9 |
+
_size_3_opt_t,
|
| 10 |
+
_size_3_t,
|
| 11 |
+
_size_any_opt_t,
|
| 12 |
+
_size_any_t,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from .module import Module
|
| 16 |
+
from .utils import _pair, _single, _triple
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"MaxPool1d",
|
| 21 |
+
"MaxPool2d",
|
| 22 |
+
"MaxPool3d",
|
| 23 |
+
"MaxUnpool1d",
|
| 24 |
+
"MaxUnpool2d",
|
| 25 |
+
"MaxUnpool3d",
|
| 26 |
+
"AvgPool1d",
|
| 27 |
+
"AvgPool2d",
|
| 28 |
+
"AvgPool3d",
|
| 29 |
+
"FractionalMaxPool2d",
|
| 30 |
+
"FractionalMaxPool3d",
|
| 31 |
+
"LPPool1d",
|
| 32 |
+
"LPPool2d",
|
| 33 |
+
"LPPool3d",
|
| 34 |
+
"AdaptiveMaxPool1d",
|
| 35 |
+
"AdaptiveMaxPool2d",
|
| 36 |
+
"AdaptiveMaxPool3d",
|
| 37 |
+
"AdaptiveAvgPool1d",
|
| 38 |
+
"AdaptiveAvgPool2d",
|
| 39 |
+
"AdaptiveAvgPool3d",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class _MaxPoolNd(Module):
|
| 44 |
+
__constants__ = [
|
| 45 |
+
"kernel_size",
|
| 46 |
+
"stride",
|
| 47 |
+
"padding",
|
| 48 |
+
"dilation",
|
| 49 |
+
"return_indices",
|
| 50 |
+
"ceil_mode",
|
| 51 |
+
]
|
| 52 |
+
return_indices: bool
|
| 53 |
+
ceil_mode: bool
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
kernel_size: _size_any_t,
|
| 58 |
+
stride: _size_any_t | None = None,
|
| 59 |
+
padding: _size_any_t = 0,
|
| 60 |
+
dilation: _size_any_t = 1,
|
| 61 |
+
return_indices: bool = False,
|
| 62 |
+
ceil_mode: bool = False,
|
| 63 |
+
) -> None:
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.kernel_size = kernel_size
|
| 66 |
+
self.stride = stride if (stride is not None) else kernel_size
|
| 67 |
+
self.padding = padding
|
| 68 |
+
self.dilation = dilation
|
| 69 |
+
self.return_indices = return_indices
|
| 70 |
+
self.ceil_mode = ceil_mode
|
| 71 |
+
|
| 72 |
+
def extra_repr(self) -> str:
|
| 73 |
+
return (
|
| 74 |
+
"kernel_size={kernel_size}, stride={stride}, padding={padding}"
|
| 75 |
+
", dilation={dilation}, ceil_mode={ceil_mode}".format(**self.__dict__)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class MaxPool1d(_MaxPoolNd):
|
| 80 |
+
r"""Applies a 1D max pooling over an input signal composed of several input planes.
|
| 81 |
+
|
| 82 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, L)`
|
| 83 |
+
and output :math:`(N, C, L_{out})` can be precisely described as:
|
| 84 |
+
|
| 85 |
+
.. math::
|
| 86 |
+
out(N_i, C_j, k) = \max_{m=0, \ldots, \text{kernel\_size} - 1}
|
| 87 |
+
input(N_i, C_j, stride \times k + m)
|
| 88 |
+
|
| 89 |
+
If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
|
| 90 |
+
for :attr:`padding` number of points. :attr:`dilation` is the stride between the elements within the
|
| 91 |
+
sliding window. This `link`_ has a nice visualization of the pooling parameters.
|
| 92 |
+
|
| 93 |
+
Note:
|
| 94 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 95 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
kernel_size: The size of the sliding window, must be > 0.
|
| 99 |
+
stride: The stride of the sliding window, must be > 0. Default value is :attr:`kernel_size`.
|
| 100 |
+
padding: Implicit negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
|
| 101 |
+
dilation: The stride between elements within a sliding window, must be > 0.
|
| 102 |
+
return_indices: If ``True``, will return the argmax along with the max values.
|
| 103 |
+
Useful for :class:`torch.nn.MaxUnpool1d` later
|
| 104 |
+
ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
|
| 105 |
+
ensures that every element in the input tensor is covered by a sliding window.
|
| 106 |
+
|
| 107 |
+
Shape:
|
| 108 |
+
- Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
|
| 109 |
+
- Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`,
|
| 110 |
+
|
| 111 |
+
where ``ceil_mode = False``
|
| 112 |
+
|
| 113 |
+
.. math::
|
| 114 |
+
L_{out} = \left\lfloor \frac{L_{in} + 2 \times \text{padding} - \text{dilation}
|
| 115 |
+
\times (\text{kernel\_size} - 1) - 1}{\text{stride}}\right\rfloor + 1
|
| 116 |
+
|
| 117 |
+
where ``ceil_mode = True``
|
| 118 |
+
|
| 119 |
+
.. math::
|
| 120 |
+
L_{out} = \left\lfloor \frac{L_{in} + 2 \times \text{padding} - \text{dilation}
|
| 121 |
+
\times (\text{kernel\_size} - 1) - 1 + (\text{stride} - 1)}{\text{stride}}\right\rfloor + 1
|
| 122 |
+
|
| 123 |
+
- Ensure that the last pooling starts inside the image, make :math:`L_{out} = L_{out} - 1`
|
| 124 |
+
when :math:`(L_{out} - 1) * \text{stride} >= L_{in} + \text{padding}`.
|
| 125 |
+
|
| 126 |
+
Examples::
|
| 127 |
+
|
| 128 |
+
>>> # pool of size=3, stride=2
|
| 129 |
+
>>> m = nn.MaxPool1d(3, stride=2)
|
| 130 |
+
>>> input = torch.randn(20, 16, 50)
|
| 131 |
+
>>> output = m(input)
|
| 132 |
+
|
| 133 |
+
.. _link:
|
| 134 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
kernel_size: _size_1_t
|
| 138 |
+
stride: _size_1_t
|
| 139 |
+
padding: _size_1_t
|
| 140 |
+
dilation: _size_1_t
|
| 141 |
+
|
| 142 |
+
def forward(self, input: Tensor):
|
| 143 |
+
"""Runs the forward pass."""
|
| 144 |
+
return F.max_pool1d(
|
| 145 |
+
input,
|
| 146 |
+
self.kernel_size,
|
| 147 |
+
self.stride,
|
| 148 |
+
self.padding,
|
| 149 |
+
self.dilation,
|
| 150 |
+
ceil_mode=self.ceil_mode,
|
| 151 |
+
return_indices=self.return_indices,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
class MaxPool2d(_MaxPoolNd):
|
| 156 |
+
r"""Applies a 2D max pooling over an input signal composed of several input planes.
|
| 157 |
+
|
| 158 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
|
| 159 |
+
output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
|
| 160 |
+
can be precisely described as:
|
| 161 |
+
|
| 162 |
+
.. math::
|
| 163 |
+
\begin{aligned}
|
| 164 |
+
out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
|
| 165 |
+
& \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
|
| 166 |
+
\text{stride[1]} \times w + n)
|
| 167 |
+
\end{aligned}
|
| 168 |
+
|
| 169 |
+
If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
|
| 170 |
+
for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
|
| 171 |
+
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
|
| 172 |
+
|
| 173 |
+
Note:
|
| 174 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 175 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 176 |
+
|
| 177 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
|
| 178 |
+
|
| 179 |
+
- a single ``int`` -- in which case the same value is used for the height and width dimension
|
| 180 |
+
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
|
| 181 |
+
and the second `int` for the width dimension
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
kernel_size: the size of the window to take a max over
|
| 185 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 186 |
+
padding: Implicit negative infinity padding to be added on both sides
|
| 187 |
+
dilation: a parameter that controls the stride of elements in the window
|
| 188 |
+
return_indices: if ``True``, will return the max indices along with the outputs.
|
| 189 |
+
Useful for :class:`torch.nn.MaxUnpool2d` later
|
| 190 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 191 |
+
|
| 192 |
+
Shape:
|
| 193 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`
|
| 194 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 195 |
+
|
| 196 |
+
.. math::
|
| 197 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 * \text{padding[0]} - \text{dilation[0]}
|
| 198 |
+
\times (\text{kernel\_size[0]} - 1) - 1}{\text{stride[0]}} + 1\right\rfloor
|
| 199 |
+
|
| 200 |
+
.. math::
|
| 201 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 * \text{padding[1]} - \text{dilation[1]}
|
| 202 |
+
\times (\text{kernel\_size[1]} - 1) - 1}{\text{stride[1]}} + 1\right\rfloor
|
| 203 |
+
|
| 204 |
+
Examples::
|
| 205 |
+
|
| 206 |
+
>>> # pool of square window of size=3, stride=2
|
| 207 |
+
>>> m = nn.MaxPool2d(3, stride=2)
|
| 208 |
+
>>> # pool of non-square window
|
| 209 |
+
>>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
|
| 210 |
+
>>> input = torch.randn(20, 16, 50, 32)
|
| 211 |
+
>>> output = m(input)
|
| 212 |
+
|
| 213 |
+
.. _link:
|
| 214 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
kernel_size: _size_2_t
|
| 218 |
+
stride: _size_2_t
|
| 219 |
+
padding: _size_2_t
|
| 220 |
+
dilation: _size_2_t
|
| 221 |
+
|
| 222 |
+
def forward(self, input: Tensor):
|
| 223 |
+
"""Runs the forward pass."""
|
| 224 |
+
return F.max_pool2d(
|
| 225 |
+
input,
|
| 226 |
+
self.kernel_size,
|
| 227 |
+
self.stride,
|
| 228 |
+
self.padding,
|
| 229 |
+
self.dilation,
|
| 230 |
+
ceil_mode=self.ceil_mode,
|
| 231 |
+
return_indices=self.return_indices,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class MaxPool3d(_MaxPoolNd):
|
| 236 |
+
r"""Applies a 3D max pooling over an input signal composed of several input planes.
|
| 237 |
+
|
| 238 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
|
| 239 |
+
output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
|
| 240 |
+
can be precisely described as:
|
| 241 |
+
|
| 242 |
+
.. math::
|
| 243 |
+
\begin{aligned}
|
| 244 |
+
\text{out}(N_i, C_j, d, h, w) ={} & \max_{k=0, \ldots, kD-1} \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
|
| 245 |
+
& \text{input}(N_i, C_j, \text{stride[0]} \times d + k,
|
| 246 |
+
\text{stride[1]} \times h + m, \text{stride[2]} \times w + n)
|
| 247 |
+
\end{aligned}
|
| 248 |
+
|
| 249 |
+
If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
|
| 250 |
+
for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
|
| 251 |
+
It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
|
| 252 |
+
|
| 253 |
+
Note:
|
| 254 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 255 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 256 |
+
|
| 257 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
|
| 258 |
+
|
| 259 |
+
- a single ``int`` -- in which case the same value is used for the depth, height and width dimension
|
| 260 |
+
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
|
| 261 |
+
the second `int` for the height dimension and the third `int` for the width dimension
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
kernel_size: the size of the window to take a max over
|
| 265 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 266 |
+
padding: Implicit negative infinity padding to be added on all three sides
|
| 267 |
+
dilation: a parameter that controls the stride of elements in the window
|
| 268 |
+
return_indices: if ``True``, will return the max indices along with the outputs.
|
| 269 |
+
Useful for :class:`torch.nn.MaxUnpool3d` later
|
| 270 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 271 |
+
|
| 272 |
+
Shape:
|
| 273 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 274 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 275 |
+
|
| 276 |
+
.. math::
|
| 277 |
+
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times
|
| 278 |
+
(\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
|
| 279 |
+
|
| 280 |
+
.. math::
|
| 281 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times
|
| 282 |
+
(\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
|
| 283 |
+
|
| 284 |
+
.. math::
|
| 285 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] \times
|
| 286 |
+
(\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
|
| 287 |
+
|
| 288 |
+
Examples::
|
| 289 |
+
|
| 290 |
+
>>> # pool of square window of size=3, stride=2
|
| 291 |
+
>>> m = nn.MaxPool3d(3, stride=2)
|
| 292 |
+
>>> # pool of non-square window
|
| 293 |
+
>>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2))
|
| 294 |
+
>>> input = torch.randn(20, 16, 50, 44, 31)
|
| 295 |
+
>>> output = m(input)
|
| 296 |
+
|
| 297 |
+
.. _link:
|
| 298 |
+
https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
kernel_size: _size_3_t
|
| 302 |
+
stride: _size_3_t
|
| 303 |
+
padding: _size_3_t
|
| 304 |
+
dilation: _size_3_t
|
| 305 |
+
|
| 306 |
+
def forward(self, input: Tensor):
|
| 307 |
+
"""Runs the forward pass."""
|
| 308 |
+
return F.max_pool3d(
|
| 309 |
+
input,
|
| 310 |
+
self.kernel_size,
|
| 311 |
+
self.stride,
|
| 312 |
+
self.padding,
|
| 313 |
+
self.dilation,
|
| 314 |
+
ceil_mode=self.ceil_mode,
|
| 315 |
+
return_indices=self.return_indices,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class _MaxUnpoolNd(Module):
|
| 320 |
+
def extra_repr(self) -> str:
|
| 321 |
+
return f"kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}"
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class MaxUnpool1d(_MaxUnpoolNd):
|
| 325 |
+
r"""Computes a partial inverse of :class:`MaxPool1d`.
|
| 326 |
+
|
| 327 |
+
:class:`MaxPool1d` is not fully invertible, since the non-maximal values are lost.
|
| 328 |
+
|
| 329 |
+
:class:`MaxUnpool1d` takes in as input the output of :class:`MaxPool1d`
|
| 330 |
+
including the indices of the maximal values and computes a partial inverse
|
| 331 |
+
in which all non-maximal values are set to zero.
|
| 332 |
+
|
| 333 |
+
Note:
|
| 334 |
+
This operation may behave nondeterministically when the input indices has repeat values.
|
| 335 |
+
See https://github.com/pytorch/pytorch/issues/80827 and :doc:`/notes/randomness` for more information.
|
| 336 |
+
|
| 337 |
+
.. note:: :class:`MaxPool1d` can map several input sizes to the same output
|
| 338 |
+
sizes. Hence, the inversion process can get ambiguous.
|
| 339 |
+
To accommodate this, you can provide the needed output size
|
| 340 |
+
as an additional argument :attr:`output_size` in the forward call.
|
| 341 |
+
See the Inputs and Example below.
|
| 342 |
+
|
| 343 |
+
Args:
|
| 344 |
+
kernel_size (int or tuple): Size of the max pooling window.
|
| 345 |
+
stride (int or tuple): Stride of the max pooling window.
|
| 346 |
+
It is set to :attr:`kernel_size` by default.
|
| 347 |
+
padding (int or tuple): Padding that was added to the input
|
| 348 |
+
|
| 349 |
+
Inputs:
|
| 350 |
+
- `input`: the input Tensor to invert
|
| 351 |
+
- `indices`: the indices given out by :class:`~torch.nn.MaxPool1d`
|
| 352 |
+
- `output_size` (optional): the targeted output size
|
| 353 |
+
|
| 354 |
+
Shape:
|
| 355 |
+
- Input: :math:`(N, C, H_{in})` or :math:`(C, H_{in})`.
|
| 356 |
+
- Output: :math:`(N, C, H_{out})` or :math:`(C, H_{out})`, where
|
| 357 |
+
|
| 358 |
+
.. math::
|
| 359 |
+
H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{kernel\_size}[0]
|
| 360 |
+
|
| 361 |
+
or as given by :attr:`output_size` in the call operator
|
| 362 |
+
|
| 363 |
+
Example::
|
| 364 |
+
|
| 365 |
+
>>> # xdoctest: +IGNORE_WANT("do other tests modify the global state?")
|
| 366 |
+
>>> pool = nn.MaxPool1d(2, stride=2, return_indices=True)
|
| 367 |
+
>>> unpool = nn.MaxUnpool1d(2, stride=2)
|
| 368 |
+
>>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8]]])
|
| 369 |
+
>>> output, indices = pool(input)
|
| 370 |
+
>>> unpool(output, indices)
|
| 371 |
+
tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]])
|
| 372 |
+
|
| 373 |
+
>>> # Example showcasing the use of output_size
|
| 374 |
+
>>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8, 9]]])
|
| 375 |
+
>>> output, indices = pool(input)
|
| 376 |
+
>>> unpool(output, indices, output_size=input.size())
|
| 377 |
+
tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8., 0.]]])
|
| 378 |
+
|
| 379 |
+
>>> unpool(output, indices)
|
| 380 |
+
tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]])
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
kernel_size: _size_1_t
|
| 384 |
+
stride: _size_1_t
|
| 385 |
+
padding: _size_1_t
|
| 386 |
+
|
| 387 |
+
def __init__(
|
| 388 |
+
self,
|
| 389 |
+
kernel_size: _size_1_t,
|
| 390 |
+
stride: _size_1_t | None = None,
|
| 391 |
+
padding: _size_1_t = 0,
|
| 392 |
+
) -> None:
|
| 393 |
+
super().__init__()
|
| 394 |
+
self.kernel_size = _single(kernel_size)
|
| 395 |
+
self.stride = _single(stride if (stride is not None) else kernel_size)
|
| 396 |
+
self.padding = _single(padding)
|
| 397 |
+
|
| 398 |
+
def forward(
|
| 399 |
+
self, input: Tensor, indices: Tensor, output_size: list[int] | None = None
|
| 400 |
+
) -> Tensor:
|
| 401 |
+
"""Runs the forward pass."""
|
| 402 |
+
return F.max_unpool1d(
|
| 403 |
+
input, indices, self.kernel_size, self.stride, self.padding, output_size
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class MaxUnpool2d(_MaxUnpoolNd):
|
| 408 |
+
r"""Computes a partial inverse of :class:`MaxPool2d`.
|
| 409 |
+
|
| 410 |
+
:class:`MaxPool2d` is not fully invertible, since the non-maximal values are lost.
|
| 411 |
+
|
| 412 |
+
:class:`MaxUnpool2d` takes in as input the output of :class:`MaxPool2d`
|
| 413 |
+
including the indices of the maximal values and computes a partial inverse
|
| 414 |
+
in which all non-maximal values are set to zero.
|
| 415 |
+
|
| 416 |
+
Note:
|
| 417 |
+
This operation may behave nondeterministically when the input indices has repeat values.
|
| 418 |
+
See https://github.com/pytorch/pytorch/issues/80827 and :doc:`/notes/randomness` for more information.
|
| 419 |
+
|
| 420 |
+
.. note:: :class:`MaxPool2d` can map several input sizes to the same output
|
| 421 |
+
sizes. Hence, the inversion process can get ambiguous.
|
| 422 |
+
To accommodate this, you can provide the needed output size
|
| 423 |
+
as an additional argument :attr:`output_size` in the forward call.
|
| 424 |
+
See the Inputs and Example below.
|
| 425 |
+
|
| 426 |
+
Args:
|
| 427 |
+
kernel_size (int or tuple): Size of the max pooling window.
|
| 428 |
+
stride (int or tuple): Stride of the max pooling window.
|
| 429 |
+
It is set to :attr:`kernel_size` by default.
|
| 430 |
+
padding (int or tuple): Padding that was added to the input
|
| 431 |
+
|
| 432 |
+
Inputs:
|
| 433 |
+
- `input`: the input Tensor to invert
|
| 434 |
+
- `indices`: the indices given out by :class:`~torch.nn.MaxPool2d`
|
| 435 |
+
- `output_size` (optional): the targeted output size
|
| 436 |
+
|
| 437 |
+
Shape:
|
| 438 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 439 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 440 |
+
|
| 441 |
+
.. math::
|
| 442 |
+
H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}
|
| 443 |
+
|
| 444 |
+
.. math::
|
| 445 |
+
W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}
|
| 446 |
+
|
| 447 |
+
or as given by :attr:`output_size` in the call operator
|
| 448 |
+
|
| 449 |
+
Example::
|
| 450 |
+
|
| 451 |
+
>>> pool = nn.MaxPool2d(2, stride=2, return_indices=True)
|
| 452 |
+
>>> unpool = nn.MaxUnpool2d(2, stride=2)
|
| 453 |
+
>>> input = torch.tensor([[[[ 1., 2., 3., 4.],
|
| 454 |
+
[ 5., 6., 7., 8.],
|
| 455 |
+
[ 9., 10., 11., 12.],
|
| 456 |
+
[13., 14., 15., 16.]]]])
|
| 457 |
+
>>> output, indices = pool(input)
|
| 458 |
+
>>> unpool(output, indices)
|
| 459 |
+
tensor([[[[ 0., 0., 0., 0.],
|
| 460 |
+
[ 0., 6., 0., 8.],
|
| 461 |
+
[ 0., 0., 0., 0.],
|
| 462 |
+
[ 0., 14., 0., 16.]]]])
|
| 463 |
+
>>> # Now using output_size to resolve an ambiguous size for the inverse
|
| 464 |
+
>>> input = torch.tensor([[[[ 1., 2., 3., 4., 5.],
|
| 465 |
+
[ 6., 7., 8., 9., 10.],
|
| 466 |
+
[11., 12., 13., 14., 15.],
|
| 467 |
+
[16., 17., 18., 19., 20.]]]])
|
| 468 |
+
>>> output, indices = pool(input)
|
| 469 |
+
>>> # This call will not work without specifying output_size
|
| 470 |
+
>>> unpool(output, indices, output_size=input.size())
|
| 471 |
+
tensor([[[[ 0., 0., 0., 0., 0.],
|
| 472 |
+
[ 0., 7., 0., 9., 0.],
|
| 473 |
+
[ 0., 0., 0., 0., 0.],
|
| 474 |
+
[ 0., 17., 0., 19., 0.]]]])
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
kernel_size: _size_2_t
|
| 480 |
+
stride: _size_2_t
|
| 481 |
+
padding: _size_2_t
|
| 482 |
+
|
| 483 |
+
def __init__(
|
| 484 |
+
self,
|
| 485 |
+
kernel_size: _size_2_t,
|
| 486 |
+
stride: _size_2_t | None = None,
|
| 487 |
+
padding: _size_2_t = 0,
|
| 488 |
+
) -> None:
|
| 489 |
+
super().__init__()
|
| 490 |
+
self.kernel_size = _pair(kernel_size)
|
| 491 |
+
self.stride = _pair(stride if (stride is not None) else kernel_size)
|
| 492 |
+
self.padding = _pair(padding)
|
| 493 |
+
|
| 494 |
+
def forward(
|
| 495 |
+
self, input: Tensor, indices: Tensor, output_size: list[int] | None = None
|
| 496 |
+
) -> Tensor:
|
| 497 |
+
"""Runs the forward pass."""
|
| 498 |
+
return F.max_unpool2d(
|
| 499 |
+
input, indices, self.kernel_size, self.stride, self.padding, output_size
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class MaxUnpool3d(_MaxUnpoolNd):
|
| 504 |
+
r"""Computes a partial inverse of :class:`MaxPool3d`.
|
| 505 |
+
|
| 506 |
+
:class:`MaxPool3d` is not fully invertible, since the non-maximal values are lost.
|
| 507 |
+
:class:`MaxUnpool3d` takes in as input the output of :class:`MaxPool3d`
|
| 508 |
+
including the indices of the maximal values and computes a partial inverse
|
| 509 |
+
in which all non-maximal values are set to zero.
|
| 510 |
+
|
| 511 |
+
Note:
|
| 512 |
+
This operation may behave nondeterministically when the input indices has repeat values.
|
| 513 |
+
See https://github.com/pytorch/pytorch/issues/80827 and :doc:`/notes/randomness` for more information.
|
| 514 |
+
|
| 515 |
+
.. note:: :class:`MaxPool3d` can map several input sizes to the same output
|
| 516 |
+
sizes. Hence, the inversion process can get ambiguous.
|
| 517 |
+
To accommodate this, you can provide the needed output size
|
| 518 |
+
as an additional argument :attr:`output_size` in the forward call.
|
| 519 |
+
See the Inputs section below.
|
| 520 |
+
|
| 521 |
+
Args:
|
| 522 |
+
kernel_size (int or tuple): Size of the max pooling window.
|
| 523 |
+
stride (int or tuple): Stride of the max pooling window.
|
| 524 |
+
It is set to :attr:`kernel_size` by default.
|
| 525 |
+
padding (int or tuple): Padding that was added to the input
|
| 526 |
+
|
| 527 |
+
Inputs:
|
| 528 |
+
- `input`: the input Tensor to invert
|
| 529 |
+
- `indices`: the indices given out by :class:`~torch.nn.MaxPool3d`
|
| 530 |
+
- `output_size` (optional): the targeted output size
|
| 531 |
+
|
| 532 |
+
Shape:
|
| 533 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 534 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 535 |
+
|
| 536 |
+
.. math::
|
| 537 |
+
D_{out} = (D_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}
|
| 538 |
+
|
| 539 |
+
.. math::
|
| 540 |
+
H_{out} = (H_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}
|
| 541 |
+
|
| 542 |
+
.. math::
|
| 543 |
+
W_{out} = (W_{in} - 1) \times \text{stride[2]} - 2 \times \text{padding[2]} + \text{kernel\_size[2]}
|
| 544 |
+
|
| 545 |
+
or as given by :attr:`output_size` in the call operator
|
| 546 |
+
|
| 547 |
+
Example::
|
| 548 |
+
|
| 549 |
+
>>> # pool of square window of size=3, stride=2
|
| 550 |
+
>>> pool = nn.MaxPool3d(3, stride=2, return_indices=True)
|
| 551 |
+
>>> unpool = nn.MaxUnpool3d(3, stride=2)
|
| 552 |
+
>>> output, indices = pool(torch.randn(20, 16, 51, 33, 15))
|
| 553 |
+
>>> unpooled_output = unpool(output, indices)
|
| 554 |
+
>>> unpooled_output.size()
|
| 555 |
+
torch.Size([20, 16, 51, 33, 15])
|
| 556 |
+
"""
|
| 557 |
+
|
| 558 |
+
kernel_size: _size_3_t
|
| 559 |
+
stride: _size_3_t
|
| 560 |
+
padding: _size_3_t
|
| 561 |
+
|
| 562 |
+
def __init__(
|
| 563 |
+
self,
|
| 564 |
+
kernel_size: _size_3_t,
|
| 565 |
+
stride: _size_3_t | None = None,
|
| 566 |
+
padding: _size_3_t = 0,
|
| 567 |
+
) -> None:
|
| 568 |
+
super().__init__()
|
| 569 |
+
self.kernel_size = _triple(kernel_size)
|
| 570 |
+
self.stride = _triple(stride if (stride is not None) else kernel_size)
|
| 571 |
+
self.padding = _triple(padding)
|
| 572 |
+
|
| 573 |
+
def forward(
|
| 574 |
+
self, input: Tensor, indices: Tensor, output_size: list[int] | None = None
|
| 575 |
+
) -> Tensor:
|
| 576 |
+
"""Runs the forward pass."""
|
| 577 |
+
return F.max_unpool3d(
|
| 578 |
+
input, indices, self.kernel_size, self.stride, self.padding, output_size
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class _AvgPoolNd(Module):
|
| 583 |
+
__constants__ = [
|
| 584 |
+
"kernel_size",
|
| 585 |
+
"stride",
|
| 586 |
+
"padding",
|
| 587 |
+
"ceil_mode",
|
| 588 |
+
"count_include_pad",
|
| 589 |
+
]
|
| 590 |
+
|
| 591 |
+
def extra_repr(self) -> str:
|
| 592 |
+
return f"kernel_size={self.kernel_size}, stride={self.stride}, padding={self.padding}"
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class AvgPool1d(_AvgPoolNd):
|
| 596 |
+
r"""Applies a 1D average pooling over an input signal composed of several input planes.
|
| 597 |
+
|
| 598 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, L)`,
|
| 599 |
+
output :math:`(N, C, L_{out})` and :attr:`kernel_size` :math:`k`
|
| 600 |
+
can be precisely described as:
|
| 601 |
+
|
| 602 |
+
.. math::
|
| 603 |
+
|
| 604 |
+
\text{out}(N_i, C_j, l) = \frac{1}{k} \sum_{m=0}^{k-1}
|
| 605 |
+
\text{input}(N_i, C_j, \text{stride} \times l + m)
|
| 606 |
+
|
| 607 |
+
If :attr:`padding` is non-zero, then the input is implicitly zero-padded on both sides
|
| 608 |
+
for :attr:`padding` number of points.
|
| 609 |
+
|
| 610 |
+
Note:
|
| 611 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 612 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 613 |
+
|
| 614 |
+
.. note::
|
| 615 |
+
pad should be at most half of effective kernel size.
|
| 616 |
+
|
| 617 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding` can each be
|
| 618 |
+
an ``int`` or a one-element tuple.
|
| 619 |
+
|
| 620 |
+
Args:
|
| 621 |
+
kernel_size: the size of the window
|
| 622 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 623 |
+
padding: implicit zero padding to be added on both sides
|
| 624 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 625 |
+
count_include_pad: when True, will include the zero-padding in the averaging calculation
|
| 626 |
+
|
| 627 |
+
Shape:
|
| 628 |
+
- Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
|
| 629 |
+
- Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
|
| 630 |
+
|
| 631 |
+
.. math::
|
| 632 |
+
L_{out} = \left\lfloor \frac{L_{in} +
|
| 633 |
+
2 \times \text{padding} - \text{kernel\_size}}{\text{stride}} + 1\right\rfloor
|
| 634 |
+
|
| 635 |
+
Per the note above, if ``ceil_mode`` is True and :math:`(L_{out} - 1) \times \text{stride} \geq L_{in}
|
| 636 |
+
+ \text{padding}`, we skip the last window as it would start in the right padded region, resulting in
|
| 637 |
+
:math:`L_{out}` being reduced by one.
|
| 638 |
+
|
| 639 |
+
Examples::
|
| 640 |
+
|
| 641 |
+
>>> # pool with window of size=3, stride=2
|
| 642 |
+
>>> m = nn.AvgPool1d(3, stride=2)
|
| 643 |
+
>>> m(torch.tensor([[[1., 2, 3, 4, 5, 6, 7]]]))
|
| 644 |
+
tensor([[[2., 4., 6.]]])
|
| 645 |
+
"""
|
| 646 |
+
|
| 647 |
+
kernel_size: _size_1_t
|
| 648 |
+
stride: _size_1_t
|
| 649 |
+
padding: _size_1_t
|
| 650 |
+
ceil_mode: bool
|
| 651 |
+
count_include_pad: bool
|
| 652 |
+
|
| 653 |
+
def __init__(
|
| 654 |
+
self,
|
| 655 |
+
kernel_size: _size_1_t,
|
| 656 |
+
stride: _size_1_t = None,
|
| 657 |
+
padding: _size_1_t = 0,
|
| 658 |
+
ceil_mode: bool = False,
|
| 659 |
+
count_include_pad: bool = True,
|
| 660 |
+
) -> None:
|
| 661 |
+
super().__init__()
|
| 662 |
+
self.kernel_size = _single(kernel_size)
|
| 663 |
+
self.stride = _single(stride if stride is not None else kernel_size)
|
| 664 |
+
self.padding = _single(padding)
|
| 665 |
+
self.ceil_mode = ceil_mode
|
| 666 |
+
self.count_include_pad = count_include_pad
|
| 667 |
+
|
| 668 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 669 |
+
"""Runs the forward pass."""
|
| 670 |
+
return F.avg_pool1d(
|
| 671 |
+
input,
|
| 672 |
+
self.kernel_size,
|
| 673 |
+
self.stride,
|
| 674 |
+
self.padding,
|
| 675 |
+
self.ceil_mode,
|
| 676 |
+
self.count_include_pad,
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
|
| 680 |
+
class AvgPool2d(_AvgPoolNd):
|
| 681 |
+
r"""Applies a 2D average pooling over an input signal composed of several input planes.
|
| 682 |
+
|
| 683 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
|
| 684 |
+
output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
|
| 685 |
+
can be precisely described as:
|
| 686 |
+
|
| 687 |
+
.. math::
|
| 688 |
+
|
| 689 |
+
out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1}
|
| 690 |
+
input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)
|
| 691 |
+
|
| 692 |
+
If :attr:`padding` is non-zero, then the input is implicitly zero-padded on both sides
|
| 693 |
+
for :attr:`padding` number of points.
|
| 694 |
+
|
| 695 |
+
Note:
|
| 696 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 697 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 698 |
+
|
| 699 |
+
.. note::
|
| 700 |
+
pad should be at most half of effective kernel size.
|
| 701 |
+
|
| 702 |
+
The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding` can either be:
|
| 703 |
+
|
| 704 |
+
- a single ``int`` or a single-element tuple -- in which case the same value is used for the height and width dimension
|
| 705 |
+
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
|
| 706 |
+
and the second `int` for the width dimension
|
| 707 |
+
|
| 708 |
+
Args:
|
| 709 |
+
kernel_size: the size of the window
|
| 710 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 711 |
+
padding: implicit zero padding to be added on both sides
|
| 712 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 713 |
+
count_include_pad: when True, will include the zero-padding in the averaging calculation
|
| 714 |
+
divisor_override: if specified, it will be used as divisor, otherwise size of the pooling region will be used.
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
Shape:
|
| 718 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 719 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 720 |
+
|
| 721 |
+
.. math::
|
| 722 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -
|
| 723 |
+
\text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
|
| 724 |
+
|
| 725 |
+
.. math::
|
| 726 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -
|
| 727 |
+
\text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
|
| 728 |
+
|
| 729 |
+
Per the note above, if ``ceil_mode`` is True and :math:`(H_{out} - 1)\times \text{stride}[0]\geq H_{in}
|
| 730 |
+
+ \text{padding}[0]`, we skip the last window as it would start in the bottom padded region,
|
| 731 |
+
resulting in :math:`H_{out}` being reduced by one.
|
| 732 |
+
|
| 733 |
+
The same applies for :math:`W_{out}`.
|
| 734 |
+
|
| 735 |
+
Examples::
|
| 736 |
+
|
| 737 |
+
>>> # pool of square window of size=3, stride=2
|
| 738 |
+
>>> m = nn.AvgPool2d(3, stride=2)
|
| 739 |
+
>>> # pool of non-square window
|
| 740 |
+
>>> m = nn.AvgPool2d((3, 2), stride=(2, 1))
|
| 741 |
+
>>> input = torch.randn(20, 16, 50, 32)
|
| 742 |
+
>>> output = m(input)
|
| 743 |
+
"""
|
| 744 |
+
|
| 745 |
+
__constants__ = [
|
| 746 |
+
"kernel_size",
|
| 747 |
+
"stride",
|
| 748 |
+
"padding",
|
| 749 |
+
"ceil_mode",
|
| 750 |
+
"count_include_pad",
|
| 751 |
+
"divisor_override",
|
| 752 |
+
]
|
| 753 |
+
|
| 754 |
+
kernel_size: _size_2_t
|
| 755 |
+
stride: _size_2_t
|
| 756 |
+
padding: _size_2_t
|
| 757 |
+
ceil_mode: bool
|
| 758 |
+
count_include_pad: bool
|
| 759 |
+
|
| 760 |
+
def __init__(
|
| 761 |
+
self,
|
| 762 |
+
kernel_size: _size_2_t,
|
| 763 |
+
stride: _size_2_t | None = None,
|
| 764 |
+
padding: _size_2_t = 0,
|
| 765 |
+
ceil_mode: bool = False,
|
| 766 |
+
count_include_pad: bool = True,
|
| 767 |
+
divisor_override: int | None = None,
|
| 768 |
+
) -> None:
|
| 769 |
+
super().__init__()
|
| 770 |
+
self.kernel_size = kernel_size
|
| 771 |
+
self.stride = stride if (stride is not None) else kernel_size
|
| 772 |
+
self.padding = padding
|
| 773 |
+
self.ceil_mode = ceil_mode
|
| 774 |
+
self.count_include_pad = count_include_pad
|
| 775 |
+
self.divisor_override = divisor_override
|
| 776 |
+
|
| 777 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 778 |
+
"""Runs the forward pass."""
|
| 779 |
+
return F.avg_pool2d(
|
| 780 |
+
input,
|
| 781 |
+
self.kernel_size,
|
| 782 |
+
self.stride,
|
| 783 |
+
self.padding,
|
| 784 |
+
self.ceil_mode,
|
| 785 |
+
self.count_include_pad,
|
| 786 |
+
self.divisor_override,
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
|
| 790 |
+
class AvgPool3d(_AvgPoolNd):
|
| 791 |
+
r"""Applies a 3D average pooling over an input signal composed of several input planes.
|
| 792 |
+
|
| 793 |
+
In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
|
| 794 |
+
output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
|
| 795 |
+
can be precisely described as:
|
| 796 |
+
|
| 797 |
+
.. math::
|
| 798 |
+
\begin{aligned}
|
| 799 |
+
\text{out}(N_i, C_j, d, h, w) ={} & \sum_{k=0}^{kD-1} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} \\
|
| 800 |
+
& \frac{\text{input}(N_i, C_j, \text{stride}[0] \times d + k,
|
| 801 |
+
\text{stride}[1] \times h + m, \text{stride}[2] \times w + n)}
|
| 802 |
+
{kD \times kH \times kW}
|
| 803 |
+
\end{aligned}
|
| 804 |
+
|
| 805 |
+
If :attr:`padding` is non-zero, then the input is implicitly zero-padded on all three sides
|
| 806 |
+
for :attr:`padding` number of points.
|
| 807 |
+
|
| 808 |
+
Note:
|
| 809 |
+
When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
|
| 810 |
+
or the input. Sliding windows that would start in the right padded region are ignored.
|
| 811 |
+
|
| 812 |
+
.. note::
|
| 813 |
+
pad should be at most half of effective kernel size.
|
| 814 |
+
|
| 815 |
+
The parameters :attr:`kernel_size`, :attr:`stride` can either be:
|
| 816 |
+
|
| 817 |
+
- a single ``int`` -- in which case the same value is used for the depth, height and width dimension
|
| 818 |
+
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
|
| 819 |
+
the second `int` for the height dimension and the third `int` for the width dimension
|
| 820 |
+
|
| 821 |
+
Args:
|
| 822 |
+
kernel_size: the size of the window
|
| 823 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 824 |
+
padding: implicit zero padding to be added on all three sides
|
| 825 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 826 |
+
count_include_pad: when True, will include the zero-padding in the averaging calculation
|
| 827 |
+
divisor_override: if specified, it will be used as divisor, otherwise :attr:`kernel_size` will be used
|
| 828 |
+
|
| 829 |
+
Shape:
|
| 830 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 831 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or
|
| 832 |
+
:math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 833 |
+
|
| 834 |
+
.. math::
|
| 835 |
+
D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
|
| 836 |
+
\text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
|
| 837 |
+
|
| 838 |
+
.. math::
|
| 839 |
+
H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -
|
| 840 |
+
\text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
|
| 841 |
+
|
| 842 |
+
.. math::
|
| 843 |
+
W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -
|
| 844 |
+
\text{kernel\_size}[2]}{\text{stride}[2]} + 1\right\rfloor
|
| 845 |
+
|
| 846 |
+
Per the note above, if ``ceil_mode`` is True and :math:`(D_{out} - 1)\times \text{stride}[0]\geq D_{in}
|
| 847 |
+
+ \text{padding}[0]`, we skip the last window as it would start in the padded region,
|
| 848 |
+
resulting in :math:`D_{out}` being reduced by one.
|
| 849 |
+
|
| 850 |
+
The same applies for :math:`W_{out}` and :math:`H_{out}`.
|
| 851 |
+
|
| 852 |
+
Examples::
|
| 853 |
+
|
| 854 |
+
>>> # pool of square window of size=3, stride=2
|
| 855 |
+
>>> m = nn.AvgPool3d(3, stride=2)
|
| 856 |
+
>>> # pool of non-square window
|
| 857 |
+
>>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2))
|
| 858 |
+
>>> input = torch.randn(20, 16, 50, 44, 31)
|
| 859 |
+
>>> output = m(input)
|
| 860 |
+
"""
|
| 861 |
+
|
| 862 |
+
__constants__ = [
|
| 863 |
+
"kernel_size",
|
| 864 |
+
"stride",
|
| 865 |
+
"padding",
|
| 866 |
+
"ceil_mode",
|
| 867 |
+
"count_include_pad",
|
| 868 |
+
"divisor_override",
|
| 869 |
+
]
|
| 870 |
+
|
| 871 |
+
kernel_size: _size_3_t
|
| 872 |
+
stride: _size_3_t
|
| 873 |
+
padding: _size_3_t
|
| 874 |
+
ceil_mode: bool
|
| 875 |
+
count_include_pad: bool
|
| 876 |
+
|
| 877 |
+
def __init__(
|
| 878 |
+
self,
|
| 879 |
+
kernel_size: _size_3_t,
|
| 880 |
+
stride: _size_3_t | None = None,
|
| 881 |
+
padding: _size_3_t = 0,
|
| 882 |
+
ceil_mode: bool = False,
|
| 883 |
+
count_include_pad: bool = True,
|
| 884 |
+
divisor_override: int | None = None,
|
| 885 |
+
) -> None:
|
| 886 |
+
super().__init__()
|
| 887 |
+
self.kernel_size = kernel_size
|
| 888 |
+
self.stride = stride if (stride is not None) else kernel_size
|
| 889 |
+
self.padding = padding
|
| 890 |
+
self.ceil_mode = ceil_mode
|
| 891 |
+
self.count_include_pad = count_include_pad
|
| 892 |
+
self.divisor_override = divisor_override
|
| 893 |
+
|
| 894 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 895 |
+
"""Runs the forward pass."""
|
| 896 |
+
return F.avg_pool3d(
|
| 897 |
+
input,
|
| 898 |
+
self.kernel_size,
|
| 899 |
+
self.stride,
|
| 900 |
+
self.padding,
|
| 901 |
+
self.ceil_mode,
|
| 902 |
+
self.count_include_pad,
|
| 903 |
+
self.divisor_override,
|
| 904 |
+
)
|
| 905 |
+
|
| 906 |
+
def __setstate__(self, d):
|
| 907 |
+
super().__setstate__(d)
|
| 908 |
+
self.__dict__.setdefault("padding", 0)
|
| 909 |
+
self.__dict__.setdefault("ceil_mode", False)
|
| 910 |
+
self.__dict__.setdefault("count_include_pad", True)
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
class FractionalMaxPool2d(Module):
|
| 914 |
+
r"""Applies a 2D fractional max pooling over an input signal composed of several input planes.
|
| 915 |
+
|
| 916 |
+
Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
|
| 917 |
+
|
| 918 |
+
The max-pooling operation is applied in :math:`kH \times kW` regions by a stochastic
|
| 919 |
+
step size determined by the target output size.
|
| 920 |
+
The number of output features is equal to the number of input planes.
|
| 921 |
+
|
| 922 |
+
.. note:: Exactly one of ``output_size`` or ``output_ratio`` must be defined.
|
| 923 |
+
|
| 924 |
+
Args:
|
| 925 |
+
kernel_size: the size of the window to take a max over.
|
| 926 |
+
Can be a single number k (for a square kernel of k x k) or a tuple `(kh, kw)`
|
| 927 |
+
output_size: the target output size of the image of the form `oH x oW`.
|
| 928 |
+
Can be a tuple `(oH, oW)` or a single number oH for a square image `oH x oH`.
|
| 929 |
+
Note that we must have :math:`kH + oH - 1 <= H_{in}` and :math:`kW + oW - 1 <= W_{in}`
|
| 930 |
+
output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
|
| 931 |
+
This has to be a number or tuple in the range (0, 1).
|
| 932 |
+
Note that we must have :math:`kH + (output\_ratio\_H * H_{in}) - 1 <= H_{in}`
|
| 933 |
+
and :math:`kW + (output\_ratio\_W * W_{in}) - 1 <= W_{in}`
|
| 934 |
+
return_indices: if ``True``, will return the indices along with the outputs.
|
| 935 |
+
Useful to pass to :meth:`nn.MaxUnpool2d`. Default: ``False``
|
| 936 |
+
|
| 937 |
+
Shape:
|
| 938 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 939 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 940 |
+
:math:`(H_{out}, W_{out})=\text{output\_size}` or
|
| 941 |
+
:math:`(H_{out}, W_{out})=\text{output\_ratio} \times (H_{in}, W_{in})`.
|
| 942 |
+
|
| 943 |
+
Examples:
|
| 944 |
+
>>> # pool of square window of size=3, and target output size 13x12
|
| 945 |
+
>>> m = nn.FractionalMaxPool2d(3, output_size=(13, 12))
|
| 946 |
+
>>> # pool of square window and target output size being half of input image size
|
| 947 |
+
>>> m = nn.FractionalMaxPool2d(3, output_ratio=(0.5, 0.5))
|
| 948 |
+
>>> input = torch.randn(20, 16, 50, 32)
|
| 949 |
+
>>> output = m(input)
|
| 950 |
+
|
| 951 |
+
.. _Fractional MaxPooling:
|
| 952 |
+
https://arxiv.org/abs/1412.6071
|
| 953 |
+
"""
|
| 954 |
+
|
| 955 |
+
__constants__ = ["kernel_size", "return_indices", "output_size", "output_ratio"]
|
| 956 |
+
|
| 957 |
+
kernel_size: _size_2_t
|
| 958 |
+
return_indices: bool
|
| 959 |
+
output_size: _size_2_t
|
| 960 |
+
output_ratio: _ratio_2_t
|
| 961 |
+
|
| 962 |
+
def __init__(
|
| 963 |
+
self,
|
| 964 |
+
kernel_size: _size_2_t,
|
| 965 |
+
output_size: _size_2_t | None = None,
|
| 966 |
+
output_ratio: _ratio_2_t | None = None,
|
| 967 |
+
return_indices: bool = False,
|
| 968 |
+
_random_samples=None,
|
| 969 |
+
) -> None:
|
| 970 |
+
super().__init__()
|
| 971 |
+
self.kernel_size = _pair(kernel_size)
|
| 972 |
+
self.return_indices = return_indices
|
| 973 |
+
self.register_buffer("_random_samples", _random_samples)
|
| 974 |
+
self.output_size = _pair(output_size) if output_size is not None else None
|
| 975 |
+
self.output_ratio = _pair(output_ratio) if output_ratio is not None else None
|
| 976 |
+
if output_size is None and output_ratio is None:
|
| 977 |
+
raise ValueError(
|
| 978 |
+
"FractionalMaxPool2d requires specifying either "
|
| 979 |
+
"an output size, or a pooling ratio"
|
| 980 |
+
)
|
| 981 |
+
if output_size is not None and output_ratio is not None:
|
| 982 |
+
raise ValueError(
|
| 983 |
+
"only one of output_size and output_ratio may be specified"
|
| 984 |
+
)
|
| 985 |
+
if self.output_ratio is not None:
|
| 986 |
+
if not (0 < self.output_ratio[0] < 1 and 0 < self.output_ratio[1] < 1):
|
| 987 |
+
raise ValueError(
|
| 988 |
+
f"output_ratio must be between 0 and 1 (got {output_ratio})"
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
def forward(self, input: Tensor):
|
| 992 |
+
return F.fractional_max_pool2d(
|
| 993 |
+
input,
|
| 994 |
+
self.kernel_size,
|
| 995 |
+
self.output_size,
|
| 996 |
+
self.output_ratio,
|
| 997 |
+
self.return_indices,
|
| 998 |
+
_random_samples=self._random_samples,
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
class FractionalMaxPool3d(Module):
|
| 1003 |
+
r"""Applies a 3D fractional max pooling over an input signal composed of several input planes.
|
| 1004 |
+
|
| 1005 |
+
Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
|
| 1006 |
+
|
| 1007 |
+
The max-pooling operation is applied in :math:`kT \times kH \times kW` regions by a stochastic
|
| 1008 |
+
step size determined by the target output size.
|
| 1009 |
+
The number of output features is equal to the number of input planes.
|
| 1010 |
+
|
| 1011 |
+
.. note:: Exactly one of ``output_size`` or ``output_ratio`` must be defined.
|
| 1012 |
+
|
| 1013 |
+
Args:
|
| 1014 |
+
kernel_size: the size of the window to take a max over.
|
| 1015 |
+
Can be a single number `k` (for a square kernel of `k x k x k`) or a tuple `(kt x kh x kw)`,
|
| 1016 |
+
`k` must be greater than 0.
|
| 1017 |
+
output_size: the target output size of the image of the form `oT x oH x oW`.
|
| 1018 |
+
Can be a tuple `(oT, oH, oW)` or a single number oH for a square image `oH x oH x oH`
|
| 1019 |
+
output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
|
| 1020 |
+
This has to be a number or tuple in the range (0, 1)
|
| 1021 |
+
return_indices: if ``True``, will return the indices along with the outputs.
|
| 1022 |
+
Useful to pass to :meth:`nn.MaxUnpool3d`. Default: ``False``
|
| 1023 |
+
|
| 1024 |
+
Shape:
|
| 1025 |
+
- Input: :math:`(N, C, T_{in}, H_{in}, W_{in})` or :math:`(C, T_{in}, H_{in}, W_{in})`.
|
| 1026 |
+
- Output: :math:`(N, C, T_{out}, H_{out}, W_{out})` or :math:`(C, T_{out}, H_{out}, W_{out})`, where
|
| 1027 |
+
:math:`(T_{out}, H_{out}, W_{out})=\text{output\_size}` or
|
| 1028 |
+
:math:`(T_{out}, H_{out}, W_{out})=\text{output\_ratio} \times (T_{in}, H_{in}, W_{in})`
|
| 1029 |
+
|
| 1030 |
+
Examples:
|
| 1031 |
+
>>> # pool of cubic window of size=3, and target output size 13x12x11
|
| 1032 |
+
>>> m = nn.FractionalMaxPool3d(3, output_size=(13, 12, 11))
|
| 1033 |
+
>>> # pool of cubic window and target output size being half of input size
|
| 1034 |
+
>>> m = nn.FractionalMaxPool3d(3, output_ratio=(0.5, 0.5, 0.5))
|
| 1035 |
+
>>> input = torch.randn(20, 16, 50, 32, 16)
|
| 1036 |
+
>>> output = m(input)
|
| 1037 |
+
|
| 1038 |
+
.. _Fractional MaxPooling:
|
| 1039 |
+
https://arxiv.org/abs/1412.6071
|
| 1040 |
+
"""
|
| 1041 |
+
|
| 1042 |
+
__constants__ = ["kernel_size", "return_indices", "output_size", "output_ratio"]
|
| 1043 |
+
kernel_size: _size_3_t
|
| 1044 |
+
return_indices: bool
|
| 1045 |
+
output_size: _size_3_t
|
| 1046 |
+
output_ratio: _ratio_3_t
|
| 1047 |
+
|
| 1048 |
+
def __init__(
|
| 1049 |
+
self,
|
| 1050 |
+
kernel_size: _size_3_t,
|
| 1051 |
+
output_size: _size_3_t | None = None,
|
| 1052 |
+
output_ratio: _ratio_3_t | None = None,
|
| 1053 |
+
return_indices: bool = False,
|
| 1054 |
+
_random_samples=None,
|
| 1055 |
+
) -> None:
|
| 1056 |
+
super().__init__()
|
| 1057 |
+
if (isinstance(kernel_size, int) and kernel_size <= 0) or (
|
| 1058 |
+
isinstance(kernel_size, (tuple, list))
|
| 1059 |
+
and not all(k > 0 for k in kernel_size)
|
| 1060 |
+
):
|
| 1061 |
+
raise ValueError(
|
| 1062 |
+
f"kernel_size must be greater than 0, but got {kernel_size}"
|
| 1063 |
+
)
|
| 1064 |
+
self.kernel_size = _triple(kernel_size)
|
| 1065 |
+
self.return_indices = return_indices
|
| 1066 |
+
self.register_buffer("_random_samples", _random_samples)
|
| 1067 |
+
self.output_size = _triple(output_size) if output_size is not None else None
|
| 1068 |
+
self.output_ratio = _triple(output_ratio) if output_ratio is not None else None
|
| 1069 |
+
if output_size is None and output_ratio is None:
|
| 1070 |
+
raise ValueError(
|
| 1071 |
+
"FractionalMaxPool3d requires specifying either "
|
| 1072 |
+
"an output size, or a pooling ratio"
|
| 1073 |
+
)
|
| 1074 |
+
if output_size is not None and output_ratio is not None:
|
| 1075 |
+
raise ValueError(
|
| 1076 |
+
"only one of output_size and output_ratio may be specified"
|
| 1077 |
+
)
|
| 1078 |
+
if self.output_ratio is not None:
|
| 1079 |
+
if not (
|
| 1080 |
+
0 < self.output_ratio[0] < 1
|
| 1081 |
+
and 0 < self.output_ratio[1] < 1
|
| 1082 |
+
and 0 < self.output_ratio[2] < 1
|
| 1083 |
+
):
|
| 1084 |
+
raise ValueError(
|
| 1085 |
+
f"output_ratio must be between 0 and 1 (got {output_ratio})"
|
| 1086 |
+
)
|
| 1087 |
+
|
| 1088 |
+
def forward(self, input: Tensor):
|
| 1089 |
+
return F.fractional_max_pool3d(
|
| 1090 |
+
input,
|
| 1091 |
+
self.kernel_size,
|
| 1092 |
+
self.output_size,
|
| 1093 |
+
self.output_ratio,
|
| 1094 |
+
self.return_indices,
|
| 1095 |
+
_random_samples=self._random_samples,
|
| 1096 |
+
)
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
class _LPPoolNd(Module):
|
| 1100 |
+
__constants__ = ["norm_type", "kernel_size", "stride", "ceil_mode"]
|
| 1101 |
+
|
| 1102 |
+
norm_type: float
|
| 1103 |
+
ceil_mode: bool
|
| 1104 |
+
|
| 1105 |
+
def __init__(
|
| 1106 |
+
self,
|
| 1107 |
+
norm_type: float,
|
| 1108 |
+
kernel_size: _size_any_t,
|
| 1109 |
+
stride: _size_any_t | None = None,
|
| 1110 |
+
ceil_mode: bool = False,
|
| 1111 |
+
) -> None:
|
| 1112 |
+
super().__init__()
|
| 1113 |
+
if norm_type == 0:
|
| 1114 |
+
raise ValueError(f"norm_type must be a non-zero value, but got {norm_type}")
|
| 1115 |
+
self.norm_type = norm_type
|
| 1116 |
+
self.kernel_size = kernel_size
|
| 1117 |
+
self.stride = stride
|
| 1118 |
+
self.ceil_mode = ceil_mode
|
| 1119 |
+
|
| 1120 |
+
def extra_repr(self) -> str:
|
| 1121 |
+
return (
|
| 1122 |
+
"norm_type={norm_type}, kernel_size={kernel_size}, stride={stride}, "
|
| 1123 |
+
"ceil_mode={ceil_mode}".format(**self.__dict__)
|
| 1124 |
+
)
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
class LPPool1d(_LPPoolNd):
|
| 1128 |
+
r"""Applies a 1D power-average pooling over an input signal composed of several input planes.
|
| 1129 |
+
|
| 1130 |
+
On each window, the function computed is:
|
| 1131 |
+
|
| 1132 |
+
.. math::
|
| 1133 |
+
f(X) = \sqrt[p]{\sum_{x \in X} x^{p}}
|
| 1134 |
+
|
| 1135 |
+
- At p = :math:`\infty`, one gets Max Pooling over absolute values
|
| 1136 |
+
- At p = 1, one gets Sum Pooling (which is proportional to Average Pooling)
|
| 1137 |
+
|
| 1138 |
+
.. note:: If the sum to the power of `p` is zero, the gradient of this function is
|
| 1139 |
+
not defined. This implementation will set the gradient to zero in this case.
|
| 1140 |
+
|
| 1141 |
+
Args:
|
| 1142 |
+
kernel_size: a single int, the size of the window
|
| 1143 |
+
stride: a single int, the stride of the window. Default value is :attr:`kernel_size`
|
| 1144 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 1145 |
+
|
| 1146 |
+
Note:
|
| 1147 |
+
When :attr:`ceil_mode` is ``True``, sliding windows may go off-bounds if they start within the
|
| 1148 |
+
left padding or the input. Sliding windows that would start in the right padded region are ignored.
|
| 1149 |
+
|
| 1150 |
+
Shape:
|
| 1151 |
+
- Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
|
| 1152 |
+
- Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
|
| 1153 |
+
|
| 1154 |
+
.. math::
|
| 1155 |
+
L_{out} = \left\lfloor\frac{L_{in} - \text{kernel\_size}}{\text{stride}} + 1\right\rfloor
|
| 1156 |
+
|
| 1157 |
+
Examples::
|
| 1158 |
+
>>> # power-2 pool of window of length 3, with stride 2.
|
| 1159 |
+
>>> m = nn.LPPool1d(2, 3, stride=2)
|
| 1160 |
+
>>> input = torch.randn(20, 16, 50)
|
| 1161 |
+
>>> output = m(input)
|
| 1162 |
+
"""
|
| 1163 |
+
|
| 1164 |
+
kernel_size: _size_1_t
|
| 1165 |
+
stride: _size_1_t
|
| 1166 |
+
|
| 1167 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1168 |
+
"""Runs the forward pass."""
|
| 1169 |
+
return F.lp_pool1d(
|
| 1170 |
+
input, float(self.norm_type), self.kernel_size, self.stride, self.ceil_mode
|
| 1171 |
+
)
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
class LPPool2d(_LPPoolNd):
|
| 1175 |
+
r"""Applies a 2D power-average pooling over an input signal composed of several input planes.
|
| 1176 |
+
|
| 1177 |
+
On each window, the function computed is:
|
| 1178 |
+
|
| 1179 |
+
.. math::
|
| 1180 |
+
f(X) = \sqrt[p]{\sum_{x \in X} x^{p}}
|
| 1181 |
+
|
| 1182 |
+
- At p = :math:`\infty`, one gets Max Pooling over absolute values
|
| 1183 |
+
- At p = 1, one gets Sum Pooling (which is proportional to average pooling)
|
| 1184 |
+
|
| 1185 |
+
The parameters :attr:`kernel_size`, :attr:`stride` can either be:
|
| 1186 |
+
|
| 1187 |
+
- a single ``int`` -- in which case the same value is used for the height and width dimension
|
| 1188 |
+
- a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
|
| 1189 |
+
and the second `int` for the width dimension
|
| 1190 |
+
|
| 1191 |
+
.. note:: If the sum to the power of `p` is zero, the gradient of this function is
|
| 1192 |
+
not defined. This implementation will set the gradient to zero in this case.
|
| 1193 |
+
|
| 1194 |
+
Args:
|
| 1195 |
+
kernel_size: the size of the window
|
| 1196 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 1197 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 1198 |
+
|
| 1199 |
+
Note:
|
| 1200 |
+
When :attr:`ceil_mode` is ``True``, sliding windows may go off-bounds if they start within the
|
| 1201 |
+
left padding or the input. Sliding windows that would start in the right padded region are ignored.
|
| 1202 |
+
|
| 1203 |
+
Shape:
|
| 1204 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 1205 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 1206 |
+
|
| 1207 |
+
.. math::
|
| 1208 |
+
H_{out} = \left\lfloor\frac{H_{in} - \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
|
| 1209 |
+
|
| 1210 |
+
.. math::
|
| 1211 |
+
W_{out} = \left\lfloor\frac{W_{in} - \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
|
| 1212 |
+
|
| 1213 |
+
Examples::
|
| 1214 |
+
|
| 1215 |
+
>>> # power-2 pool of square window of size=3, stride=2
|
| 1216 |
+
>>> m = nn.LPPool2d(2, 3, stride=2)
|
| 1217 |
+
>>> # pool of non-square window of power 1.2
|
| 1218 |
+
>>> m = nn.LPPool2d(1.2, (3, 2), stride=(2, 1))
|
| 1219 |
+
>>> input = torch.randn(20, 16, 50, 32)
|
| 1220 |
+
>>> output = m(input)
|
| 1221 |
+
|
| 1222 |
+
"""
|
| 1223 |
+
|
| 1224 |
+
kernel_size: _size_2_t
|
| 1225 |
+
stride: _size_2_t
|
| 1226 |
+
|
| 1227 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1228 |
+
"""Runs the forward pass."""
|
| 1229 |
+
return F.lp_pool2d(
|
| 1230 |
+
input, float(self.norm_type), self.kernel_size, self.stride, self.ceil_mode
|
| 1231 |
+
)
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
class LPPool3d(_LPPoolNd):
|
| 1235 |
+
r"""Applies a 3D power-average pooling over an input signal composed of several input planes.
|
| 1236 |
+
|
| 1237 |
+
On each window, the function computed is:
|
| 1238 |
+
|
| 1239 |
+
.. math::
|
| 1240 |
+
f(X) = \sqrt[p]{\sum_{x \in X} x^{p}}
|
| 1241 |
+
|
| 1242 |
+
- At p = :math:`\infty`, one gets Max Pooling over absolute values
|
| 1243 |
+
- At p = 1, one gets Sum Pooling (which is proportional to average pooling)
|
| 1244 |
+
|
| 1245 |
+
The parameters :attr:`kernel_size`, :attr:`stride` can either be:
|
| 1246 |
+
|
| 1247 |
+
- a single ``int`` -- in which case the same value is used for the height, width and depth dimension
|
| 1248 |
+
- a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
|
| 1249 |
+
the second `int` for the height dimension and the third `int` for the width dimension
|
| 1250 |
+
|
| 1251 |
+
.. note:: If the sum to the power of `p` is zero, the gradient of this function is
|
| 1252 |
+
not defined. This implementation will set the gradient to zero in this case.
|
| 1253 |
+
|
| 1254 |
+
Args:
|
| 1255 |
+
kernel_size: the size of the window
|
| 1256 |
+
stride: the stride of the window. Default value is :attr:`kernel_size`
|
| 1257 |
+
ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
|
| 1258 |
+
|
| 1259 |
+
Note:
|
| 1260 |
+
When :attr:`ceil_mode` is ``True``, sliding windows may go off-bounds if they start within the
|
| 1261 |
+
left padding or the input. Sliding windows that would start in the right padded region are ignored.
|
| 1262 |
+
|
| 1263 |
+
Shape:
|
| 1264 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 1265 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or
|
| 1266 |
+
:math:`(C, D_{out}, H_{out}, W_{out})`, where
|
| 1267 |
+
|
| 1268 |
+
.. math::
|
| 1269 |
+
D_{out} = \left\lfloor\frac{D_{in} - \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
|
| 1270 |
+
|
| 1271 |
+
.. math::
|
| 1272 |
+
H_{out} = \left\lfloor\frac{H_{in} - \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
|
| 1273 |
+
|
| 1274 |
+
.. math::
|
| 1275 |
+
W_{out} = \left\lfloor\frac{W_{in} - \text{kernel\_size}[2]}{\text{stride}[2]} + 1\right\rfloor
|
| 1276 |
+
|
| 1277 |
+
Examples::
|
| 1278 |
+
|
| 1279 |
+
>>> # power-2 pool of square window of size=3, stride=2
|
| 1280 |
+
>>> m = nn.LPPool3d(2, 3, stride=2)
|
| 1281 |
+
>>> # pool of non-square window of power 1.2
|
| 1282 |
+
>>> m = nn.LPPool3d(1.2, (3, 2, 2), stride=(2, 1, 2))
|
| 1283 |
+
>>> input = torch.randn(20, 16, 50, 44, 31)
|
| 1284 |
+
>>> output = m(input)
|
| 1285 |
+
|
| 1286 |
+
"""
|
| 1287 |
+
|
| 1288 |
+
kernel_size: _size_3_t
|
| 1289 |
+
stride: _size_3_t
|
| 1290 |
+
|
| 1291 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1292 |
+
"""Runs the forward pass."""
|
| 1293 |
+
return F.lp_pool3d(
|
| 1294 |
+
input, float(self.norm_type), self.kernel_size, self.stride, self.ceil_mode
|
| 1295 |
+
)
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
class _AdaptiveMaxPoolNd(Module):
|
| 1299 |
+
__constants__ = ["output_size", "return_indices"]
|
| 1300 |
+
return_indices: bool
|
| 1301 |
+
|
| 1302 |
+
def __init__(
|
| 1303 |
+
self, output_size: _size_any_opt_t, return_indices: bool = False
|
| 1304 |
+
) -> None:
|
| 1305 |
+
super().__init__()
|
| 1306 |
+
self.output_size = output_size
|
| 1307 |
+
self.return_indices = return_indices
|
| 1308 |
+
|
| 1309 |
+
def extra_repr(self) -> str:
|
| 1310 |
+
return f"output_size={self.output_size}"
|
| 1311 |
+
|
| 1312 |
+
|
| 1313 |
+
# FIXME (by @ssnl): Improve adaptive pooling docs: specify what the input and
|
| 1314 |
+
# output shapes are, and how the operation computes output.
|
| 1315 |
+
|
| 1316 |
+
|
| 1317 |
+
class AdaptiveMaxPool1d(_AdaptiveMaxPoolNd):
|
| 1318 |
+
r"""Applies a 1D adaptive max pooling over an input signal composed of several input planes.
|
| 1319 |
+
|
| 1320 |
+
The output size is :math:`L_{out}`, for any input size.
|
| 1321 |
+
The number of output features is equal to the number of input planes.
|
| 1322 |
+
|
| 1323 |
+
Args:
|
| 1324 |
+
output_size: the target output size :math:`L_{out}`.
|
| 1325 |
+
return_indices: if ``True``, will return the indices along with the outputs.
|
| 1326 |
+
Useful to pass to nn.MaxUnpool1d. Default: ``False``
|
| 1327 |
+
|
| 1328 |
+
Shape:
|
| 1329 |
+
- Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
|
| 1330 |
+
- Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
|
| 1331 |
+
:math:`L_{out}=\text{output\_size}`.
|
| 1332 |
+
|
| 1333 |
+
Examples:
|
| 1334 |
+
>>> # target output size of 5
|
| 1335 |
+
>>> m = nn.AdaptiveMaxPool1d(5)
|
| 1336 |
+
>>> input = torch.randn(1, 64, 8)
|
| 1337 |
+
>>> output = m(input)
|
| 1338 |
+
|
| 1339 |
+
"""
|
| 1340 |
+
|
| 1341 |
+
output_size: _size_1_t
|
| 1342 |
+
|
| 1343 |
+
def forward(self, input: Tensor):
|
| 1344 |
+
"""Runs the forward pass."""
|
| 1345 |
+
return F.adaptive_max_pool1d(input, self.output_size, self.return_indices)
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
class AdaptiveMaxPool2d(_AdaptiveMaxPoolNd):
|
| 1349 |
+
r"""Applies a 2D adaptive max pooling over an input signal composed of several input planes.
|
| 1350 |
+
|
| 1351 |
+
The output is of size :math:`H_{out} \times W_{out}`, for any input size.
|
| 1352 |
+
The number of output features is equal to the number of input planes.
|
| 1353 |
+
|
| 1354 |
+
Args:
|
| 1355 |
+
output_size: the target output size of the image of the form :math:`H_{out} \times W_{out}`.
|
| 1356 |
+
Can be a tuple :math:`(H_{out}, W_{out})` or a single :math:`H_{out}` for a
|
| 1357 |
+
square image :math:`H_{out} \times H_{out}`. :math:`H_{out}` and :math:`W_{out}`
|
| 1358 |
+
can be either a ``int``, or ``None`` which means the size will be the same as that
|
| 1359 |
+
of the input.
|
| 1360 |
+
return_indices: if ``True``, will return the indices along with the outputs.
|
| 1361 |
+
Useful to pass to nn.MaxUnpool2d. Default: ``False``
|
| 1362 |
+
|
| 1363 |
+
Shape:
|
| 1364 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 1365 |
+
- Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
|
| 1366 |
+
:math:`(H_{out}, W_{out})=\text{output\_size}`.
|
| 1367 |
+
|
| 1368 |
+
Examples:
|
| 1369 |
+
>>> # target output size of 5x7
|
| 1370 |
+
>>> m = nn.AdaptiveMaxPool2d((5, 7))
|
| 1371 |
+
>>> input = torch.randn(1, 64, 8, 9)
|
| 1372 |
+
>>> output = m(input)
|
| 1373 |
+
>>> # target output size of 7x7 (square)
|
| 1374 |
+
>>> m = nn.AdaptiveMaxPool2d(7)
|
| 1375 |
+
>>> input = torch.randn(1, 64, 10, 9)
|
| 1376 |
+
>>> output = m(input)
|
| 1377 |
+
>>> # target output size of 10x7
|
| 1378 |
+
>>> m = nn.AdaptiveMaxPool2d((None, 7))
|
| 1379 |
+
>>> input = torch.randn(1, 64, 10, 9)
|
| 1380 |
+
>>> output = m(input)
|
| 1381 |
+
|
| 1382 |
+
"""
|
| 1383 |
+
|
| 1384 |
+
output_size: _size_2_opt_t
|
| 1385 |
+
|
| 1386 |
+
def forward(self, input: Tensor):
|
| 1387 |
+
"""Runs the forward pass."""
|
| 1388 |
+
return F.adaptive_max_pool2d(input, self.output_size, self.return_indices)
|
| 1389 |
+
|
| 1390 |
+
|
| 1391 |
+
class AdaptiveMaxPool3d(_AdaptiveMaxPoolNd):
|
| 1392 |
+
r"""Applies a 3D adaptive max pooling over an input signal composed of several input planes.
|
| 1393 |
+
|
| 1394 |
+
The output is of size :math:`D_{out} \times H_{out} \times W_{out}`, for any input size.
|
| 1395 |
+
The number of output features is equal to the number of input planes.
|
| 1396 |
+
|
| 1397 |
+
Args:
|
| 1398 |
+
output_size: the target output size of the image of the form :math:`D_{out} \times H_{out} \times W_{out}`.
|
| 1399 |
+
Can be a tuple :math:`(D_{out}, H_{out}, W_{out})` or a single
|
| 1400 |
+
:math:`D_{out}` for a cube :math:`D_{out} \times D_{out} \times D_{out}`.
|
| 1401 |
+
:math:`D_{out}`, :math:`H_{out}` and :math:`W_{out}` can be either a
|
| 1402 |
+
``int``, or ``None`` which means the size will be the same as that of the input.
|
| 1403 |
+
|
| 1404 |
+
return_indices: if ``True``, will return the indices along with the outputs.
|
| 1405 |
+
Useful to pass to nn.MaxUnpool3d. Default: ``False``
|
| 1406 |
+
|
| 1407 |
+
Shape:
|
| 1408 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 1409 |
+
- Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`,
|
| 1410 |
+
where :math:`(D_{out}, H_{out}, W_{out})=\text{output\_size}`.
|
| 1411 |
+
|
| 1412 |
+
Examples:
|
| 1413 |
+
>>> # target output size of 5x7x9
|
| 1414 |
+
>>> m = nn.AdaptiveMaxPool3d((5, 7, 9))
|
| 1415 |
+
>>> input = torch.randn(1, 64, 8, 9, 10)
|
| 1416 |
+
>>> output = m(input)
|
| 1417 |
+
>>> # target output size of 7x7x7 (cube)
|
| 1418 |
+
>>> m = nn.AdaptiveMaxPool3d(7)
|
| 1419 |
+
>>> input = torch.randn(1, 64, 10, 9, 8)
|
| 1420 |
+
>>> output = m(input)
|
| 1421 |
+
>>> # target output size of 7x9x8
|
| 1422 |
+
>>> m = nn.AdaptiveMaxPool3d((7, None, None))
|
| 1423 |
+
>>> input = torch.randn(1, 64, 10, 9, 8)
|
| 1424 |
+
>>> output = m(input)
|
| 1425 |
+
|
| 1426 |
+
"""
|
| 1427 |
+
|
| 1428 |
+
output_size: _size_3_opt_t
|
| 1429 |
+
|
| 1430 |
+
def forward(self, input: Tensor):
|
| 1431 |
+
"""Runs the forward pass."""
|
| 1432 |
+
return F.adaptive_max_pool3d(input, self.output_size, self.return_indices)
|
| 1433 |
+
|
| 1434 |
+
|
| 1435 |
+
class _AdaptiveAvgPoolNd(Module):
|
| 1436 |
+
__constants__ = ["output_size"]
|
| 1437 |
+
|
| 1438 |
+
def __init__(self, output_size: _size_any_opt_t) -> None:
|
| 1439 |
+
super().__init__()
|
| 1440 |
+
self.output_size = output_size
|
| 1441 |
+
|
| 1442 |
+
def extra_repr(self) -> str:
|
| 1443 |
+
return f"output_size={self.output_size}"
|
| 1444 |
+
|
| 1445 |
+
|
| 1446 |
+
class AdaptiveAvgPool1d(_AdaptiveAvgPoolNd):
|
| 1447 |
+
r"""Applies a 1D adaptive average pooling over an input signal composed of several input planes.
|
| 1448 |
+
|
| 1449 |
+
The output size is :math:`L_{out}`, for any input size.
|
| 1450 |
+
The number of output features is equal to the number of input planes.
|
| 1451 |
+
|
| 1452 |
+
Args:
|
| 1453 |
+
output_size: the target output size :math:`L_{out}`.
|
| 1454 |
+
|
| 1455 |
+
Shape:
|
| 1456 |
+
- Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
|
| 1457 |
+
- Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
|
| 1458 |
+
:math:`L_{out}=\text{output\_size}`.
|
| 1459 |
+
|
| 1460 |
+
Examples:
|
| 1461 |
+
>>> # target output size of 5
|
| 1462 |
+
>>> m = nn.AdaptiveAvgPool1d(5)
|
| 1463 |
+
>>> input = torch.randn(1, 64, 8)
|
| 1464 |
+
>>> output = m(input)
|
| 1465 |
+
|
| 1466 |
+
"""
|
| 1467 |
+
|
| 1468 |
+
output_size: _size_1_t
|
| 1469 |
+
|
| 1470 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1471 |
+
"""
|
| 1472 |
+
Runs the forward pass.
|
| 1473 |
+
"""
|
| 1474 |
+
return F.adaptive_avg_pool1d(input, self.output_size)
|
| 1475 |
+
|
| 1476 |
+
|
| 1477 |
+
class AdaptiveAvgPool2d(_AdaptiveAvgPoolNd):
|
| 1478 |
+
r"""Applies a 2D adaptive average pooling over an input signal composed of several input planes.
|
| 1479 |
+
|
| 1480 |
+
The output is of size H x W, for any input size.
|
| 1481 |
+
The number of output features is equal to the number of input planes.
|
| 1482 |
+
|
| 1483 |
+
Args:
|
| 1484 |
+
output_size: the target output size of the image of the form H x W.
|
| 1485 |
+
Can be a tuple (H, W) or a single H for a square image H x H.
|
| 1486 |
+
H and W can be either a ``int``, or ``None`` which means the size will
|
| 1487 |
+
be the same as that of the input.
|
| 1488 |
+
|
| 1489 |
+
Shape:
|
| 1490 |
+
- Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
|
| 1491 |
+
- Output: :math:`(N, C, S_{0}, S_{1})` or :math:`(C, S_{0}, S_{1})`, where
|
| 1492 |
+
:math:`S=\text{output\_size}`.
|
| 1493 |
+
|
| 1494 |
+
Examples:
|
| 1495 |
+
>>> # target output size of 5x7
|
| 1496 |
+
>>> m = nn.AdaptiveAvgPool2d((5, 7))
|
| 1497 |
+
>>> input = torch.randn(1, 64, 8, 9)
|
| 1498 |
+
>>> output = m(input)
|
| 1499 |
+
>>> # target output size of 7x7 (square)
|
| 1500 |
+
>>> m = nn.AdaptiveAvgPool2d(7)
|
| 1501 |
+
>>> input = torch.randn(1, 64, 10, 9)
|
| 1502 |
+
>>> output = m(input)
|
| 1503 |
+
>>> # target output size of 10x7
|
| 1504 |
+
>>> m = nn.AdaptiveAvgPool2d((None, 7))
|
| 1505 |
+
>>> input = torch.randn(1, 64, 10, 9)
|
| 1506 |
+
>>> output = m(input)
|
| 1507 |
+
|
| 1508 |
+
"""
|
| 1509 |
+
|
| 1510 |
+
output_size: _size_2_opt_t
|
| 1511 |
+
|
| 1512 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1513 |
+
"""Runs the forward pass."""
|
| 1514 |
+
return F.adaptive_avg_pool2d(input, self.output_size)
|
| 1515 |
+
|
| 1516 |
+
|
| 1517 |
+
class AdaptiveAvgPool3d(_AdaptiveAvgPoolNd):
|
| 1518 |
+
r"""Applies a 3D adaptive average pooling over an input signal composed of several input planes.
|
| 1519 |
+
|
| 1520 |
+
The output is of size D x H x W, for any input size.
|
| 1521 |
+
The number of output features is equal to the number of input planes.
|
| 1522 |
+
|
| 1523 |
+
Args:
|
| 1524 |
+
output_size: the target output size of the form D x H x W.
|
| 1525 |
+
Can be a tuple (D, H, W) or a single number D for a cube D x D x D.
|
| 1526 |
+
D, H and W can be either a ``int``, or ``None`` which means the size will
|
| 1527 |
+
be the same as that of the input.
|
| 1528 |
+
|
| 1529 |
+
Shape:
|
| 1530 |
+
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
|
| 1531 |
+
- Output: :math:`(N, C, S_{0}, S_{1}, S_{2})` or :math:`(C, S_{0}, S_{1}, S_{2})`,
|
| 1532 |
+
where :math:`S=\text{output\_size}`.
|
| 1533 |
+
|
| 1534 |
+
Examples:
|
| 1535 |
+
>>> # target output size of 5x7x9
|
| 1536 |
+
>>> m = nn.AdaptiveAvgPool3d((5, 7, 9))
|
| 1537 |
+
>>> input = torch.randn(1, 64, 8, 9, 10)
|
| 1538 |
+
>>> output = m(input)
|
| 1539 |
+
>>> # target output size of 7x7x7 (cube)
|
| 1540 |
+
>>> m = nn.AdaptiveAvgPool3d(7)
|
| 1541 |
+
>>> input = torch.randn(1, 64, 10, 9, 8)
|
| 1542 |
+
>>> output = m(input)
|
| 1543 |
+
>>> # target output size of 7x9x8
|
| 1544 |
+
>>> m = nn.AdaptiveAvgPool3d((7, None, None))
|
| 1545 |
+
>>> input = torch.randn(1, 64, 10, 9, 8)
|
| 1546 |
+
>>> output = m(input)
|
| 1547 |
+
|
| 1548 |
+
"""
|
| 1549 |
+
|
| 1550 |
+
output_size: _size_3_opt_t
|
| 1551 |
+
|
| 1552 |
+
def forward(self, input: Tensor) -> Tensor:
|
| 1553 |
+
"""Runs the forward pass."""
|
| 1554 |
+
return F.adaptive_avg_pool3d(input, self.output_size)
|