jasonfan commited on
Commit
b04c30b
·
verified ·
1 Parent(s): 52c956c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/qat/modules/embedding_ops.py +14 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/qat/modules/linear.py +11 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/__init__.py +1 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/__init__.py +9 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/activation.py +11 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/rnn.py +11 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/__init__.py +39 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/__init__.py +1 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/__init__.py +39 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/conv.py +21 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/linear.py +12 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/rnn.py +19 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/sparse.py +12 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/utils.py +18 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/__init__.py +1 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/__init__.py +43 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/conv.py +28 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/linear.py +11 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/rnn.py +34 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/functional.py +10 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/__init__.py +97 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/activation.py +20 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/batchnorm.py +11 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/conv.py +29 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/dropout.py +14 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/embedding_ops.py +18 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/functional_modules.py +18 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/linear.py +14 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/normalization.py +26 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/rnn.py +11 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/utils.py +17 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/__init__.py +48 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_deprecation_utils.py +53 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/__init__.py +10 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/conv_expanded_weights.py +82 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/conv_utils.py +354 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/embedding_expanded_weights.py +88 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/expanded_weights_impl.py +186 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/expanded_weights_utils.py +188 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/group_norm_expanded_weights.py +107 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/instance_norm_expanded_weights.py +101 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/layer_norm_expanded_weights.py +88 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/linear_expanded_weights.py +63 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_named_member_accessor.py +373 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_per_sample_grad.py +126 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/clip_grad.py +299 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/convert_parameters.py +90 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/fusion.py +190 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/init.py +55 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/memory_format.py +174 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/qat/modules/embedding_ops.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""QAT Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/qat`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/qat/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.qat.modules.embedding_ops import Embedding, EmbeddingBag
12
+
13
+
14
+ __all__ = ["Embedding", "EmbeddingBag"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/qat/modules/linear.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""QAT Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/qat`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/qat/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.qat.modules.linear import Linear
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from torch.nn.quantizable.modules import * # noqa: F403
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from torch.ao.nn.quantizable.modules.activation import MultiheadAttention
2
+ from torch.ao.nn.quantizable.modules.rnn import LSTM, LSTMCell
3
+
4
+
5
+ __all__ = [
6
+ "LSTM",
7
+ "LSTMCell",
8
+ "MultiheadAttention",
9
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/activation.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantizable Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantizable`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantizable/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantizable.modules.activation import MultiheadAttention
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantizable/modules/rnn.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantizable Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantizable`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantizable/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantizable.modules.rnn import LSTM, LSTMCell
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch.nn.quantized import dynamic, functional, modules # noqa: F403
2
+ from torch.nn.quantized.modules import * # noqa: F403
3
+ from torch.nn.quantized.modules import MaxPool2d
4
+
5
+
6
+ __all__ = [
7
+ "BatchNorm2d",
8
+ "BatchNorm3d",
9
+ "Conv1d",
10
+ "Conv2d",
11
+ "Conv3d",
12
+ "ConvTranspose1d",
13
+ "ConvTranspose2d",
14
+ "ConvTranspose3d",
15
+ "DeQuantize",
16
+ "Dropout",
17
+ "ELU",
18
+ "Embedding",
19
+ "EmbeddingBag",
20
+ "GroupNorm",
21
+ "Hardswish",
22
+ "InstanceNorm1d",
23
+ "InstanceNorm2d",
24
+ "InstanceNorm3d",
25
+ "LayerNorm",
26
+ "LeakyReLU",
27
+ "Linear",
28
+ "LSTM",
29
+ "MultiheadAttention",
30
+ "PReLU",
31
+ "Quantize",
32
+ "ReLU6",
33
+ "Sigmoid",
34
+ "Softmax",
35
+ # Wrapper modules
36
+ "FloatFunctional",
37
+ "FXFloatFunctional",
38
+ "QFunctional",
39
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from torch.nn.quantized._reference.modules import * # noqa: F403
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.conv import (
13
+ Conv1d,
14
+ Conv2d,
15
+ Conv3d,
16
+ ConvTranspose1d,
17
+ ConvTranspose2d,
18
+ ConvTranspose3d,
19
+ )
20
+ from torch.ao.nn.quantized.reference.modules.linear import Linear
21
+ from torch.ao.nn.quantized.reference.modules.rnn import GRUCell, LSTM, LSTMCell, RNNCell
22
+ from torch.ao.nn.quantized.reference.modules.sparse import Embedding, EmbeddingBag
23
+
24
+
25
+ __all__ = [
26
+ "Linear",
27
+ "Conv1d",
28
+ "Conv2d",
29
+ "Conv3d",
30
+ "ConvTranspose1d",
31
+ "ConvTranspose2d",
32
+ "ConvTranspose3d",
33
+ "RNNCell",
34
+ "LSTMCell",
35
+ "GRUCell",
36
+ "LSTM",
37
+ "Embedding",
38
+ "EmbeddingBag",
39
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/conv.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.conv import (
13
+ _ConvNd,
14
+ _ConvTransposeNd,
15
+ Conv1d,
16
+ Conv2d,
17
+ Conv3d,
18
+ ConvTranspose1d,
19
+ ConvTranspose2d,
20
+ ConvTranspose3d,
21
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/linear.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.linear import Linear
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/rnn.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.rnn import (
13
+ GRUCell,
14
+ LSTM,
15
+ LSTMCell,
16
+ RNNBase,
17
+ RNNCell,
18
+ RNNCellBase,
19
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/sparse.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.sparse import Embedding, EmbeddingBag
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/_reference/modules/utils.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Reference Modules.
3
+
4
+ This module is in the process of migration to
5
+ `torch/ao/nn/quantized/reference`, and is kept here for
6
+ compatibility while the migration process is ongoing.
7
+ If you are adding a new entry/functionality, please, add it to the
8
+ appropriate file under the `torch/ao/nn/quantized/reference`,
9
+ while adding an import statement here.
10
+ """
11
+
12
+ from torch.ao.nn.quantized.reference.modules.utils import (
13
+ _get_weight_qparam_keys,
14
+ _quantize_and_dequantize_weight,
15
+ _quantize_weight,
16
+ _save_weight_qparams,
17
+ ReferenceQuantizedModule,
18
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from torch.ao.nn.quantized.dynamic import * # noqa: F403
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Dynamic Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
5
+ and is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/dynamic`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.dynamic.modules import conv, linear, rnn
12
+ from torch.ao.nn.quantized.dynamic.modules.conv import (
13
+ Conv1d,
14
+ Conv2d,
15
+ Conv3d,
16
+ ConvTranspose1d,
17
+ ConvTranspose2d,
18
+ ConvTranspose3d,
19
+ )
20
+ from torch.ao.nn.quantized.dynamic.modules.linear import Linear
21
+ from torch.ao.nn.quantized.dynamic.modules.rnn import (
22
+ GRU,
23
+ GRUCell,
24
+ LSTM,
25
+ LSTMCell,
26
+ RNNCell,
27
+ )
28
+
29
+
30
+ __all__ = [
31
+ "Linear",
32
+ "LSTM",
33
+ "GRU",
34
+ "LSTMCell",
35
+ "RNNCell",
36
+ "GRUCell",
37
+ "Conv1d",
38
+ "Conv2d",
39
+ "Conv3d",
40
+ "ConvTranspose1d",
41
+ "ConvTranspose2d",
42
+ "ConvTranspose3d",
43
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/conv.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Dynamic Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
5
+ and is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/dynamic/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.dynamic.modules.conv import (
12
+ Conv1d,
13
+ Conv2d,
14
+ Conv3d,
15
+ ConvTranspose1d,
16
+ ConvTranspose2d,
17
+ ConvTranspose3d,
18
+ )
19
+
20
+
21
+ __all__ = [
22
+ "Conv1d",
23
+ "Conv2d",
24
+ "Conv3d",
25
+ "ConvTranspose1d",
26
+ "ConvTranspose2d",
27
+ "ConvTranspose3d",
28
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/linear.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Dynamic Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
5
+ and is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/dynamic/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.dynamic.modules.linear import Linear
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/dynamic/modules/rnn.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Dynamic Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized/dynamic`,
5
+ and is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/dynamic/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.dynamic.modules.rnn import (
12
+ GRU,
13
+ GRUCell,
14
+ LSTM,
15
+ LSTMCell,
16
+ pack_weight_bias,
17
+ PackedParameter,
18
+ RNNBase,
19
+ RNNCell,
20
+ RNNCellBase,
21
+ )
22
+
23
+
24
+ __all__ = [
25
+ "pack_weight_bias",
26
+ "PackedParameter",
27
+ "RNNBase",
28
+ "LSTM",
29
+ "GRU",
30
+ "RNNCellBase",
31
+ "RNNCell",
32
+ "LSTMCell",
33
+ "GRUCell",
34
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/functional.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""nn.quantized.functional.
2
+
3
+ Quantized equivalents of the `nn.functional`.
4
+
5
+ Note::
6
+ This location is in the process of being deprecated.
7
+ Please, use the `torch.ao.nn.quantized.functional` instead.
8
+ """
9
+
10
+ from torch.ao.nn.quantized.functional import * # noqa: F401,F403
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/__init__.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Quantized Modules.
2
+
3
+ Note::
4
+ The `torch.nn.quantized` namespace is in the process of being deprecated.
5
+ Please, use `torch.ao.nn.quantized` instead.
6
+ """
7
+
8
+ # The following imports are needed in case the user decides
9
+ # to import the files directly,
10
+ # s.a. `from torch.nn.quantized.modules.conv import ...`.
11
+ # No need to add them to the `__all__`.
12
+ from torch.ao.nn.quantized.modules import (
13
+ activation,
14
+ batchnorm,
15
+ conv,
16
+ DeQuantize,
17
+ dropout,
18
+ embedding_ops,
19
+ functional_modules,
20
+ linear,
21
+ MaxPool2d,
22
+ normalization,
23
+ Quantize,
24
+ rnn,
25
+ utils,
26
+ )
27
+ from torch.ao.nn.quantized.modules.activation import (
28
+ ELU,
29
+ Hardswish,
30
+ LeakyReLU,
31
+ MultiheadAttention,
32
+ PReLU,
33
+ ReLU6,
34
+ Sigmoid,
35
+ Softmax,
36
+ )
37
+ from torch.ao.nn.quantized.modules.batchnorm import BatchNorm2d, BatchNorm3d
38
+ from torch.ao.nn.quantized.modules.conv import (
39
+ Conv1d,
40
+ Conv2d,
41
+ Conv3d,
42
+ ConvTranspose1d,
43
+ ConvTranspose2d,
44
+ ConvTranspose3d,
45
+ )
46
+ from torch.ao.nn.quantized.modules.dropout import Dropout
47
+ from torch.ao.nn.quantized.modules.embedding_ops import Embedding, EmbeddingBag
48
+ from torch.ao.nn.quantized.modules.functional_modules import (
49
+ FloatFunctional,
50
+ FXFloatFunctional,
51
+ QFunctional,
52
+ )
53
+ from torch.ao.nn.quantized.modules.linear import Linear
54
+ from torch.ao.nn.quantized.modules.normalization import (
55
+ GroupNorm,
56
+ InstanceNorm1d,
57
+ InstanceNorm2d,
58
+ InstanceNorm3d,
59
+ LayerNorm,
60
+ )
61
+ from torch.ao.nn.quantized.modules.rnn import LSTM
62
+
63
+
64
+ __all__ = [
65
+ "BatchNorm2d",
66
+ "BatchNorm3d",
67
+ "Conv1d",
68
+ "Conv2d",
69
+ "Conv3d",
70
+ "ConvTranspose1d",
71
+ "ConvTranspose2d",
72
+ "ConvTranspose3d",
73
+ "DeQuantize",
74
+ "ELU",
75
+ "Embedding",
76
+ "EmbeddingBag",
77
+ "GroupNorm",
78
+ "Hardswish",
79
+ "InstanceNorm1d",
80
+ "InstanceNorm2d",
81
+ "InstanceNorm3d",
82
+ "LayerNorm",
83
+ "LeakyReLU",
84
+ "Linear",
85
+ "LSTM",
86
+ "MultiheadAttention",
87
+ "Quantize",
88
+ "ReLU6",
89
+ "Sigmoid",
90
+ "Softmax",
91
+ "Dropout",
92
+ "PReLU",
93
+ # Wrapper modules
94
+ "FloatFunctional",
95
+ "FXFloatFunctional",
96
+ "QFunctional",
97
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/activation.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.activation import (
12
+ ELU,
13
+ Hardswish,
14
+ LeakyReLU,
15
+ MultiheadAttention,
16
+ PReLU,
17
+ ReLU6,
18
+ Sigmoid,
19
+ Softmax,
20
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/batchnorm.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.batchnorm import BatchNorm2d, BatchNorm3d
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/conv.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.conv import (
12
+ _reverse_repeat_padding,
13
+ Conv1d,
14
+ Conv2d,
15
+ Conv3d,
16
+ ConvTranspose1d,
17
+ ConvTranspose2d,
18
+ ConvTranspose3d,
19
+ )
20
+
21
+
22
+ __all__ = [
23
+ "Conv1d",
24
+ "Conv2d",
25
+ "Conv3d",
26
+ "ConvTranspose1d",
27
+ "ConvTranspose2d",
28
+ "ConvTranspose3d",
29
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/dropout.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.dropout import Dropout
12
+
13
+
14
+ __all__ = ["Dropout"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/embedding_ops.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.embedding_ops import (
12
+ Embedding,
13
+ EmbeddingBag,
14
+ EmbeddingPackedParams,
15
+ )
16
+
17
+
18
+ __all__ = ["EmbeddingPackedParams", "Embedding", "EmbeddingBag"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/functional_modules.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.functional_modules import (
12
+ FloatFunctional,
13
+ FXFloatFunctional,
14
+ QFunctional,
15
+ )
16
+
17
+
18
+ __all__ = ["FloatFunctional", "FXFloatFunctional", "QFunctional"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/linear.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.linear import Linear, LinearPackedParams
12
+
13
+
14
+ __all__ = ["LinearPackedParams", "Linear"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/normalization.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.normalization import (
12
+ GroupNorm,
13
+ InstanceNorm1d,
14
+ InstanceNorm2d,
15
+ InstanceNorm3d,
16
+ LayerNorm,
17
+ )
18
+
19
+
20
+ __all__ = [
21
+ "LayerNorm",
22
+ "GroupNorm",
23
+ "InstanceNorm1d",
24
+ "InstanceNorm2d",
25
+ "InstanceNorm3d",
26
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/rnn.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.rnn import LSTM
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/quantized/modules/utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa: F401
2
+ r"""Quantized Modules.
3
+
4
+ This file is in the process of migration to `torch/ao/nn/quantized`, and
5
+ is kept here for compatibility while the migration process is ongoing.
6
+ If you are adding a new entry/functionality, please, add it to the
7
+ appropriate file under the `torch/ao/nn/quantized/modules`,
8
+ while adding an import statement here.
9
+ """
10
+
11
+ from torch.ao.nn.quantized.modules.utils import (
12
+ _hide_packed_params_repr,
13
+ _ntuple_from_first,
14
+ _pair_from_first,
15
+ _quantize_weight,
16
+ WeightedQuantizedModule,
17
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/__init__.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import parametrizations, parametrize, rnn, stateless
2
+ from .clip_grad import ( # pyrefly: ignore # deprecated; pyrefly: ignore [deprecated]
3
+ _clip_grads_with_norm_ as clip_grads_with_norm_,
4
+ _get_total_norm as get_total_norm,
5
+ clip_grad_norm,
6
+ clip_grad_norm_,
7
+ clip_grad_value_,
8
+ )
9
+ from .convert_parameters import parameters_to_vector, vector_to_parameters
10
+ from .fusion import (
11
+ fuse_conv_bn_eval,
12
+ fuse_conv_bn_weights,
13
+ fuse_linear_bn_eval,
14
+ fuse_linear_bn_weights,
15
+ )
16
+ from .init import skip_init
17
+ from .memory_format import (
18
+ convert_conv2d_weight_memory_format,
19
+ convert_conv3d_weight_memory_format,
20
+ )
21
+ from .spectral_norm import remove_spectral_norm, spectral_norm
22
+ from .weight_norm import remove_weight_norm, weight_norm
23
+
24
+
25
+ __all__ = [
26
+ "clip_grad_norm",
27
+ "clip_grad_norm_",
28
+ "clip_grads_with_norm_",
29
+ "clip_grad_value_",
30
+ "convert_conv2d_weight_memory_format",
31
+ "convert_conv3d_weight_memory_format",
32
+ "fuse_conv_bn_eval",
33
+ "fuse_conv_bn_weights",
34
+ "fuse_linear_bn_eval",
35
+ "fuse_linear_bn_weights",
36
+ "get_total_norm",
37
+ "parameters_to_vector",
38
+ "parametrizations",
39
+ "parametrize",
40
+ "remove_spectral_norm",
41
+ "remove_weight_norm",
42
+ "rnn",
43
+ "skip_init",
44
+ "spectral_norm",
45
+ "stateless",
46
+ "vector_to_parameters",
47
+ "weight_norm",
48
+ ]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_deprecation_utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import warnings
3
+ from collections.abc import Callable
4
+
5
+
6
+ _MESSAGE_TEMPLATE = (
7
+ r"Usage of '{old_location}' is deprecated; please use '{new_location}' instead."
8
+ )
9
+
10
+
11
+ def lazy_deprecated_import(
12
+ all: list[str],
13
+ old_module: str,
14
+ new_module: str,
15
+ ) -> Callable:
16
+ r"""Import utility to lazily import deprecated packages / modules / functional.
17
+
18
+ The old_module and new_module are also used in the deprecation warning defined
19
+ by the `_MESSAGE_TEMPLATE`.
20
+
21
+ Args:
22
+ all: The list of the functions that are imported. Generally, the module's
23
+ __all__ list of the module.
24
+ old_module: Old module location
25
+ new_module: New module location / Migrated location
26
+
27
+ Returns:
28
+ Callable to assign to the `__getattr__`
29
+
30
+ Usage:
31
+
32
+ # In the `torch/nn/quantized/functional.py`
33
+ from torch.nn.utils._deprecation_utils import lazy_deprecated_import
34
+ _MIGRATED_TO = "torch.ao.nn.quantized.functional"
35
+ __getattr__ = lazy_deprecated_import(
36
+ all=__all__,
37
+ old_module=__name__,
38
+ new_module=_MIGRATED_TO)
39
+ """
40
+ warning_message = _MESSAGE_TEMPLATE.format(
41
+ old_location=old_module, new_location=new_module
42
+ )
43
+
44
+ def getattr_dunder(name: str) -> None:
45
+ if name in all:
46
+ # We are using the "RuntimeWarning" to make sure it is not
47
+ # ignored by default.
48
+ warnings.warn(warning_message, RuntimeWarning, stacklevel=2)
49
+ package = importlib.import_module(new_module)
50
+ return getattr(package, name)
51
+ raise AttributeError(f"Module {new_module!r} has no attribute {name!r}.")
52
+
53
+ return getattr_dunder
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from .conv_expanded_weights import ConvPerSampleGrad
2
+ from .embedding_expanded_weights import EmbeddingPerSampleGrad
3
+ from .expanded_weights_impl import ExpandedWeight
4
+ from .group_norm_expanded_weights import GroupNormPerSampleGrad
5
+ from .instance_norm_expanded_weights import InstanceNormPerSampleGrad
6
+ from .layer_norm_expanded_weights import LayerNormPerSampleGrad
7
+ from .linear_expanded_weights import LinearPerSampleGrad
8
+
9
+
10
+ __all__ = ["ExpandedWeight"]
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/conv_expanded_weights.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Any, TypeVar
3
+ from typing_extensions import ParamSpec
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+
9
+ _P = ParamSpec("_P")
10
+ _R = TypeVar("_R")
11
+
12
+ from .conv_utils import (
13
+ conv_args_and_kwargs,
14
+ conv_backward,
15
+ conv_input_for_string_padding,
16
+ conv_picker,
17
+ )
18
+ from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
19
+ from .expanded_weights_utils import forward_helper
20
+
21
+
22
+ @implements_per_sample_grads(F.conv1d)
23
+ @implements_per_sample_grads(F.conv2d)
24
+ @implements_per_sample_grads(F.conv3d)
25
+ class ConvPerSampleGrad(torch.autograd.Function):
26
+ @staticmethod
27
+ # pyrefly: ignore [bad-override]
28
+ def forward(
29
+ ctx: Any,
30
+ kwarg_names: list[str],
31
+ conv_fn: Callable[_P, _R],
32
+ *expanded_args_and_kwargs: Any,
33
+ ) -> torch.Tensor:
34
+ expanded_args, expanded_kwargs = conv_args_and_kwargs(
35
+ kwarg_names, expanded_args_and_kwargs
36
+ )
37
+ orig_input = expanded_args[0]
38
+ was_same_padding = expanded_kwargs["padding"] == "same"
39
+
40
+ if isinstance(expanded_kwargs["padding"], str):
41
+ # if padding is a string, we'll do the necessary padding (slowly) using F.pad
42
+ kernel_size = expanded_args[1].shape[2:]
43
+ padding, dilation = expanded_kwargs["padding"], expanded_kwargs["dilation"]
44
+ input = conv_input_for_string_padding(
45
+ conv_fn, padding, expanded_args[0], dilation, kernel_size
46
+ )
47
+ expanded_args = (input, expanded_args[1])
48
+ # since we've already done the padding, don't need any more
49
+ expanded_kwargs["padding"] = 0
50
+
51
+ output = forward_helper(conv_fn, expanded_args, expanded_kwargs)
52
+ input, weight = expanded_args
53
+ batched_dim_size = conv_picker(conv_fn, 3, 4, 5)
54
+ if input.dim() != batched_dim_size:
55
+ raise RuntimeError(
56
+ f"Expanded Weights only support convolution with batched input, got {conv_fn} with an"
57
+ f"unbatched input of dim {input.dim()}, expected input of dim {batched_dim_size}"
58
+ )
59
+
60
+ # pyrefly: ignore [invalid-type-var]
61
+ ctx.conv_fn = conv_fn
62
+
63
+ ctx.batch_size = orig_input.shape[0]
64
+ ctx.input_required_grad = orig_input.requires_grad
65
+ ctx.orig_input_shape = orig_input.shape
66
+ ctx.was_same_padding = was_same_padding
67
+ ctx.stride, ctx.padding = expanded_kwargs["stride"], expanded_kwargs["padding"]
68
+ ctx.dilation, ctx.groups = (
69
+ expanded_kwargs["dilation"],
70
+ expanded_kwargs["groups"],
71
+ )
72
+
73
+ if isinstance(weight, ExpandedWeight):
74
+ ctx.input = input
75
+ ctx.weight = weight
76
+ ctx.bias = expanded_kwargs["bias"]
77
+
78
+ return output
79
+
80
+ @staticmethod
81
+ def backward(ctx: Any, *grad_outputs: Any) -> Any:
82
+ return conv_backward(ctx.conv_fn, ctx, grad_outputs[0])
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/conv_utils.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from .expanded_weights_utils import (
7
+ set_grad_sample_if_exists,
8
+ unpack_expanded_weight_or_tensor,
9
+ )
10
+
11
+
12
+ THRESHOLD = 32
13
+
14
+
15
+ def conv_picker(func, conv1dOpt, conv2dOpt, conv3dOpt):
16
+ if func is F.conv1d:
17
+ return conv1dOpt
18
+ if func is F.conv2d:
19
+ return conv2dOpt
20
+ else:
21
+ assert func is F.conv3d
22
+ return conv3dOpt
23
+
24
+
25
+ def conv_args_and_kwargs(kwarg_names, expanded_args_and_kwargs):
26
+ args = expanded_args_and_kwargs[: len(expanded_args_and_kwargs) - len(kwarg_names)]
27
+ kwargs = expanded_args_and_kwargs[
28
+ len(expanded_args_and_kwargs) - len(kwarg_names) :
29
+ ]
30
+ kwargs = dict(zip(kwarg_names, kwargs, strict=True))
31
+
32
+ return conv_normalizer(*args, **kwargs)
33
+
34
+
35
+ def conv_normalizer(
36
+ input,
37
+ weight,
38
+ bias=None,
39
+ stride=1,
40
+ padding=0,
41
+ dilation=1,
42
+ groups=1,
43
+ ):
44
+ return (input, weight), {
45
+ "bias": bias,
46
+ "stride": stride,
47
+ "padding": padding,
48
+ "dilation": dilation,
49
+ "groups": groups,
50
+ }
51
+
52
+
53
+ def conv_input_for_string_padding(func, padding_style, input, dilation, kernel_size):
54
+ if padding_style == "valid":
55
+ return input
56
+ else:
57
+ padding = int_padding_for_string_padding(
58
+ func, padding_style, dilation, kernel_size
59
+ )
60
+ return F.pad(input, padding)
61
+
62
+
63
+ def int_padding_for_string_padding(func, padding_style, dilation, kernel_size):
64
+ def get_dilation(i):
65
+ return dilation[i] if isinstance(dilation, tuple) else dilation
66
+
67
+ if padding_style == "same":
68
+ padding: list[int] = []
69
+ # F.pad needs the padding in reverse order from what conv expects
70
+ for i in range(conv_picker(func, 0, 1, 2), -1, -1):
71
+ padding += conv_padding_for_same(get_dilation(i), kernel_size[i])
72
+ return padding
73
+ elif padding_style == "valid":
74
+ return conv_picker(func, 2, 4, 6) * (0,)
75
+ else:
76
+ raise RuntimeError(
77
+ f"got padding type of {padding_style}, only accept 'same' or 'valid'"
78
+ )
79
+
80
+
81
+ def conv_padding_for_same(dilation, kernel_size):
82
+ total_pad = dilation * (kernel_size - 1)
83
+ left_pad = total_pad // 2
84
+ right_pad = total_pad - left_pad
85
+ return left_pad, right_pad
86
+
87
+
88
+ def conv_backward(func, ctx, grad_output):
89
+ def weight_grad_sample(weight):
90
+ if batch_size < THRESHOLD and groups == 1:
91
+ return conv_group_weight_grad_sample(
92
+ ctx.input,
93
+ grad_output,
94
+ weight_shape,
95
+ stride,
96
+ padding,
97
+ dilation,
98
+ batch_size,
99
+ func,
100
+ )
101
+ else:
102
+ return conv_unfold_weight_grad_sample(
103
+ ctx.input,
104
+ grad_output,
105
+ weight_shape,
106
+ kernel_size,
107
+ stride,
108
+ padding,
109
+ dilation,
110
+ groups,
111
+ func,
112
+ )
113
+
114
+ def expand(param):
115
+ if isinstance(param, int):
116
+ return conv_picker(func, (param,), (param, param), (param, param, param))
117
+ else:
118
+ return param
119
+
120
+ def calc_total_padding(func, was_same, padding, dilation, kernel_size):
121
+ if was_same:
122
+ all_padding = int_padding_for_string_padding(
123
+ func, "same", dilation, kernel_size
124
+ )
125
+ # F.pad needs the padding in reverse order from what conv expects
126
+ total_padding = tuple(
127
+ all_padding[i] + all_padding[i - 1]
128
+ for i in range(len(all_padding) - 1, -1, -2)
129
+ )
130
+ return total_padding
131
+ else:
132
+ return tuple(2 * pad for pad in padding)
133
+
134
+ weight_shape = ctx.weight.shape
135
+ stride, padding, dilation, groups = (
136
+ expand(ctx.stride),
137
+ expand(ctx.padding),
138
+ expand(ctx.dilation),
139
+ ctx.groups,
140
+ )
141
+
142
+ kernel_size = [weight_shape[i] for i in range(2, conv_picker(func, 3, 4, 5))]
143
+
144
+ batch_size = ctx.batch_size
145
+ results: list[torch.Tensor | None] = []
146
+ results.append(None) # for kwarg names
147
+ results.append(None) # for op reference
148
+
149
+ # "same" padding may give uneven padding on either side so we need to separate the "padding" attr and total padding
150
+ total_padding = calc_total_padding(
151
+ func, ctx.was_same_padding, padding, dilation, kernel_size
152
+ )
153
+
154
+ if ctx.input_required_grad:
155
+ output_padding = []
156
+ input_dims = conv_picker(func, 1, 2, 3)
157
+ for i in range(input_dims):
158
+ input_dim = ctx.orig_input_shape[2 + i]
159
+ output_padding.append(
160
+ (
161
+ total_padding[i]
162
+ + input_dim
163
+ - (kernel_size[i] * dilation[i] - dilation[i] + 1)
164
+ )
165
+ % stride[i]
166
+ )
167
+ weight_ = unpack_expanded_weight_or_tensor(ctx.weight)
168
+ transpose_func = conv_picker(
169
+ func, F.conv_transpose1d, F.conv_transpose2d, F.conv_transpose3d
170
+ )
171
+ out = transpose_func(
172
+ grad_output,
173
+ weight_,
174
+ None,
175
+ stride,
176
+ padding,
177
+ tuple(output_padding),
178
+ groups,
179
+ dilation,
180
+ )
181
+
182
+ if ctx.was_same_padding:
183
+ for i in range(len(total_padding)):
184
+ out = torch.narrow(
185
+ out, 2 + i, total_padding[i] // 2, ctx.orig_input_shape[2 + i]
186
+ )
187
+
188
+ results.append(out)
189
+ else:
190
+ results.append(None)
191
+ # weight and bias don't compute batched gradients; no other arguments are differentiable
192
+ results = results + [None] * 6
193
+
194
+ # set grad_sample field for weight and bias with per sample gradients
195
+ set_grad_sample_if_exists(ctx.weight, weight_grad_sample)
196
+ set_grad_sample_if_exists(
197
+ ctx.bias, lambda _: grad_output.reshape(*grad_output.shape[:2], -1).sum(dim=2)
198
+ )
199
+ return tuple(results)
200
+
201
+
202
+ def conv_unfold_weight_grad_sample(
203
+ input,
204
+ grad_output,
205
+ weight_shape,
206
+ kernel_size,
207
+ stride,
208
+ padding,
209
+ dilation,
210
+ groups,
211
+ func,
212
+ ):
213
+ import numpy as np
214
+
215
+ n = input.shape[0]
216
+ in_channels = input.shape[1]
217
+
218
+ unfold_func = conv_picker(
219
+ func,
220
+ lambda: F.unfold(
221
+ input.unsqueeze(-2),
222
+ kernel_size=(1, kernel_size[0]),
223
+ dilation=(1, dilation[0]),
224
+ padding=(0, padding[0]),
225
+ stride=(1, stride[0]),
226
+ ),
227
+ lambda: F.unfold(
228
+ input, kernel_size, dilation=dilation, padding=padding, stride=stride
229
+ ),
230
+ lambda: unfold3d(input, kernel_size, padding, stride, dilation),
231
+ )
232
+
233
+ input = unfold_func()
234
+ grad_output = grad_output.reshape(n, -1, input.shape[-1])
235
+
236
+ # n=batch_sz; o=num_out_channels; p=(num_in_channels/groups)*kernel_sz
237
+ weight_grad_sample = torch.einsum("noq,npq->nop", grad_output, input)
238
+ # rearrange the above tensor and extract diagonals.
239
+ # pyrefly: ignore [no-matching-overload]
240
+ weight_grad_sample = weight_grad_sample.view(
241
+ n,
242
+ groups,
243
+ -1,
244
+ groups,
245
+ int(in_channels / groups),
246
+ np.prod(kernel_size),
247
+ )
248
+ weight_grad_sample = torch.einsum(
249
+ "ngrg...->ngr...", weight_grad_sample
250
+ ).contiguous()
251
+ shape = [n] + list(weight_shape)
252
+ weight_grad_sample = weight_grad_sample.view(shape)
253
+ return weight_grad_sample
254
+
255
+
256
+ def conv_group_weight_grad_sample(
257
+ input,
258
+ grad_output,
259
+ weight_shape,
260
+ stride,
261
+ padding,
262
+ dilation,
263
+ batch_size,
264
+ func,
265
+ ):
266
+ I = input.shape[1]
267
+ O = grad_output.shape[1]
268
+
269
+ input_ = input.transpose(0, 1)
270
+ grad_output_ = grad_output.view(
271
+ grad_output.shape[0] * grad_output.shape[1], 1, *grad_output.shape[2:]
272
+ )
273
+
274
+ weight_grad_sample = func(
275
+ input_,
276
+ grad_output_,
277
+ None,
278
+ stride=dilation,
279
+ padding=padding,
280
+ dilation=stride,
281
+ groups=batch_size,
282
+ )
283
+ input_dims = conv_picker(func, 3, 4, 5)
284
+ for i in range(2, input_dims):
285
+ weight_grad_sample = weight_grad_sample.narrow(i, 0, weight_shape[i])
286
+ weight_grad_sample = weight_grad_sample.view(
287
+ I, batch_size, O, *weight_grad_sample.shape[2:]
288
+ )
289
+ weight_grad_sample = weight_grad_sample.movedim(0, 2)
290
+ return weight_grad_sample
291
+
292
+
293
+ def unfold3d(
294
+ tensor,
295
+ kernel_size,
296
+ padding,
297
+ stride,
298
+ dilation,
299
+ ):
300
+ r"""
301
+ Extract sliding local blocks from an batched input tensor.
302
+
303
+ :class:`torch.nn.Unfold` only supports 4D inputs (batched image-like tensors).
304
+ This method implements the same action for 5D inputs
305
+ Args:
306
+ tensor: An input tensor of shape ``(B, C, D, H, W)``.
307
+ kernel_size: the size of the sliding blocks
308
+ padding: implicit zero padding to be added on both sides of input
309
+ stride: the stride of the sliding blocks in the input spatial dimensions
310
+ dilation: the spacing between the kernel points.
311
+ Returns:
312
+ A tensor of shape ``(B, C * np.prod(kernel_size), L)``, where L - output spatial dimensions.
313
+ See :class:`torch.nn.Unfold` for more details
314
+ Example:
315
+ >>> # xdoctest: +SKIP
316
+ >>> B, C, D, H, W = 3, 4, 5, 6, 7
317
+ >>> tensor = torch.arange(1, B * C * D * H * W + 1.0).view(B, C, D, H, W)
318
+ >>> unfold3d(tensor, kernel_size=2, padding=0, stride=1).shape
319
+ torch.Size([3, 32, 120])
320
+ """
321
+
322
+ import numpy as np
323
+
324
+ if len(tensor.shape) != 5:
325
+ raise ValueError(
326
+ f"Input tensor must be of the shape [B, C, D, H, W]. Got{tensor.shape}"
327
+ )
328
+
329
+ if dilation != (1, 1, 1):
330
+ raise NotImplementedError(f"dilation={dilation} not supported.")
331
+
332
+ batch_size, channels, _, _, _ = tensor.shape
333
+
334
+ # Input shape: (B, C, D, H, W)
335
+ tensor = F.pad(
336
+ tensor, (padding[2], padding[2], padding[1], padding[1], padding[0], padding[0])
337
+ )
338
+ # Output shape: (B, C, D+2*padding[2], H+2*padding[1], W+2*padding[0])
339
+
340
+ tensor = tensor.unfold(dimension=2, size=kernel_size[0], step=stride[0])
341
+ tensor = tensor.unfold(dimension=3, size=kernel_size[1], step=stride[1])
342
+ tensor = tensor.unfold(dimension=4, size=kernel_size[2], step=stride[2])
343
+ # Output shape: (B, C, D_out, H_out, W_out, kernel_size[0], kernel_size[1], kernel_size[2])
344
+ # For D_out, H_out, W_out definitions see :class:`torch.nn.Unfold`
345
+
346
+ tensor = tensor.permute(0, 2, 3, 4, 1, 5, 6, 7)
347
+ # Output shape: (B, D_out, H_out, W_out, C, kernel_size[0], kernel_size[1], kernel_size[2])
348
+
349
+ tensor = tensor.reshape(batch_size, -1, channels * np.prod(kernel_size)).transpose(
350
+ 1, 2
351
+ )
352
+ # Output shape: (B, D_out * H_out * W_out, C * kernel_size[0] * kernel_size[1] * kernel_size[2]
353
+
354
+ return tensor
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/embedding_expanded_weights.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from .expanded_weights_impl import implements_per_sample_grads
7
+ from .expanded_weights_utils import (
8
+ forward_helper,
9
+ set_grad_sample_if_exists,
10
+ standard_kwargs,
11
+ )
12
+
13
+
14
+ @implements_per_sample_grads(F.embedding)
15
+ class EmbeddingPerSampleGrad(torch.autograd.Function):
16
+ @staticmethod
17
+ # pyrefly: ignore [bad-override]
18
+ def forward(
19
+ ctx: Any, kwarg_names: list[str], _: Any, *expanded_args_and_kwargs: Any
20
+ ) -> torch.Tensor:
21
+ expanded_args, expanded_kwargs = standard_kwargs(
22
+ kwarg_names, expanded_args_and_kwargs
23
+ )
24
+ if len(expanded_args[0].shape) == 1:
25
+ raise RuntimeError(
26
+ f"Expanded Weights needs an input with a batch size, got a 1D tensor, {expanded_args[0]}"
27
+ )
28
+ output = forward_helper(F.embedding, expanded_args, expanded_kwargs)
29
+ ctx.input, ctx.weight = expanded_args
30
+ ctx.padding_idx, ctx.scale_grad_by_freq = (
31
+ expanded_kwargs["padding_idx"],
32
+ expanded_kwargs["scale_grad_by_freq"],
33
+ )
34
+ ctx.sparse = expanded_kwargs["sparse"]
35
+ return output
36
+
37
+ @staticmethod
38
+ # pyrefly: ignore [bad-override]
39
+ def backward(
40
+ ctx: Any, grad_output: torch.Tensor
41
+ ) -> tuple[torch.Tensor | None, ...]:
42
+ input, weight = ctx.input, ctx.weight
43
+ padding_idx, scale_grad_by_freq, sparse = (
44
+ ctx.padding_idx,
45
+ ctx.scale_grad_by_freq,
46
+ ctx.sparse,
47
+ )
48
+
49
+ def weight_per_sample_grad(weight: torch.Tensor) -> torch.Tensor:
50
+ batch_size = input.shape[0]
51
+ embedding_dim = weight.shape[1]
52
+ index = (
53
+ input.unsqueeze(-1)
54
+ .expand(*input.shape, embedding_dim)
55
+ .reshape(batch_size, -1, embedding_dim)
56
+ )
57
+ grad_sample = torch.zeros( # type: ignore[attr-defined]
58
+ batch_size, *weight.shape, device=weight.device, dtype=grad_output.dtype
59
+ )
60
+ return grad_sample.scatter_add_(
61
+ 1, index, grad_output.reshape(batch_size, -1, embedding_dim)
62
+ )
63
+
64
+ results: list[torch.Tensor | None] = []
65
+ results.append(None) # for kwarg names
66
+ results.append(None) # for op reference
67
+
68
+ if input.requires_grad:
69
+ bw_fn = torch.ops.aten.embedding_backward
70
+ results.append(
71
+ bw_fn(
72
+ grad_output,
73
+ input,
74
+ weight.shape[0],
75
+ padding_idx,
76
+ scale_grad_by_freq,
77
+ sparse,
78
+ )
79
+ )
80
+ else:
81
+ results.append(None)
82
+
83
+ # weight doesn't compute batched gradients; no other arguments are differentiable (2 not saved from forward)
84
+ results = results + [None] * 6
85
+
86
+ # set grad_sample field for weight with per sample gradients
87
+ set_grad_sample_if_exists(weight, weight_per_sample_grad)
88
+ return tuple(results)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/expanded_weights_impl.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections.abc import Callable
4
+ from contextlib import contextmanager
5
+
6
+ import torch
7
+ from torch._decomp import decomposition_table
8
+ from torch.utils._pytree import tree_map_only
9
+
10
+
11
+ HANDLED_FUNCTIONS: dict[Callable, torch.autograd.Function] = {}
12
+
13
+ aten = torch._ops.ops.aten
14
+ # __torch_function__ runs before the pydispatcher so we need to manually use the same
15
+ # decompositions indexed by their torch equivalent
16
+ expanded_weights_rnn_decomps = {
17
+ # func: (input_decomp, data_decomp)
18
+ torch.rnn_relu: (
19
+ decomposition_table[aten.rnn_relu.input],
20
+ decomposition_table[aten.rnn_relu.data],
21
+ ),
22
+ torch.rnn_tanh: (
23
+ decomposition_table[aten.rnn_tanh.input],
24
+ decomposition_table[aten.rnn_tanh.data],
25
+ ),
26
+ torch.lstm: (
27
+ decomposition_table[aten.lstm.input],
28
+ decomposition_table[aten.lstm.data],
29
+ ),
30
+ torch.gru: (
31
+ decomposition_table[aten.gru.input],
32
+ decomposition_table[aten.gru.data],
33
+ ),
34
+ }
35
+
36
+
37
+ # all of the RNN decomps run linear with the batch dimension second, even if batch_first was set
38
+ @contextmanager
39
+ def batch_second(args, kwargs):
40
+ def set_batch_second(ew) -> None:
41
+ ew.set_batch_first(False)
42
+
43
+ def reset_batch_first(ew) -> None:
44
+ ew.set_batch_first(True)
45
+
46
+ tree_map_only(ExpandedWeight, set_batch_second, args)
47
+ tree_map_only(ExpandedWeight, set_batch_second, kwargs)
48
+ try:
49
+ yield
50
+ finally:
51
+ tree_map_only(ExpandedWeight, reset_batch_first, args)
52
+ tree_map_only(ExpandedWeight, reset_batch_first, kwargs)
53
+
54
+
55
+ # to support packed sequences, we need to allow for smaller batches. Expanded weights represents the largest batch
56
+ @contextmanager
57
+ def allow_smaller_batches(args, kwargs):
58
+ def allow(ew) -> None:
59
+ ew.set_allow_smaller_batches(True)
60
+
61
+ def reset(ew) -> None:
62
+ ew.set_allow_smaller_batches(False)
63
+
64
+ tree_map_only(ExpandedWeight, allow, args)
65
+ tree_map_only(ExpandedWeight, allow, kwargs)
66
+ try:
67
+ yield
68
+ finally:
69
+ tree_map_only(ExpandedWeight, reset, args)
70
+ tree_map_only(ExpandedWeight, reset, kwargs)
71
+
72
+
73
+ @contextmanager
74
+ def setup_rnn(use_input_variant, args, kwargs):
75
+ with (
76
+ batch_second(args, kwargs)
77
+ if use_input_variant
78
+ else allow_smaller_batches(args, kwargs)
79
+ ):
80
+ yield
81
+
82
+
83
+ def implements_per_sample_grads(torch_function):
84
+ @functools.wraps(torch_function)
85
+ def decorator(autograd_func):
86
+ HANDLED_FUNCTIONS[torch_function] = autograd_func
87
+ return autograd_func
88
+
89
+ return decorator
90
+
91
+
92
+ # ExpandedWeight represents a weight (parameter) Tensor that has an expanded
93
+ # batch dimension. Operations on the ExpandedWeight Tensor act exactly like
94
+ # those without an expanded batch dimension but a call to .backward() populates
95
+ # the original (unexpanded) tensor with per-sample-gradients for in the grad_sample field
96
+ #
97
+ # ExpandedWeight has a fallback that always fails since we cannot know what the batch
98
+ # dimension of the input tensor is and therefore cannot know if this is a valid call
99
+ #
100
+ # This is a __torch_function__ object but it could have also been a Tensor Extension
101
+ # with a dispatch key.
102
+ #
103
+ # Needs to be a tensor subclass to allow reparameterization
104
+ class ExpandedWeight(torch.Tensor):
105
+ def __init__(self, orig_weight, batch_size, loss_reduction) -> None:
106
+ self.batch_size = batch_size
107
+ self.batch_first = True
108
+ self.allow_smaller_batches = False
109
+ self.orig_weight = orig_weight
110
+ self.loss_reduction = loss_reduction
111
+
112
+ handled_functions = HANDLED_FUNCTIONS
113
+
114
+ def __new__(cls, orig_weight, batch_size, loss_reduction):
115
+ if not isinstance(orig_weight, torch.Tensor):
116
+ raise RuntimeError(
117
+ f"Can only make Expanded Weights of Tensors, got {type(orig_weight).__name__}"
118
+ )
119
+ if not orig_weight.requires_grad:
120
+ raise RuntimeError(
121
+ "Can only build ExpandedWeights objects of tensors that require_grad"
122
+ )
123
+ ret = torch.Tensor._make_subclass(cls, orig_weight, True)
124
+ return ret
125
+
126
+ @classmethod
127
+ def __torch_function__(cls, func, _, args=(), kwargs=None):
128
+ if kwargs is None:
129
+ kwargs = {}
130
+ if func in expanded_weights_rnn_decomps:
131
+ # in aten, choosing the input or data variants is done by parsing logic. This mimics some of that
132
+ decomp_opts = expanded_weights_rnn_decomps[func]
133
+ use_input_variant = isinstance(
134
+ # pyrefly: ignore [index-error]
135
+ args[2],
136
+ list,
137
+ ) # data variant uses a list here
138
+ decomp = decomp_opts[0] if use_input_variant else decomp_opts[1]
139
+
140
+ if decomp is not None:
141
+ with setup_rnn(use_input_variant, args, kwargs):
142
+ return decomp(*args, **kwargs)
143
+ if func is torch._cudnn_rnn_flatten_weight:
144
+ # since we aren't using the fused cuda kernels for RNNs, don't do this
145
+ return
146
+ if func in cls.handled_functions:
147
+ return cls.handled_functions[func].apply(
148
+ tuple(kwargs.keys()), func, *(args + tuple(kwargs.values()))
149
+ )
150
+ # We cannot use a fallback here because we do not know the batch dimension for any regular tensor inputs,
151
+ # i.e. torch.add(torch.Tensor, ExpandedWeight)
152
+ raise RuntimeError(
153
+ f"Expanded Weights encountered but cannot handle function {func.__name__}"
154
+ )
155
+
156
+ @property
157
+ def dtype(self): # type: ignore[override]
158
+ return self.orig_weight.dtype
159
+
160
+ @property
161
+ def data(self): # type: ignore[override]
162
+ return self.orig_weight.data
163
+
164
+ @property
165
+ def shape(self): # type: ignore[override]
166
+ return self.orig_weight.shape
167
+
168
+ @property
169
+ def device(self): # type: ignore[override]
170
+ return self.orig_weight.device
171
+
172
+ @property
173
+ def is_cuda(self): # type: ignore[override]
174
+ return self.orig_weight.is_cuda
175
+
176
+ def data_ptr(self):
177
+ return self.orig_weight.data_ptr()
178
+
179
+ def get_device(self):
180
+ return self.orig_weight.get_device()
181
+
182
+ def set_allow_smaller_batches(self, is_allow_smaller_batches) -> None:
183
+ self.allow_smaller_batches = is_allow_smaller_batches
184
+
185
+ def set_batch_first(self, is_batch_first=True) -> None:
186
+ self.batch_first = is_batch_first
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/expanded_weights_utils.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+
5
+ from .expanded_weights_impl import ExpandedWeight
6
+
7
+
8
+ def is_batch_first(expanded_args_and_kwargs):
9
+ batch_first = None
10
+ # pyrefly: ignore [bad-assignment]
11
+ for arg in expanded_args_and_kwargs:
12
+ if not isinstance(arg, ExpandedWeight):
13
+ continue
14
+
15
+ if not batch_first:
16
+ batch_first = arg.batch_first
17
+ elif arg.batch_first != batch_first:
18
+ raise RuntimeError(
19
+ "Got conflicting batch_first arguments in the same layer"
20
+ )
21
+ return batch_first
22
+
23
+
24
+ def standard_kwargs(kwarg_names, expanded_args):
25
+ r"""Separate args and kwargs from `__torch_function__`s that standardize kwargs.
26
+
27
+ Most `__torch_function__`s standardize the kwargs that they give, so this will separate
28
+ the args and kwargs they pass. Functions that don't are linear and convND.
29
+ """
30
+ kwarg_values = expanded_args[len(expanded_args) - len(kwarg_names) :]
31
+ expanded_args_without_kwargs = expanded_args[
32
+ : len(expanded_args) - len(kwarg_names)
33
+ ]
34
+ expanded_kwargs = dict(zip(kwarg_names, kwarg_values, strict=True))
35
+ return expanded_args_without_kwargs, expanded_kwargs
36
+
37
+
38
+ def forward_helper(func, expanded_args, expanded_kwargs):
39
+ r"""Compute the forward pass for a function that has expanded weight(s) passed to it.
40
+
41
+ It will run the forward pass where all ExpandedWeights are their original
42
+ weight. It runs checks on the given arguments and detaches the outputs.
43
+
44
+ .. note:: First argument in :attr:`expanded_args` must be the input with the batch
45
+ dimension as the first element of the shape
46
+
47
+ .. note:: :attr:`func` must return a Tensor or tuple of Tensors
48
+
49
+ Args:
50
+ func: The function to be called
51
+ expanded_args: Arguments to be passed to :attr:`func`. Will include arguments
52
+ that need to be unpacked because they are ExpandedWeights
53
+ expanded_kwargs: Keyword arguments to be passed to :attr:`func`.
54
+ Similar to :attr:`expanded_args`.
55
+ """
56
+ unexpanded_args, unexpanded_kwargs = _check_and_unexpand_args(
57
+ func, expanded_args, expanded_kwargs
58
+ )
59
+ return func(*unexpanded_args, **unexpanded_kwargs)
60
+
61
+
62
+ def _check_and_unexpand_args(func, expanded_args, expanded_kwargs):
63
+ # input must be the first argument passed
64
+ input = expanded_args[0]
65
+ if isinstance(input, ExpandedWeight):
66
+ raise RuntimeError(
67
+ "Expanded Weights do not support inputs that are also ExpandedWeights. "
68
+ f"Input must be a Tensor, got {type(input).__name__} in function {func.__name__}"
69
+ )
70
+ if not isinstance(input, torch.Tensor):
71
+ raise RuntimeError(
72
+ "Expanded Weights requires a Tensor as the first input to get the batch dimension, "
73
+ f"got {type(input).__name__} in function {func.__name__}"
74
+ )
75
+ if len(input.shape) == 0:
76
+ raise RuntimeError(
77
+ f"Expanded Weights requires a batch dimension but got an input of size 0 in function {func.__name__}"
78
+ )
79
+ if input.shape[0] == 0:
80
+ raise RuntimeError(
81
+ "0 is not a valid batch size for Expanded Weights but got input tensor of "
82
+ f"{input} in function {func.__name__}"
83
+ )
84
+ for arg in expanded_args + tuple(expanded_kwargs.values()):
85
+ if not isinstance(arg, ExpandedWeight):
86
+ continue
87
+ batch_size = input.shape[0] if arg.batch_first else input.shape[1]
88
+ if (arg.allow_smaller_batches and batch_size > arg.batch_size) or (
89
+ not arg.allow_smaller_batches and arg.batch_size != batch_size
90
+ ):
91
+ raise RuntimeError(
92
+ "Expected ExpandedWeights to have batch size matching input but got "
93
+ f"input batch size of {batch_size} with ExpandedWeight of batch size {arg.batch_size}"
94
+ )
95
+
96
+ loss_reduction: str | None = None
97
+ for arg in expanded_args + tuple(expanded_kwargs.values()):
98
+ if isinstance(arg, ExpandedWeight):
99
+ if loss_reduction is None:
100
+ loss_reduction = arg.loss_reduction
101
+ elif loss_reduction != arg.loss_reduction:
102
+ raise RuntimeError(
103
+ "Expected ExpandedWeights to all have the same loss_reduction argument but got one"
104
+ f"with {loss_reduction} and one with {arg.loss_reduction}"
105
+ )
106
+
107
+ unexpanded_args = tuple(
108
+ arg.orig_weight if isinstance(arg, ExpandedWeight) else arg
109
+ for arg in expanded_args
110
+ )
111
+ unexpanded_kwargs = {
112
+ name: arg.orig_weight if isinstance(arg, ExpandedWeight) else arg
113
+ for (name, arg) in expanded_kwargs.items()
114
+ }
115
+ return unexpanded_args, unexpanded_kwargs
116
+
117
+
118
+ def maybe_scale_by_batch_size(grad_sample, expanded_weight):
119
+ if expanded_weight.loss_reduction == "mean":
120
+ return grad_sample * expanded_weight.batch_size
121
+ else:
122
+ return grad_sample
123
+
124
+
125
+ def set_grad_sample_if_exists(maybe_expanded_weight, per_sample_grad_fn) -> None:
126
+ unpacked = unpack_expanded_weight_or_tensor(maybe_expanded_weight)
127
+ if isinstance(maybe_expanded_weight, ExpandedWeight):
128
+ grad_sample_contribution = maybe_scale_by_batch_size(
129
+ per_sample_grad_fn(unpacked), maybe_expanded_weight
130
+ )
131
+
132
+ if maybe_expanded_weight.batch_size > grad_sample_contribution.shape[0]:
133
+ # this only passes the other checks if the arg allows smaller batch sizes
134
+ intermediate = torch.zeros(
135
+ maybe_expanded_weight.batch_size,
136
+ *grad_sample_contribution.shape[1:],
137
+ dtype=grad_sample_contribution.dtype,
138
+ device=grad_sample_contribution.device,
139
+ )
140
+ intermediate[: grad_sample_contribution.shape[0]] = grad_sample_contribution
141
+ grad_sample_contribution = intermediate
142
+
143
+ if hasattr(unpacked, "grad_sample") and unpacked.grad_sample is not None:
144
+ unpacked.grad_sample = unpacked.grad_sample + grad_sample_contribution
145
+ else:
146
+ unpacked.grad_sample = grad_sample_contribution
147
+
148
+
149
+ def unpack_expanded_weight_or_tensor(maybe_expanded_weight, func=lambda x: x):
150
+ if isinstance(maybe_expanded_weight, ExpandedWeight):
151
+ orig_weight = maybe_expanded_weight.orig_weight
152
+ return func(orig_weight)
153
+ elif (
154
+ isinstance(maybe_expanded_weight, torch.Tensor)
155
+ and not maybe_expanded_weight.requires_grad
156
+ ):
157
+ return func(maybe_expanded_weight)
158
+ elif isinstance(maybe_expanded_weight, torch.Tensor):
159
+ raise RuntimeError(
160
+ "ExpandedWeights currently does not support a mixture of ExpandedWeight parameters "
161
+ "and normal Parameters. Please file and issue with pytorch/pytorch"
162
+ )
163
+
164
+
165
+ def sum_over_all_but_batch_and_last_n(
166
+ tensor: torch.Tensor,
167
+ n_dims: int,
168
+ ) -> torch.Tensor:
169
+ r"""
170
+ Calculate the sum over all dimensions, except the first (batch dimension), and excluding the last n_dims.
171
+
172
+ This function will ignore the first dimension and it will
173
+ not aggregate over the last n_dims dimensions.
174
+ Args:
175
+ tensor: An input tensor of shape ``(B, ..., X[n_dims-1])``.
176
+ n_dims: Number of dimensions to keep.
177
+ Example:
178
+ >>> tensor = torch.ones(1, 2, 3, 4, 5)
179
+ >>> sum_over_all_but_batch_and_last_n(tensor, n_dims=2).shape
180
+ torch.Size([1, 4, 5])
181
+ Returns:
182
+ A tensor of shape ``(B, ..., X[n_dims-1])``
183
+ """
184
+ if tensor.dim() == n_dims + 1:
185
+ return tensor
186
+ else:
187
+ dims = list(range(1, tensor.dim() - n_dims))
188
+ return tensor.sum(dim=dims)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/group_norm_expanded_weights.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ from functools import reduce
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+
8
+ from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
9
+ from .expanded_weights_utils import (
10
+ forward_helper,
11
+ set_grad_sample_if_exists,
12
+ standard_kwargs,
13
+ unpack_expanded_weight_or_tensor,
14
+ )
15
+
16
+
17
+ @implements_per_sample_grads(F.group_norm)
18
+ class GroupNormPerSampleGrad(torch.autograd.Function):
19
+ @staticmethod
20
+ # pyrefly: ignore [bad-override]
21
+ def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
22
+ expanded_args, expanded_kwargs = standard_kwargs(
23
+ kwarg_names, expanded_args_and_kwargs
24
+ )
25
+ input, num_groups = expanded_args
26
+ N = input.shape[0]
27
+ C = input.shape[1]
28
+ HxW = reduce(operator.mul, input.shape[2:], 1)
29
+ weight, bias, eps = (
30
+ expanded_kwargs["weight"],
31
+ expanded_kwargs["bias"],
32
+ expanded_kwargs["eps"],
33
+ )
34
+ output, mean, rstd = forward_helper(
35
+ torch.native_group_norm,
36
+ (input, weight, bias, N, C, HxW, num_groups, eps),
37
+ {},
38
+ )
39
+ ctx.input, ctx.num_groups = input, num_groups
40
+ ctx.weight, ctx.eps = weight, eps
41
+ ctx.mean, ctx.rstd = mean, rstd
42
+ if isinstance(bias, ExpandedWeight):
43
+ ctx.bias = bias
44
+ if input.requires_grad and isinstance(weight, ExpandedWeight):
45
+ ctx.weight = weight
46
+ return output
47
+
48
+ @staticmethod
49
+ # pyrefly: ignore [bad-override]
50
+ def backward(ctx, grad_output):
51
+ input, num_groups = ctx.input, ctx.num_groups
52
+ weight, bias, eps = ctx.weight, ctx.bias, ctx.eps
53
+ mean, rstd = ctx.mean, ctx.rstd
54
+
55
+ results: list[torch.Tensor | None] = []
56
+ results.append(None) # for kwarg names
57
+ results.append(None) # for op reference
58
+
59
+ if input.requires_grad:
60
+ weight_c = unpack_expanded_weight_or_tensor(
61
+ weight, lambda t: t.contiguous()
62
+ )
63
+ input_c = input.contiguous()
64
+ grad_output_c = (
65
+ grad_output.contiguous() if grad_output is not None else None
66
+ )
67
+ N = input.shape[0]
68
+ C = input.shape[1]
69
+ HxW = 1
70
+ for s in input.shape[2:]:
71
+ HxW *= s
72
+ bw_fn = torch.ops.aten.native_group_norm_backward
73
+ results.append(
74
+ bw_fn(
75
+ grad_output_c,
76
+ input_c,
77
+ mean,
78
+ rstd,
79
+ weight_c,
80
+ N,
81
+ C,
82
+ HxW,
83
+ num_groups,
84
+ (True, False, False),
85
+ )[0]
86
+ )
87
+ else:
88
+ results.append(None)
89
+
90
+ # weight and bias don't compute batched gradients; no other arguments are differentiable
91
+ results = results + [None] * 4
92
+
93
+ # set grad_sample field for weight and bias with per sample gradients
94
+ if hasattr(ctx, "weight"):
95
+ set_grad_sample_if_exists(
96
+ weight,
97
+ lambda _: torch.einsum(
98
+ "ni...->ni",
99
+ # pyrefly: ignore [unsupported-operation]
100
+ F.group_norm(input, num_groups, eps=eps) * grad_output,
101
+ ),
102
+ )
103
+ if hasattr(ctx, "bias"):
104
+ set_grad_sample_if_exists(
105
+ bias, lambda _: torch.einsum("ni...->ni", grad_output)
106
+ )
107
+ return tuple(results)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/instance_norm_expanded_weights.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from functools import partial
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+ from .expanded_weights_impl import implements_per_sample_grads
8
+ from .expanded_weights_utils import (
9
+ forward_helper,
10
+ set_grad_sample_if_exists,
11
+ standard_kwargs,
12
+ unpack_expanded_weight_or_tensor,
13
+ )
14
+
15
+
16
+ @implements_per_sample_grads(F.instance_norm)
17
+ class InstanceNormPerSampleGrad(torch.autograd.Function):
18
+ @staticmethod
19
+ # pyrefly: ignore [bad-override]
20
+ def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
21
+ instance_norm = partial(torch.instance_norm, cudnn_enabled=True)
22
+ expanded_args, expanded_kwargs = standard_kwargs(
23
+ kwarg_names, expanded_args_and_kwargs
24
+ )
25
+ output = forward_helper(instance_norm, expanded_args, expanded_kwargs)
26
+ ctx.input = expanded_args[0]
27
+ ctx.running_mean, ctx.running_var = (
28
+ expanded_kwargs["running_mean"],
29
+ expanded_kwargs["running_var"],
30
+ )
31
+ ctx.weight, ctx.bias, ctx.eps = (
32
+ expanded_kwargs["weight"],
33
+ expanded_kwargs["bias"],
34
+ expanded_kwargs["eps"],
35
+ )
36
+ return output
37
+
38
+ @staticmethod
39
+ # pyrefly: ignore [bad-override]
40
+ def backward(ctx, grad_output):
41
+ input, running_mean, running_var = ctx.input, ctx.running_mean, ctx.running_var
42
+ weight, bias, eps = ctx.weight, ctx.bias, ctx.eps
43
+
44
+ results: list[torch.Tensor | None] = []
45
+ results.append(None) # for kwarg names
46
+ results.append(None) # for op reference
47
+ if input.requires_grad:
48
+ b = input.shape[0]
49
+ c = input.shape[1]
50
+ new_shape = (1, b * c, *input.shape[2:])
51
+
52
+ weight_ = unpack_expanded_weight_or_tensor(
53
+ weight, lambda orig_weight: orig_weight.repeat(b)
54
+ )
55
+ running_mean_ = running_mean.repeat(b) if running_mean is not None else None
56
+ running_var_ = running_var.repeat(b) if running_var is not None else None
57
+ input_reshaped = input.contiguous().view(new_shape)
58
+ grad_output_reshaped = grad_output.contiguous().view(new_shape)
59
+ mean = torch.mean(
60
+ input_reshaped, (0,) + tuple(range(2, input.dim())), False
61
+ )
62
+ var = torch.var(
63
+ input_reshaped,
64
+ (0,) + tuple(range(2, input.dim())),
65
+ keepdim=False,
66
+ unbiased=False,
67
+ )
68
+ rstd = 1 / torch.sqrt(var + eps)
69
+
70
+ # must use native batch norm since it supports all inputs. This may have used cuda or openmi during the forward but
71
+ # it didn't save the metadata, so we don't know during the backward
72
+ res = torch.ops.aten.native_batch_norm_backward(
73
+ grad_output_reshaped,
74
+ input_reshaped,
75
+ weight_,
76
+ running_mean_,
77
+ running_var_,
78
+ mean,
79
+ rstd,
80
+ True,
81
+ eps,
82
+ (True, False, False),
83
+ )
84
+ results.append(res[0].reshape(input.shape))
85
+ else:
86
+ results.append(None)
87
+
88
+ # weight and bias don't compute batched gradients; no other arguments are differentiable (2 are not saved from the forward)
89
+ results = results + [None] * 7
90
+
91
+ # set grad_sample field for weight and bias with per sample gradients
92
+ set_grad_sample_if_exists(
93
+ weight,
94
+ lambda _: torch.einsum(
95
+ "ni...->ni", F.instance_norm(input, eps=eps) * grad_output
96
+ ),
97
+ )
98
+ set_grad_sample_if_exists(
99
+ bias, lambda _: torch.einsum("ni...->ni", grad_output)
100
+ )
101
+ return tuple(results)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/layer_norm_expanded_weights.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from .expanded_weights_impl import ExpandedWeight, implements_per_sample_grads
7
+ from .expanded_weights_utils import (
8
+ forward_helper,
9
+ set_grad_sample_if_exists,
10
+ standard_kwargs,
11
+ sum_over_all_but_batch_and_last_n,
12
+ unpack_expanded_weight_or_tensor,
13
+ )
14
+
15
+
16
+ @implements_per_sample_grads(F.layer_norm)
17
+ class LayerNormPerSampleGrad(torch.autograd.Function):
18
+ @staticmethod
19
+ # pyrefly: ignore [bad-override]
20
+ def forward(ctx, kwarg_names, _, *expanded_args_and_kwargs):
21
+ expanded_args, expanded_kwargs = standard_kwargs(
22
+ kwarg_names, expanded_args_and_kwargs
23
+ )
24
+ input = expanded_args[0]
25
+ normalized_shape = expanded_args[1]
26
+ if len(input.shape) <= len(normalized_shape):
27
+ raise RuntimeError(
28
+ "Expanded Weights: Layer norm should not normalize over batch dimension for per sample gradient"
29
+ f"computations but got that normalized shape, {normalized_shape}, matched input shape."
30
+ )
31
+ output, mean, rstd = forward_helper(
32
+ torch.native_layer_norm, expanded_args, expanded_kwargs
33
+ )
34
+ ctx.args = expanded_args
35
+
36
+ if input.requires_grad or isinstance(expanded_kwargs["weight"], ExpandedWeight):
37
+ ctx.weight = expanded_kwargs["weight"]
38
+ if input.requires_grad or isinstance(expanded_kwargs["bias"], ExpandedWeight):
39
+ ctx.bias = expanded_kwargs["bias"]
40
+ ctx.eps = expanded_kwargs["eps"]
41
+ ctx.mean, ctx.rstd = mean, rstd
42
+ return output
43
+
44
+ @staticmethod
45
+ # pyrefly: ignore [bad-override]
46
+ def backward(ctx, grad_output):
47
+ def weight_per_sample_grad(weight):
48
+ return sum_over_all_but_batch_and_last_n(
49
+ F.layer_norm(input, normalized_shape, eps=ctx.eps) * grad_output,
50
+ weight.dim(),
51
+ )
52
+
53
+ input, normalized_shape = ctx.args
54
+ mean, rstd = ctx.mean, ctx.rstd
55
+
56
+ results: list[torch.Tensor | None] = []
57
+ results.append(None) # for kwarg names
58
+ results.append(None) # for op reference
59
+ if input.requires_grad:
60
+ weight_ = unpack_expanded_weight_or_tensor(ctx.weight)
61
+ bias_ = unpack_expanded_weight_or_tensor(ctx.bias)
62
+ results.append(
63
+ torch.ops.aten.native_layer_norm_backward(
64
+ grad_output,
65
+ input,
66
+ normalized_shape,
67
+ mean,
68
+ rstd,
69
+ weight_,
70
+ bias_,
71
+ (True, False, False),
72
+ )[0]
73
+ )
74
+ else:
75
+ results.append(None)
76
+
77
+ # weight and bias don't compute batched gradients; no other arguments are differentiable
78
+ results = results + [None] * 4
79
+
80
+ # set grad_sample field for weight and bias with per sample gradients
81
+ if hasattr(ctx, "weight"):
82
+ set_grad_sample_if_exists(ctx.weight, weight_per_sample_grad)
83
+ if hasattr(ctx, "bias"):
84
+ set_grad_sample_if_exists(
85
+ ctx.bias,
86
+ lambda bias: sum_over_all_but_batch_and_last_n(grad_output, bias.dim()),
87
+ )
88
+ return tuple(results)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_expanded_weights/linear_expanded_weights.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from .expanded_weights_impl import implements_per_sample_grads
7
+ from .expanded_weights_utils import (
8
+ forward_helper,
9
+ is_batch_first,
10
+ set_grad_sample_if_exists,
11
+ unpack_expanded_weight_or_tensor,
12
+ )
13
+
14
+
15
+ @implements_per_sample_grads(F.linear)
16
+ class LinearPerSampleGrad(torch.autograd.Function):
17
+ @staticmethod
18
+ # pyrefly: ignore [bad-override]
19
+ def forward(ctx, _, __, *expanded_args_and_kwargs):
20
+ if len(expanded_args_and_kwargs[0].shape) <= 1:
21
+ raise RuntimeError(
22
+ "Input does not have a batch dimension. Expanded Weights expected input "
23
+ f"of at least rank 2, got of rank {len(expanded_args_and_kwargs[0].shape)}"
24
+ )
25
+ expanded_kwargs = {
26
+ "bias": expanded_args_and_kwargs[2]
27
+ if len(expanded_args_and_kwargs) == 3
28
+ else None
29
+ }
30
+ expanded_args = expanded_args_and_kwargs[:2]
31
+ ctx.batch_first = is_batch_first(expanded_args_and_kwargs)
32
+ output = forward_helper(F.linear, expanded_args, expanded_kwargs)
33
+ ctx.args = expanded_args
34
+ ctx.kwargs = expanded_kwargs
35
+ return output
36
+
37
+ @staticmethod
38
+ # pyrefly: ignore [bad-override]
39
+ def backward(ctx, grad_output):
40
+ input, weight = ctx.args
41
+ bias = ctx.kwargs["bias"]
42
+ results: list[torch.Tensor | None] = []
43
+ results.append(None) # for kwarg_names
44
+ results.append(None) # for op reference
45
+
46
+ if input.requires_grad:
47
+ results.append(grad_output.matmul(unpack_expanded_weight_or_tensor(weight)))
48
+ else:
49
+ results.append(None)
50
+ results.extend([None] * 2) # weight and bias don't compute batched gradients
51
+
52
+ if not ctx.batch_first:
53
+ grad_output = grad_output.transpose(0, 1)
54
+ input = input.transpose(0, 1)
55
+
56
+ # weight and bias get their grad_sample fields set directly if they exist
57
+ set_grad_sample_if_exists(
58
+ weight, lambda _: torch.einsum("n...i,n...j->nij", grad_output, input)
59
+ )
60
+ set_grad_sample_if_exists(
61
+ bias, lambda _: torch.einsum("n...k->nk", grad_output)
62
+ )
63
+ return tuple(results)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_named_member_accessor.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This source code is licensed under the BSD-style license found in the
2
+ # LICENSE file in the root directory of this source tree.
3
+
4
+ from collections.abc import Iterable
5
+
6
+ import torch
7
+
8
+
9
+ _MISSING: torch.Tensor = object() # type: ignore[assignment]
10
+
11
+
12
+ def set_tensor(module: "torch.nn.Module", name: str, tensor: torch.Tensor) -> None:
13
+ if not isinstance(module, torch.nn.Module):
14
+ raise TypeError(f"{module} is not an instance of torch.nn.Module")
15
+ if not isinstance(tensor, torch.Tensor) and tensor is not None:
16
+ raise TypeError(f"{tensor} is not an instance of torch.Tensor")
17
+ if "." in name:
18
+ raise KeyError('tensor name can\'t contain "."')
19
+ if name == "":
20
+ raise KeyError('tensor name can\'t be empty string ""')
21
+ if name in module._parameters:
22
+ module._parameters[name] = tensor # type: ignore[assignment]
23
+ elif name in module._buffers:
24
+ module._buffers[name] = tensor
25
+ else:
26
+ setattr(module, name, tensor)
27
+
28
+
29
+ def swap_tensor(
30
+ module: "torch.nn.Module",
31
+ name: str,
32
+ tensor: torch.Tensor,
33
+ allow_missing: bool = False,
34
+ ) -> torch.Tensor:
35
+ if not isinstance(module, torch.nn.Module):
36
+ raise TypeError(f"{module} is not an instance of torch.nn.Module")
37
+ if (
38
+ tensor is not _MISSING
39
+ and not isinstance(tensor, torch.Tensor)
40
+ and tensor is not None
41
+ ):
42
+ raise TypeError(f"{tensor} is not an instance of torch.Tensor")
43
+ if "." in name:
44
+ raise KeyError('tensor name can\'t contain "."')
45
+ if name == "":
46
+ raise KeyError('tensor name can\'t be empty string ""')
47
+
48
+ orig_tensor: torch.Tensor
49
+ if name in module._parameters:
50
+ orig_tensor = module._parameters[name] # type: ignore[assignment]
51
+ if tensor is not _MISSING:
52
+ module._parameters[name] = tensor # type: ignore[assignment]
53
+ else:
54
+ del module._parameters[name]
55
+ elif name in module._buffers:
56
+ orig_tensor = module._buffers[name] # type: ignore[assignment]
57
+ if tensor is not _MISSING:
58
+ module._buffers[name] = tensor
59
+ else:
60
+ del module._buffers[name]
61
+ else:
62
+ if hasattr(module, name):
63
+ orig_tensor = getattr(module, name)
64
+ else:
65
+ if not allow_missing:
66
+ raise AttributeError(f"{module._get_name()} has no attribute `{name}`")
67
+ orig_tensor = _MISSING
68
+ if (
69
+ orig_tensor is not _MISSING
70
+ and not isinstance(orig_tensor, torch.Tensor)
71
+ and orig_tensor is not None
72
+ ):
73
+ raise TypeError(
74
+ f"attribute `{name}`: {orig_tensor} is not an instance of torch.Tensor"
75
+ )
76
+ if tensor is not _MISSING:
77
+ setattr(module, name, tensor)
78
+ elif hasattr(module, name):
79
+ delattr(module, name)
80
+ # pyrefly: ignore [bad-return]
81
+ return orig_tensor
82
+
83
+
84
+ def swap_submodule(
85
+ module: "torch.nn.Module",
86
+ name: str,
87
+ submodule: "torch.nn.Module",
88
+ ) -> "torch.nn.Module":
89
+ if not isinstance(module, torch.nn.Module):
90
+ raise TypeError(f"{module} is not an instance of torch.nn.Module")
91
+ if not isinstance(submodule, torch.nn.Module):
92
+ raise TypeError(f"{submodule} is not an instance of torch.nn.Module")
93
+ if "." in name:
94
+ raise KeyError('submodule name can\'t contain "."')
95
+ if name == "":
96
+ raise KeyError('submodule name can\'t be empty string ""')
97
+ if name not in module._modules:
98
+ raise KeyError(f"submodule {name} does not exist")
99
+
100
+ orig_submodule = module._modules[name]
101
+ if not isinstance(orig_submodule, torch.nn.Module):
102
+ raise TypeError(f"{name} attribute is not an instance of torch.nn.Module")
103
+ module._modules[name] = submodule
104
+ return orig_submodule
105
+
106
+
107
+ class NamedMemberAccessor:
108
+ """
109
+ A class that provides a way to access the submodules and parameters/buffers of a module.
110
+
111
+ It provides caching mechanism to speed up submodule lookups.
112
+ This is useful for functional programming to manipulate the module state.
113
+ """
114
+
115
+ def __init__(self, module: "torch.nn.Module") -> None:
116
+ self.module = module
117
+ self.memo: dict[str, torch.nn.Module] = {}
118
+
119
+ # Nested attribute access
120
+
121
+ def get_submodule(self, name: str) -> "torch.nn.Module":
122
+ """
123
+ Return the submodule specified by the given path.
124
+
125
+ For example, to get the submodule mod.layer1.conv1,
126
+ use accessor.get_submodule("layer1.conv1")
127
+
128
+ Compare to mod.get_submodule("layer1.conv1"), this method will cache the
129
+ intermediate submodule access to speed up future lookups.
130
+ """
131
+ if not name:
132
+ return self.module
133
+
134
+ if name in self.memo:
135
+ return self.memo[name]
136
+ else:
137
+ prefix, dot, attr = name.rpartition(".")
138
+ if dot:
139
+ module = self.get_submodule(prefix)
140
+ else:
141
+ module = self.module
142
+ try:
143
+ submodule = getattr(module, attr)
144
+ except AttributeError as ex:
145
+ raise AttributeError(
146
+ f"{module._get_name()} has no attribute `{attr}`"
147
+ ) from ex
148
+ if not isinstance(submodule, torch.nn.Module):
149
+ raise TypeError(
150
+ f"submodule `{name}`: {submodule} is not an instance of torch.nn.Module"
151
+ )
152
+ self.memo[name] = submodule
153
+ return submodule
154
+
155
+ def swap_submodule(self, path: str, value: "torch.nn.Module") -> "torch.nn.Module":
156
+ """
157
+ Swap the submodule specified by the given ``path`` to ``value``.
158
+
159
+ For example, to swap the attribute mod.layer1.conv1 use
160
+ ``accessor.swap_submodule("layer1.conv1", conv2)``.
161
+ """
162
+ prefix, _, attr = path.rpartition(".")
163
+ return swap_submodule(self.get_submodule(prefix), attr, value)
164
+
165
+ def get_tensor(self, name: str) -> torch.Tensor:
166
+ """
167
+ Get the tensor specified by the given path to value.
168
+
169
+ For example, to get the attribute mod.layer1.conv1.weight,
170
+ use accessor.get_tensor('layer1.conv1.weight')
171
+
172
+ Compare to mod.get_parameter("layer1.conv1.weight"), this method will
173
+ cache the intermediate submodule access to speed up future lookups.
174
+ """
175
+ prefix, _, attr = name.rpartition(".")
176
+ submodule = self.get_submodule(prefix)
177
+ try:
178
+ tensor = getattr(submodule, attr)
179
+ except AttributeError as ex:
180
+ raise AttributeError(
181
+ f"{submodule._get_name()} has no attribute `{name}`"
182
+ ) from ex
183
+ if not isinstance(tensor, torch.Tensor) and tensor is not None:
184
+ raise TypeError(f"{tensor} is not an instance of torch.Tensor")
185
+ return tensor # type: ignore[return-value]
186
+
187
+ def set_tensor(self, name: str, value: torch.Tensor) -> None:
188
+ """
189
+ Set the attribute specified by the given path to value.
190
+
191
+ For example, to set the attribute mod.layer1.conv1.weight,
192
+ use accessor.set_tensor("layer1.conv1.weight", value)
193
+ """
194
+ prefix, _, attr = name.rpartition(".")
195
+ set_tensor(self.get_submodule(prefix), attr, value)
196
+
197
+ def del_tensor(self, name: str) -> None:
198
+ """
199
+ Delete the attribute specified by the given path.
200
+
201
+ For example, to delete the attribute mod.layer1.conv1.weight,
202
+ use accessor.del_tensor("layer1.conv1.weight")
203
+ """
204
+ prefix, _, attr = name.rpartition(".")
205
+ submodule = self.get_submodule(prefix)
206
+ try:
207
+ delattr(submodule, attr)
208
+ except AttributeError as ex:
209
+ raise AttributeError(
210
+ f"{submodule._get_name()} has no attribute `{name}`"
211
+ ) from ex
212
+
213
+ def swap_tensor(
214
+ self, name: str, value: torch.Tensor, allow_missing: bool = False
215
+ ) -> torch.Tensor:
216
+ """
217
+ Swap the attribute specified by the given path to value.
218
+
219
+ For example, to swap the attribute mod.layer1.conv1.weight,
220
+ use accessor.swap_tensor("layer1.conv1.weight", value)
221
+ """
222
+ prefix, _, attr = name.rpartition(".")
223
+ return swap_tensor(
224
+ self.get_submodule(prefix), attr, value, allow_missing=allow_missing
225
+ )
226
+
227
+ # Batched operations
228
+
229
+ def get_tensors(self, names: Iterable[str]) -> list[torch.Tensor]:
230
+ """
231
+ Get the tensors specified by the given paths.
232
+
233
+ For example, to get the attributes mod.layer1.conv1.weight and
234
+ mod.layer1.conv1.bias, use accessor.get_tensors(["layer1.conv1.weight",
235
+ "layer1.conv1.bias"])
236
+ """
237
+ return [self.get_tensor(name) for name in names]
238
+
239
+ def set_tensors(self, names: Iterable[str], values: Iterable[torch.Tensor]) -> None:
240
+ """
241
+ Set the attributes specified by the given paths to values.
242
+
243
+ For example, to set the attributes mod.layer1.conv1.weight and
244
+ mod.layer1.conv1.bias, use accessor.set_tensors(["layer1.conv1.weight",
245
+ "layer1.conv1.bias"], [weight, bias])
246
+ """
247
+ if not isinstance(names, (list, tuple)):
248
+ names = list(names)
249
+ if not isinstance(values, (list, tuple)):
250
+ values = list(values)
251
+ assert len(names) == len(values), "names and values must have the same length"
252
+
253
+ for name, value in zip(names, values, strict=True):
254
+ self.set_tensor(name, value)
255
+
256
+ def set_tensors_dict(self, named_tensors: dict[str, torch.Tensor]) -> None:
257
+ """
258
+ Set the attributes specified by the given paths to values.
259
+
260
+ For example, to set the attributes mod.layer1.conv1.weight and
261
+ mod.layer1.conv1.bias, use accessor.set_tensors_dict({
262
+ "layer1.conv1.weight": weight,
263
+ "layer1.conv1.bias": bias,
264
+ })
265
+ """
266
+ for name, value in named_tensors.items():
267
+ self.set_tensor(name, value)
268
+
269
+ def del_tensors(self, names: Iterable[str]) -> None:
270
+ """
271
+ Delete the attributes specified by the given paths.
272
+
273
+ For example, to delete the attributes mod.layer1.conv1.weight and
274
+ mod.layer1.conv1.bias, use accessor.del_tensors(["layer1.conv1.weight",
275
+ "layer1.conv1.bias"])
276
+ """
277
+ for name in names:
278
+ self.del_tensor(name)
279
+
280
+ def swap_tensors(
281
+ self,
282
+ names: Iterable[str],
283
+ values: Iterable[torch.Tensor],
284
+ allow_missing: bool = False,
285
+ ) -> list[torch.Tensor]:
286
+ """
287
+ Swap the attributes specified by the given paths to values.
288
+
289
+ For example, to swap the attributes mod.layer1.conv1.weight and
290
+ mod.layer1.conv1.bias, use accessor.swap_tensors(["layer1.conv1.weight",
291
+ "layer1.conv1.bias"], [weight, bias])
292
+ """
293
+ if not isinstance(names, (list, tuple)):
294
+ names = list(names)
295
+ if not isinstance(values, (list, tuple)):
296
+ values = list(values)
297
+ assert len(names) == len(values), "names and values must have the same length"
298
+
299
+ return [
300
+ self.swap_tensor(name, value, allow_missing=allow_missing)
301
+ for name, value in zip(names, values, strict=True)
302
+ ]
303
+
304
+ def swap_tensors_dict(
305
+ self, named_tensors: dict[str, torch.Tensor], allow_missing: bool = False
306
+ ) -> tuple[dict[str, torch.Tensor], list[str]]:
307
+ """
308
+ Swap the attributes specified by the given paths to values.
309
+
310
+ For example, to swap the attributes mod.layer1.conv1.weight and
311
+ mod.layer1.conv1.bias, use accessor.swap_tensors_dict({
312
+ "layer1.conv1.weight": weight,
313
+ "layer1.conv1.bias": bias,
314
+ })
315
+ """
316
+ orig_named_tensors = {}
317
+ missing_keys = []
318
+ try:
319
+ for name, tensor in named_tensors.items():
320
+ orig_tensor = self.swap_tensor(name, tensor, allow_missing=True)
321
+ if orig_tensor is _MISSING:
322
+ missing_keys.append(name)
323
+ orig_named_tensors[name] = orig_tensor
324
+ except Exception:
325
+ # Swap back if any exception occurs
326
+ for name, orig_tensor in orig_named_tensors.items():
327
+ self.swap_tensor(name, orig_tensor, allow_missing=True)
328
+ raise
329
+ if missing_keys and not allow_missing:
330
+ # Swap back if any key is missing when allow_missing is False
331
+ for name, orig_tensor in orig_named_tensors.items():
332
+ self.swap_tensor(name, orig_tensor, allow_missing=True)
333
+ raise RuntimeError(f"Missing key(s): {', '.join(map(repr, missing_keys))}.")
334
+ return orig_named_tensors, missing_keys
335
+
336
+ def check_keys(self, keys: Iterable[str]) -> tuple[list[str], list[str]]:
337
+ """Check that the given keys are valid."""
338
+ keys = set(keys)
339
+ valid_keys = {name for name, _ in self.named_tensors(remove_duplicate=False)}
340
+ missing_keys = valid_keys - keys
341
+ unexpected_keys = keys - valid_keys
342
+ return sorted(missing_keys), sorted(unexpected_keys)
343
+
344
+ # Shortcut methods
345
+
346
+ def named_parameters(
347
+ self,
348
+ remove_duplicate: bool = True,
349
+ ) -> Iterable[tuple[str, torch.Tensor]]:
350
+ """Iterate over all the parameters in the module."""
351
+ yield from self.module.named_parameters(remove_duplicate=remove_duplicate)
352
+
353
+ def named_buffers(
354
+ self,
355
+ remove_duplicate: bool = True,
356
+ ) -> Iterable[tuple[str, torch.Tensor]]:
357
+ """Iterate over all the buffers in the module."""
358
+ yield from self.module.named_buffers(remove_duplicate=remove_duplicate)
359
+
360
+ def named_tensors(
361
+ self,
362
+ remove_duplicate: bool = True,
363
+ ) -> Iterable[tuple[str, torch.Tensor]]:
364
+ """Iterate over all the tensors in the module."""
365
+ yield from self.module.named_parameters(remove_duplicate=remove_duplicate)
366
+ yield from self.module.named_buffers(remove_duplicate=remove_duplicate)
367
+
368
+ def named_modules(
369
+ self,
370
+ remove_duplicate: bool = True,
371
+ ) -> Iterable[tuple[str, "torch.nn.Module"]]:
372
+ """Iterate over all the modules in the module."""
373
+ yield from self.module.named_modules(remove_duplicate=remove_duplicate)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/_per_sample_grad.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+
4
+ import torch
5
+ from torch.nn.utils._expanded_weights.expanded_weights_impl import ExpandedWeight
6
+ from torch.utils import _pytree as pytree
7
+
8
+
9
+ # dependency on `functional_call` means that this can't be exposed in utils
10
+ # without creating circular dependency
11
+ def call_for_per_sample_grads(
12
+ module,
13
+ *,
14
+ batch_size=None,
15
+ loss_reduction="sum",
16
+ batch_first=True,
17
+ ):
18
+ r"""
19
+ Return a forward function for a module, populating grad_sample with per sample gradients on backward invocation.
20
+
21
+ Args:
22
+ module: The ``nn.Module`` to get per sample gradients with respect to. All trainable
23
+ parameters will compute per sample gradients, located in a ``grad_sample``
24
+ field when ``backward`` is invoked
25
+ batch_size: The batch size of the input. If None is passed, all tensor arguments in args and kwargs must have
26
+ the same batch size, which is the size of the first dimension. Otherwise, it must be passed manually.
27
+ Default: None
28
+ loss_reduction: Indicates if the loss reduction (for aggregating the gradients) is a sum or a mean operation. If
29
+ "mean", per sample gradients will be scaled by the batch size to offset the crossbatch interaction from
30
+ running mean across a batch. Must be "mean" or "sum". Default: "sum"
31
+ batch_first: Indicates if the batch dimension is the first dimension. If True, the batch dimension is the first
32
+ dimension. If False, it's the second dimension. Default: True.
33
+
34
+ Examples::
35
+ >>> # xdoctest: +SKIP
36
+ >>> model = nn.Linear(4, 3)
37
+ >>> batched_input = torch.randn(5, 4) # batch size of 5
38
+ >>> res = call_for_per_sample_grads(model)(batched_input).sum()
39
+ >>> res.backward()
40
+ >>> assert model.weight.shape == (3, 4)
41
+ >>> assert model.weight.grad_sample.shape == (5, 3, 4)
42
+ >>> assert model.weight.grad is None
43
+ >>> assert model.bias.shape == (3,)
44
+ >>> assert model.bias.grad_sample.shape == (5, 3)
45
+ >>> assert model.bias.grad is None
46
+
47
+ An example using "mean" loss reduction. The grad_sample fields will be scaled by batch_size from what they would be
48
+ if we ran the same code with loss_reduction="sum". This is because the mean at the end will scale all
49
+ grad_outputs by 1 / batch_size from cross batch interaction.
50
+ >>> model = nn.Linear(4, 3)
51
+ >>> batched_input = torch.randn(5, 4) # batch size of 5
52
+ >>> res = call_for_per_sample_grads(model, 5, loss_reduction="mean")(
53
+ ... batched_input
54
+ ... ).mean()
55
+ >>> res.backward()
56
+
57
+ Note::
58
+ Does not work with any `nn.RNN`, including `nn.GRU` or `nn.LSTM`. Please use custom
59
+ rewrites that wrap an `nn.Linear` module. See Opacus for an example
60
+ """
61
+
62
+ def maybe_build_expanded_weight(og_tensor, batch_size):
63
+ if og_tensor.requires_grad:
64
+ return ExpandedWeight(og_tensor, batch_size, loss_reduction)
65
+ else:
66
+ return og_tensor
67
+
68
+ def compute_batch_size(*args, **kwargs):
69
+ args_and_kwargs = pytree.arg_tree_leaves(*args, **kwargs)
70
+ batch_size = None
71
+ for arg in args_and_kwargs:
72
+ if not isinstance(arg, torch.Tensor):
73
+ continue
74
+
75
+ arg_batch_size = arg.shape[0] if batch_first else arg.shape[1]
76
+ if batch_size is not None and batch_size != arg_batch_size:
77
+ raise RuntimeError(
78
+ "When computing batch size, found at least one input with batch size "
79
+ f"{batch_size} and one with batch size {arg_batch_size}. Please specify it "
80
+ "explicitly using the batch size kwarg in call_for_per_sample_grads"
81
+ )
82
+ batch_size = arg_batch_size
83
+ if batch_size is None:
84
+ raise RuntimeError(
85
+ "Unable to find a tensor in the passed args and kwargs. They may not be pytree-able "
86
+ "and so ExpandedWeights cannot compute the batch size from the inputs. Please specify "
87
+ "it explicitly"
88
+ )
89
+ return batch_size
90
+
91
+ if loss_reduction not in ["sum", "mean"]:
92
+ raise RuntimeError(
93
+ f"Expected loss_reduction argument to be sum or mean, got {loss_reduction}"
94
+ )
95
+
96
+ if not isinstance(module, torch.nn.Module):
97
+ raise RuntimeError(
98
+ f"Module passed must be nn.Module, got {type(module).__name__}"
99
+ )
100
+ if not (batch_size is None or isinstance(batch_size, int)):
101
+ raise RuntimeError(
102
+ f"Batch size passed must be None or an integer, got {type(batch_size).__name__}"
103
+ )
104
+ if batch_size is not None and batch_size < 1:
105
+ raise RuntimeError(f"Batch size must be positive, got {batch_size}")
106
+ for weight in module.parameters():
107
+ if hasattr(weight, "grad_sample") and weight.grad_sample is not None: # type: ignore[attr-defined]
108
+ raise RuntimeError(
109
+ "Current Expanded Weights accumulates the gradients, which will be incorrect for multiple "
110
+ f"calls without clearing gradients. Please clear out the grad_sample parameter of {weight} or "
111
+ "post an issue to pytorch/pytorch to prioritize correct behavior"
112
+ )
113
+
114
+ @functools.wraps(module.forward)
115
+ def wrapper(*args, **kwargs):
116
+ wrapper_batch_size = batch_size
117
+ if wrapper_batch_size is None:
118
+ wrapper_batch_size = compute_batch_size(*args, **kwargs)
119
+
120
+ params = {
121
+ name: maybe_build_expanded_weight(value, wrapper_batch_size)
122
+ for (name, value) in module.named_parameters()
123
+ }
124
+ return torch.func.functional_call(module, params, args, kwargs)
125
+
126
+ return wrapper
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/clip_grad.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import functools
4
+ import types
5
+ import typing
6
+ import warnings
7
+ from collections.abc import Callable
8
+ from typing import cast, TypeAlias, TypeVar
9
+ from typing_extensions import deprecated, ParamSpec
10
+
11
+ import torch
12
+ from torch import Tensor
13
+ from torch.utils._foreach_utils import (
14
+ _device_has_foreach_support,
15
+ _group_tensors_by_device_and_dtype,
16
+ _has_foreach_support,
17
+ )
18
+
19
+
20
+ __all__: list[str] = [
21
+ "clip_grad_norm",
22
+ "clip_grad_norm_",
23
+ "clip_grad_value_",
24
+ ]
25
+
26
+
27
+ _tensor_or_tensors: TypeAlias = torch.Tensor | typing.Iterable[torch.Tensor] # noqa: PYI042
28
+
29
+ _P = ParamSpec("_P")
30
+ _R = TypeVar("_R")
31
+
32
+
33
+ def _no_grad(func: Callable[_P, _R]) -> Callable[_P, _R]:
34
+ """
35
+ This wrapper is needed to avoid a circular import when using @torch.no_grad on the exposed functions
36
+ clip_grad_norm_ and clip_grad_value_ themselves.
37
+ """
38
+
39
+ def _no_grad_wrapper(*args, **kwargs):
40
+ with torch.no_grad():
41
+ # pyrefly: ignore [invalid-param-spec]
42
+ return func(*args, **kwargs)
43
+
44
+ functools.update_wrapper(_no_grad_wrapper, func)
45
+ # pyrefly: ignore [bad-return]
46
+ return _no_grad_wrapper
47
+
48
+
49
+ @_no_grad
50
+ def _get_total_norm(
51
+ tensors: _tensor_or_tensors,
52
+ norm_type: float = 2.0,
53
+ error_if_nonfinite: bool = False,
54
+ foreach: bool | None = None,
55
+ ) -> torch.Tensor:
56
+ r"""Compute the norm of an iterable of tensors.
57
+
58
+ The norm is computed over the norms of the individual tensors, as if the norms of
59
+ the individual tensors were concatenated into a single vector.
60
+
61
+ Args:
62
+ tensors (Iterable[Tensor] or Tensor): an iterable of Tensors or a
63
+ single Tensor that will be normalized
64
+ norm_type (float): type of the used p-norm. Can be ``'inf'`` for
65
+ infinity norm.
66
+ error_if_nonfinite (bool): if True, an error is thrown if the total
67
+ norm of :attr:`tensors` is ``nan``, ``inf``, or ``-inf``.
68
+ Default: ``False``
69
+ foreach (bool): use the faster foreach-based implementation.
70
+ If ``None``, use the foreach implementation for CUDA and CPU native tensors and silently
71
+ fall back to the slow implementation for other device types.
72
+ Default: ``None``
73
+
74
+ Returns:
75
+ Total norm of the tensors (viewed as a single vector).
76
+ """
77
+ if isinstance(tensors, torch.Tensor):
78
+ tensors = [tensors]
79
+ else:
80
+ tensors = list(tensors)
81
+ norm_type = float(norm_type)
82
+ if len(tensors) == 0:
83
+ return torch.tensor(0.0)
84
+ first_device = tensors[0].device
85
+ grouped_tensors: dict[
86
+ tuple[torch.device, torch.dtype], tuple[list[list[Tensor]], list[int]]
87
+ ] = _group_tensors_by_device_and_dtype(
88
+ [tensors] # type: ignore[list-item]
89
+ ) # type: ignore[assignment]
90
+
91
+ norms: list[Tensor] = []
92
+ for (device, _), ([device_tensors], _) in grouped_tensors.items():
93
+ if (foreach is None and _has_foreach_support(device_tensors, device)) or (
94
+ foreach and _device_has_foreach_support(device)
95
+ ):
96
+ norms.extend(torch._foreach_norm(device_tensors, norm_type))
97
+ elif foreach:
98
+ raise RuntimeError(
99
+ f"foreach=True was passed, but can't use the foreach API on {device.type} tensors"
100
+ )
101
+ else:
102
+ norms.extend(
103
+ [torch.linalg.vector_norm(g, norm_type) for g in device_tensors]
104
+ )
105
+
106
+ total_norm = torch.linalg.vector_norm(
107
+ torch.stack([norm.to(first_device) for norm in norms]), norm_type
108
+ )
109
+
110
+ if error_if_nonfinite and torch.logical_or(total_norm.isnan(), total_norm.isinf()):
111
+ raise RuntimeError(
112
+ f"The total norm of order {norm_type} for gradients from "
113
+ "`parameters` is non-finite, so it cannot be clipped. To disable "
114
+ "this error and scale the gradients by the non-finite norm anyway, "
115
+ "set `error_if_nonfinite=False`"
116
+ )
117
+ return total_norm
118
+
119
+
120
+ @_no_grad
121
+ def _clip_grads_with_norm_(
122
+ parameters: _tensor_or_tensors,
123
+ max_norm: float,
124
+ total_norm: torch.Tensor,
125
+ foreach: bool | None = None,
126
+ ) -> None:
127
+ r"""Scale the gradients of an iterable of parameters given a pre-calculated total norm and desired max norm.
128
+
129
+ The gradients will be scaled by the following calculation
130
+
131
+ .. math::
132
+ grad = grad * \min(\frac{max\_norm}{total\_norm + 1e-6}, 1)
133
+
134
+ Gradients are modified in-place.
135
+
136
+ Note: The scale coefficient is clamped to a maximum of 1.0 to prevent gradient amplification.
137
+ This ensures that gradients are only scaled down when the total norm exceeds max_norm.
138
+
139
+ This function is equivalent to :func:`torch.nn.utils.clip_grad_norm_` with a pre-calculated
140
+ total norm.
141
+
142
+ Args:
143
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
144
+ single Tensor that will have gradients normalized
145
+ max_norm (float): max norm of the gradients
146
+ total_norm (Tensor): total norm of the gradients to use for clipping
147
+ foreach (bool): use the faster foreach-based implementation.
148
+ If ``None``, use the foreach implementation for CUDA and CPU native tensors and silently
149
+ fall back to the slow implementation for other device types.
150
+ Default: ``None``
151
+
152
+ Returns:
153
+ None
154
+ """
155
+ if isinstance(parameters, torch.Tensor):
156
+ parameters = [parameters]
157
+ grads = [p.grad for p in parameters if p.grad is not None]
158
+ max_norm = float(max_norm)
159
+ if len(grads) == 0:
160
+ return
161
+ grouped_grads: dict[
162
+ tuple[torch.device, torch.dtype], tuple[list[list[Tensor]], list[int]]
163
+ ] = _group_tensors_by_device_and_dtype([grads]) # type: ignore[assignment]
164
+
165
+ clip_coef = max_norm / (total_norm + 1e-6)
166
+ # Note: multiplying by the clamped coef is redundant when the coef is clamped to 1, but doing so
167
+ # avoids a `if clip_coef < 1:` conditional which can require a CPU <=> device synchronization
168
+ # when the gradients do not reside in CPU memory.
169
+ clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
170
+ for (device, _), ([device_grads], _) in grouped_grads.items():
171
+ if (foreach is None and _has_foreach_support(device_grads, device)) or (
172
+ foreach and _device_has_foreach_support(device)
173
+ ):
174
+ torch._foreach_mul_(device_grads, clip_coef_clamped.to(device))
175
+ elif foreach:
176
+ raise RuntimeError(
177
+ f"foreach=True was passed, but can't use the foreach API on {device.type} tensors"
178
+ )
179
+ else:
180
+ clip_coef_clamped_device = clip_coef_clamped.to(device)
181
+ for g in device_grads:
182
+ g.mul_(clip_coef_clamped_device)
183
+
184
+
185
+ @_no_grad
186
+ def clip_grad_norm_(
187
+ parameters: _tensor_or_tensors,
188
+ max_norm: float,
189
+ norm_type: float = 2.0,
190
+ error_if_nonfinite: bool = False,
191
+ foreach: bool | None = None,
192
+ ) -> torch.Tensor:
193
+ r"""Clip the gradient norm of an iterable of parameters.
194
+
195
+ The norm is computed over the norms of the individual gradients of all parameters,
196
+ as if the norms of the individual gradients were concatenated into a single vector.
197
+ Gradients are modified in-place.
198
+
199
+ This function is equivalent to :func:`torch.nn.utils.get_total_norm` followed by
200
+ :func:`torch.nn.utils.clip_grads_with_norm_` with the ``total_norm`` returned by ``get_total_norm``.
201
+
202
+ Args:
203
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
204
+ single Tensor that will have gradients normalized
205
+ max_norm (float): max norm of the gradients
206
+ norm_type (float, optional): type of the used p-norm. Can be ``'inf'`` for
207
+ infinity norm. Default: 2.0
208
+ error_if_nonfinite (bool, optional): if True, an error is thrown if the total
209
+ norm of the gradients from :attr:`parameters` is ``nan``,
210
+ ``inf``, or ``-inf``. Default: False
211
+ foreach (bool, optional): use the faster foreach-based implementation.
212
+ If ``None``, use the foreach implementation for CUDA and CPU native tensors and silently
213
+ fall back to the slow implementation for other device types.
214
+ Default: ``None``
215
+
216
+ Returns:
217
+ Total norm of the parameter gradients (viewed as a single vector).
218
+ """
219
+ if isinstance(parameters, torch.Tensor):
220
+ parameters = [parameters]
221
+ else:
222
+ is_generator = isinstance(parameters, types.GeneratorType)
223
+ # prevent generators from being exhausted
224
+ parameters = list(parameters)
225
+ if is_generator and len(parameters) == 0:
226
+ warnings.warn(
227
+ "`parameters` is an empty generator, no gradient clipping will occur.",
228
+ stacklevel=3,
229
+ )
230
+ grads = [p.grad for p in parameters if p.grad is not None]
231
+ total_norm = _get_total_norm(grads, norm_type, error_if_nonfinite, foreach)
232
+ _clip_grads_with_norm_(parameters, max_norm, total_norm, foreach)
233
+ return total_norm
234
+
235
+
236
+ @deprecated(
237
+ "`torch.nn.utils.clip_grad_norm` is now deprecated "
238
+ "in favor of `torch.nn.utils.clip_grad_norm_`.",
239
+ category=FutureWarning,
240
+ )
241
+ def clip_grad_norm(
242
+ parameters: _tensor_or_tensors,
243
+ max_norm: float,
244
+ norm_type: float = 2.0,
245
+ error_if_nonfinite: bool = False,
246
+ foreach: bool | None = None,
247
+ ) -> torch.Tensor:
248
+ r"""Clip the gradient norm of an iterable of parameters.
249
+
250
+ .. warning::
251
+ This method is now deprecated in favor of
252
+ :func:`torch.nn.utils.clip_grad_norm_`.
253
+ """
254
+ return clip_grad_norm_(parameters, max_norm, norm_type, error_if_nonfinite, foreach)
255
+
256
+
257
+ @_no_grad
258
+ def clip_grad_value_(
259
+ parameters: _tensor_or_tensors,
260
+ clip_value: float,
261
+ foreach: bool | None = None,
262
+ ) -> None:
263
+ r"""Clip the gradients of an iterable of parameters at specified value.
264
+
265
+ Gradients are modified in-place.
266
+
267
+ Args:
268
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
269
+ single Tensor that will have gradients normalized
270
+ clip_value (float): maximum allowed value of the gradients.
271
+ The gradients are clipped in the range
272
+ :math:`\left[\text{-clip\_value}, \text{clip\_value}\right]`
273
+ foreach (bool, optional): use the faster foreach-based implementation
274
+ If ``None``, use the foreach implementation for CUDA and CPU native tensors and
275
+ silently fall back to the slow implementation for other device types.
276
+ Default: ``None``
277
+ """
278
+ if isinstance(parameters, torch.Tensor):
279
+ parameters = [parameters]
280
+ clip_value = float(clip_value)
281
+
282
+ grads = [p.grad for p in parameters if p.grad is not None]
283
+ # pyrefly: ignore [bad-argument-type]
284
+ grouped_grads = _group_tensors_by_device_and_dtype([grads])
285
+
286
+ for (device, _), ([grads], _) in grouped_grads.items():
287
+ if (
288
+ foreach is None
289
+ and _has_foreach_support(cast(list[Tensor], grads), device=device)
290
+ ) or (foreach and _device_has_foreach_support(device)):
291
+ torch._foreach_clamp_min_(cast(list[Tensor], grads), -clip_value)
292
+ torch._foreach_clamp_max_(cast(list[Tensor], grads), clip_value)
293
+ elif foreach:
294
+ raise RuntimeError(
295
+ f"foreach=True was passed, but can't use the foreach API on {device.type} tensors"
296
+ )
297
+ else:
298
+ for grad in grads:
299
+ cast(Tensor, grad).clamp_(min=-clip_value, max=clip_value)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/convert_parameters.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+
3
+ import torch
4
+
5
+
6
+ def parameters_to_vector(parameters: Iterable[torch.Tensor]) -> torch.Tensor:
7
+ r"""Flatten an iterable of parameters into a single vector.
8
+
9
+ Args:
10
+ parameters (Iterable[Tensor]): an iterable of Tensors that are the
11
+ parameters of a model.
12
+
13
+ Returns:
14
+ The parameters represented by a single vector
15
+ """
16
+ # Flag for the device where the parameter is located
17
+ param_device = None
18
+
19
+ vec = []
20
+ for param in parameters:
21
+ # Ensure the parameters are located in the same device
22
+ param_device = _check_param_device(param, param_device)
23
+
24
+ vec.append(param.view(-1))
25
+ return torch.cat(vec)
26
+
27
+
28
+ def vector_to_parameters(vec: torch.Tensor, parameters: Iterable[torch.Tensor]) -> None:
29
+ r"""Copy slices of a vector into an iterable of parameters.
30
+
31
+ Args:
32
+ vec (Tensor): a single vector representing the parameters of a model.
33
+ parameters (Iterable[Tensor]): an iterable of Tensors that are the
34
+ parameters of a model.
35
+ """
36
+ # Ensure vec of type Tensor
37
+ if not isinstance(vec, torch.Tensor):
38
+ raise TypeError(f"expected torch.Tensor, but got: {torch.typename(vec)}")
39
+ # Flag for the device where the parameter is located
40
+ param_device = None
41
+
42
+ # Pointer for slicing the vector for each parameter
43
+ pointer = 0
44
+ for param in parameters:
45
+ # Ensure the parameters are located in the same device
46
+ param_device = _check_param_device(param, param_device)
47
+
48
+ # The length of the parameter
49
+ num_param = param.numel()
50
+ # Slice the vector, reshape it, and replace the old data of the parameter
51
+ param.data = vec[pointer : pointer + num_param].view_as(param).data
52
+
53
+ # Increment the pointer
54
+ pointer += num_param
55
+
56
+
57
+ def _check_param_device(param: torch.Tensor, old_param_device: int | None) -> int:
58
+ r"""Check if the parameters are located on the same device.
59
+
60
+ Currently, the conversion between model parameters and single vector form is not supported
61
+ for multiple allocations, e.g. parameters in different GPUs/PrivateUse1s, or mixture of CPU/GPU/PrivateUse1.
62
+
63
+ Args:
64
+ param ([Tensor]): a Tensor of a parameter of a model
65
+ old_param_device (int): the device where the first parameter of a
66
+ model is allocated.
67
+
68
+ Returns:
69
+ old_param_device (int): report device for the first time
70
+ """
71
+ # Meet the first parameter
72
+ support_device_types = ["cuda", torch._C._get_privateuse1_backend_name()]
73
+ if old_param_device is None:
74
+ old_param_device = (
75
+ param.get_device() if param.device.type in support_device_types else -1
76
+ )
77
+ else:
78
+ warn = False
79
+ if (
80
+ param.device.type in support_device_types
81
+ ): # Check if in same GPU/PrivateUse1
82
+ warn = param.get_device() != old_param_device
83
+ else: # Check if in CPU
84
+ warn = old_param_device != -1
85
+ if warn:
86
+ raise TypeError(
87
+ "Found two parameters on different devices, "
88
+ "this is currently not supported."
89
+ )
90
+ return old_param_device
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/fusion.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ from typing import TypeVar
5
+
6
+ import torch
7
+
8
+
9
+ __all__ = [
10
+ "fuse_conv_bn_eval",
11
+ "fuse_conv_bn_weights",
12
+ "fuse_linear_bn_eval",
13
+ "fuse_linear_bn_weights",
14
+ ]
15
+
16
+ ConvT = TypeVar("ConvT", bound="torch.nn.modules.conv._ConvNd")
17
+ LinearT = TypeVar("LinearT", bound="torch.nn.Linear")
18
+
19
+
20
+ def fuse_conv_bn_eval(
21
+ conv: ConvT,
22
+ bn: torch.nn.modules.batchnorm._BatchNorm,
23
+ transpose: bool = False,
24
+ ) -> ConvT:
25
+ r"""Fuse a convolutional module and a BatchNorm module into a single, new convolutional module.
26
+
27
+ Args:
28
+ conv (torch.nn.modules.conv._ConvNd): A convolutional module.
29
+ bn (torch.nn.modules.batchnorm._BatchNorm): A BatchNorm module.
30
+ transpose (bool, optional): If True, transpose the convolutional weight. Defaults to False.
31
+
32
+ Returns:
33
+ torch.nn.modules.conv._ConvNd: The fused convolutional module.
34
+
35
+ .. note::
36
+ Both ``conv`` and ``bn`` must be in eval mode, and ``bn`` must have its running buffers computed.
37
+ """
38
+ assert not (conv.training or bn.training), "Fusion only for eval!"
39
+ fused_conv = copy.deepcopy(conv)
40
+
41
+ assert bn.running_mean is not None and bn.running_var is not None
42
+ fused_conv.weight, fused_conv.bias = fuse_conv_bn_weights(
43
+ fused_conv.weight,
44
+ fused_conv.bias,
45
+ bn.running_mean,
46
+ bn.running_var,
47
+ bn.eps,
48
+ bn.weight,
49
+ bn.bias,
50
+ transpose,
51
+ )
52
+
53
+ return fused_conv
54
+
55
+
56
+ def fuse_conv_bn_weights(
57
+ conv_w: torch.Tensor,
58
+ conv_b: torch.Tensor | None,
59
+ bn_rm: torch.Tensor,
60
+ bn_rv: torch.Tensor,
61
+ bn_eps: float,
62
+ bn_w: torch.Tensor | None,
63
+ bn_b: torch.Tensor | None,
64
+ transpose: bool = False,
65
+ ) -> tuple[torch.nn.Parameter, torch.nn.Parameter]:
66
+ r"""Fuse convolutional module parameters and BatchNorm module parameters into new convolutional module parameters.
67
+
68
+ Args:
69
+ conv_w (torch.Tensor): Convolutional weight.
70
+ conv_b (Optional[torch.Tensor]): Convolutional bias.
71
+ bn_rm (torch.Tensor): BatchNorm running mean.
72
+ bn_rv (torch.Tensor): BatchNorm running variance.
73
+ bn_eps (float): BatchNorm epsilon.
74
+ bn_w (Optional[torch.Tensor]): BatchNorm weight.
75
+ bn_b (Optional[torch.Tensor]): BatchNorm bias.
76
+ transpose (bool, optional): If True, transpose the conv weight. Defaults to False.
77
+
78
+ Returns:
79
+ Tuple[torch.nn.Parameter, torch.nn.Parameter]: Fused convolutional weight and bias.
80
+ """
81
+ conv_weight_dtype = conv_w.dtype
82
+ conv_bias_dtype = conv_b.dtype if conv_b is not None else conv_weight_dtype
83
+ if conv_b is None:
84
+ conv_b = torch.zeros_like(bn_rm)
85
+ if bn_w is None:
86
+ bn_w = torch.ones_like(bn_rm)
87
+ if bn_b is None:
88
+ bn_b = torch.zeros_like(bn_rm)
89
+ bn_var_rsqrt = torch.rsqrt(bn_rv + bn_eps)
90
+
91
+ if transpose:
92
+ shape = [1, -1] + [1] * (len(conv_w.shape) - 2)
93
+ else:
94
+ shape = [-1, 1] + [1] * (len(conv_w.shape) - 2)
95
+
96
+ fused_conv_w = (conv_w * (bn_w * bn_var_rsqrt).reshape(shape)).to(
97
+ dtype=conv_weight_dtype
98
+ )
99
+ fused_conv_b = ((conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b).to(
100
+ dtype=conv_bias_dtype
101
+ )
102
+
103
+ return (
104
+ torch.nn.Parameter(fused_conv_w, conv_w.requires_grad),
105
+ torch.nn.Parameter(fused_conv_b, conv_b.requires_grad),
106
+ )
107
+
108
+
109
+ def fuse_linear_bn_eval(
110
+ linear: LinearT,
111
+ bn: torch.nn.modules.batchnorm._BatchNorm,
112
+ ) -> LinearT:
113
+ r"""Fuse a linear module and a BatchNorm module into a single, new linear module.
114
+
115
+ Args:
116
+ linear (torch.nn.Linear): A Linear module.
117
+ bn (torch.nn.modules.batchnorm._BatchNorm): A BatchNorm module.
118
+
119
+ Returns:
120
+ torch.nn.Linear: The fused linear module.
121
+
122
+ .. note::
123
+ Both ``linear`` and ``bn`` must be in eval mode, and ``bn`` must have its running buffers computed.
124
+ """
125
+ assert not (linear.training or bn.training), "Fusion only for eval!"
126
+ fused_linear = copy.deepcopy(linear)
127
+
128
+ """
129
+ Linear-BN needs to be fused while preserving the shapes of linear weight/bias.
130
+ To preserve the shapes of linear weight/bias, the channel dim of bn needs to be broadcastable with the last dim of linear,
131
+ because bn operates over the channel dim, (N, C_in, H, W) while linear operates over the last dim, (*, H_in).
132
+ To be broadcastable, the number of features in bn and
133
+ the number of output features from linear must satisfy the following condition:
134
+ 1. they are equal, or
135
+ 2. the number of features in bn is 1
136
+ Otherwise, skip the folding path
137
+ """
138
+ assert linear.out_features == bn.num_features or bn.num_features == 1, (
139
+ "To fuse, linear.out_features == bn.num_features or bn.num_features == 1"
140
+ )
141
+
142
+ assert bn.running_mean is not None and bn.running_var is not None
143
+ fused_linear.weight, fused_linear.bias = fuse_linear_bn_weights(
144
+ fused_linear.weight,
145
+ fused_linear.bias,
146
+ bn.running_mean,
147
+ bn.running_var,
148
+ bn.eps,
149
+ bn.weight,
150
+ bn.bias,
151
+ )
152
+
153
+ return fused_linear
154
+
155
+
156
+ def fuse_linear_bn_weights(
157
+ linear_w: torch.Tensor,
158
+ linear_b: torch.Tensor | None,
159
+ bn_rm: torch.Tensor,
160
+ bn_rv: torch.Tensor,
161
+ bn_eps: float,
162
+ bn_w: torch.Tensor,
163
+ bn_b: torch.Tensor,
164
+ ) -> tuple[torch.nn.Parameter, torch.nn.Parameter]:
165
+ r"""Fuse linear module parameters and BatchNorm module parameters into new linear module parameters.
166
+
167
+ Args:
168
+ linear_w (torch.Tensor): Linear weight.
169
+ linear_b (Optional[torch.Tensor]): Linear bias.
170
+ bn_rm (torch.Tensor): BatchNorm running mean.
171
+ bn_rv (torch.Tensor): BatchNorm running variance.
172
+ bn_eps (float): BatchNorm epsilon.
173
+ bn_w (torch.Tensor): BatchNorm weight.
174
+ bn_b (torch.Tensor): BatchNorm bias.
175
+
176
+ Returns:
177
+ Tuple[torch.nn.Parameter, torch.nn.Parameter]: Fused linear weight and bias.
178
+ """
179
+ linear_weight_dtype = linear_w.dtype
180
+ linear_bias_dtype = linear_b.dtype if linear_b is not None else linear_weight_dtype
181
+ if linear_b is None:
182
+ linear_b = torch.zeros_like(bn_rm)
183
+ bn_scale = bn_w * torch.rsqrt(bn_rv + bn_eps)
184
+
185
+ fused_w = linear_w * bn_scale.unsqueeze(-1).to(dtype=linear_weight_dtype)
186
+ fused_b = ((linear_b - bn_rm) * bn_scale + bn_b).to(dtype=linear_bias_dtype)
187
+
188
+ return torch.nn.Parameter(fused_w, linear_w.requires_grad), torch.nn.Parameter(
189
+ fused_b, linear_b.requires_grad
190
+ )
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/init.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+
4
+ import torch
5
+
6
+
7
+ def skip_init(module_cls, *args, **kwargs):
8
+ r"""
9
+ Given a module class object and args / kwargs, instantiate the module without initializing parameters / buffers.
10
+
11
+ This can be useful if initialization is slow or if custom initialization will
12
+ be performed, making the default initialization unnecessary. There are some caveats to this, due to
13
+ the way this function is implemented:
14
+
15
+ 1. The module must accept a `device` arg in its constructor that is passed to any parameters
16
+ or buffers created during construction.
17
+
18
+ 2. The module must not perform any computation on parameters in its constructor except
19
+ initialization (i.e. functions from :mod:`torch.nn.init`).
20
+
21
+ If these conditions are satisfied, the module can be instantiated with parameter / buffer values
22
+ uninitialized, as if having been created using :func:`torch.empty`.
23
+
24
+ Args:
25
+ module_cls: Class object; should be a subclass of :class:`torch.nn.Module`
26
+ args: args to pass to the module's constructor
27
+ kwargs: kwargs to pass to the module's constructor
28
+
29
+ Returns:
30
+ Instantiated module with uninitialized parameters / buffers
31
+
32
+ Example::
33
+
34
+ >>> # xdoctest: +IGNORE_WANT("non-deterministic")
35
+ >>> import torch
36
+ >>> m = torch.nn.utils.skip_init(torch.nn.Linear, 5, 1)
37
+ >>> m.weight
38
+ Parameter containing:
39
+ tensor([[0.0000e+00, 1.5846e+29, 7.8307e+00, 2.5250e-29, 1.1210e-44]],
40
+ requires_grad=True)
41
+ >>> m2 = torch.nn.utils.skip_init(torch.nn.Linear, in_features=6, out_features=1)
42
+ >>> m2.weight
43
+ Parameter containing:
44
+ tensor([[-1.4677e+24, 4.5915e-41, 1.4013e-45, 0.0000e+00, -1.4677e+24,
45
+ 4.5915e-41]], requires_grad=True)
46
+
47
+ """
48
+ if not issubclass(module_cls, torch.nn.Module):
49
+ raise RuntimeError(f"Expected a Module; got {module_cls}")
50
+ if "device" not in inspect.signature(module_cls).parameters:
51
+ raise RuntimeError("Module must support a 'device' arg to skip initialization")
52
+
53
+ final_device = kwargs.pop("device", "cpu")
54
+ kwargs["device"] = "meta"
55
+ return module_cls(*args, **kwargs).to_empty(device=final_device)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/nn/utils/memory_format.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TypeVar
4
+
5
+ import torch
6
+
7
+
8
+ _M = TypeVar("_M", bound="torch.nn.Module")
9
+
10
+
11
+ def convert_conv2d_weight_memory_format(
12
+ module: _M, memory_format: torch.memory_format
13
+ ) -> _M:
14
+ r"""Convert ``memory_format`` of ``nn.Conv2d.weight`` to ``memory_format``.
15
+
16
+ The conversion recursively applies to nested ``nn.Module``, including ``module``.
17
+ Note that it only changes the memory_format, but not the semantics of each dimensions.
18
+ This function is used to facilitate the computation to adopt NHWC kernels, which
19
+ provides considerable speed up for fp16 data on CUDA devices with compute capability >= 7.0
20
+
21
+ .. note::
22
+ Calling ``model.to(memory_format=torch.channels_last)`` is more aggressive
23
+ than the utility function ``convert_conv2d_weight_memory_format``. Any
24
+ layer with 4d weight will be affected by ``model.to``, which does not
25
+ necessarily benefit from conversion to specified ``memory_format``.
26
+ One place we are confident in is that NHWC(channels_last) conversion for
27
+ convolution in cuDNN, as it is beneficial to run convolution in NHWC,
28
+ even in cases where we have to apply permutation to input tensors.
29
+
30
+ Hence our strategy here is to convert only the weight of convolution to
31
+ channels_last. This ensures that;
32
+ 1. Fast convolution kernels will be used, the benefit of which could
33
+ outweigh overhead of permutation (if input is not in the same format).
34
+ 2. No unnecessary permutations are applied on layers that do not benefit
35
+ from memory_format conversion.
36
+
37
+ The optimal case is that, layers between convolution layers are channels
38
+ last compatible. Input tensor would be permuted to channels last when it
39
+ encounters the first convolution layer and stay in that memory format.
40
+ Hence following convolutions will not need to permute its input tensor.
41
+
42
+ In case where a channels last incompatible layer is between convolution
43
+ layers, we need to permute the input tensor back to contiguous format
44
+ for that layer. The input tensor will go through the remaining layers in
45
+ contiguous format and be permuted to channels last when it encounters
46
+ another convolution layer. There's no point in propagating that
47
+ permutation to an earlier layer, as most layers are quite agnostic to
48
+ ``memory_format``.
49
+
50
+ This claim might change when PyTorch supports fusion of permutation, as
51
+ there might have been a better spot to fuse the permutation other than
52
+ immediately before a convolution.
53
+
54
+ Args:
55
+ module (nn.Module): ``nn.Conv2d`` & ``nn.ConvTranspose2d`` or container
56
+ ``nn.Module``
57
+ memory_format: user specified ``memory_format``,
58
+ e.g. ``torch.channels_last`` or ``torch.contiguous_format``
59
+
60
+ Returns:
61
+ The original module with updated ``nn.Conv2d``
62
+
63
+ Example:
64
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
65
+ >>> # xdoctest: +REQUIRES(env:CUBLAS_WORKSPACE_CONFIG)
66
+ >>> input = torch.randint(
67
+ ... 1, 10, (2, 8, 4, 4), dtype=torch.float16, device="cuda"
68
+ ... )
69
+ >>> model = nn.Sequential(
70
+ >>> nn.Conv2d(8, 4, 3)).cuda().half()
71
+ >>> # This is identical to:
72
+ >>> # nn.utils.convert_conv2d_weight_memory_format(model, torch.channels_last)
73
+ >>> model = nn.utils.convert_conv2d_weight_memory_format(
74
+ ... model, torch.channels_last
75
+ ... )
76
+ >>> out = model(input)
77
+ """
78
+ # TODO: expand this to `_ConvNd` when channels_last support is extended
79
+ # beyond only 4d tensors.
80
+ if isinstance(module, (torch.nn.Conv2d, torch.nn.ConvTranspose2d)):
81
+ weight_data = module.weight.detach().clone(memory_format=memory_format)
82
+ module.weight.data = weight_data.resize_(
83
+ weight_data.size(), memory_format=memory_format
84
+ )
85
+ for child in module.children():
86
+ convert_conv2d_weight_memory_format(child, memory_format)
87
+ # pyrefly: ignore [bad-return]
88
+ return module
89
+
90
+
91
+ def convert_conv3d_weight_memory_format(
92
+ module: _M, memory_format: torch.memory_format
93
+ ) -> _M:
94
+ r"""Convert ``memory_format`` of ``nn.Conv3d.weight`` to ``memory_format``
95
+ The conversion recursively applies to nested ``nn.Module``, including ``module``.
96
+ Note that it only changes the memory_format, but not the semantics of each dimensions.
97
+ This function is used to facilitate the computation to adopt NHWC kernels, which
98
+ provides considerable speed up for fp16 data on CUDA devices with compute capability >= 7.0
99
+
100
+ .. note::
101
+ Calling ``model.to(memory_format=torch.channels_last_3d)`` is more aggressive
102
+ than the utility function ``convert_conv3d_weight_memory_format``. Any
103
+ layer with 4d weight will be affected by ``model.to``, which does not
104
+ necessarily benefit from conversion to specified ``memory_format``.
105
+ One place we are confident in is that NDHWC(channels_last_3d) conversion for
106
+ convolution in cuDNN, as it is beneficial to run convolution in NDHWC,
107
+ even in cases where we have to apply permutation to input tensors.
108
+
109
+ Hence our strategy here is to convert only the weight of convolution to
110
+ channels_last_3d. This ensures that;
111
+ 1. Fast convolution kernels will be used, the benefit of which could
112
+ outweigh overhead of permutation (if input is not in the same format).
113
+ 2. No unnecessary permutations are applied on layers that do not benefit
114
+ from memory_format conversion.
115
+
116
+ The optimal case is that, layers between convolution layers are channels
117
+ last compatible. Input tensor would be permuted to channels last when it
118
+ encounters the first convolution layer and stay in that memory format.
119
+ Hence following convolutions will not need to permute its input tensor.
120
+
121
+ In case where a channels last incompatible layer is between convolution
122
+ layers, we need to permute the input tensor back to contiguous format
123
+ for that layer. The input tensor will go through the remaining layers in
124
+ contiguous format and be permuted to channels last when it encounters
125
+ another convolution layer. There's no point in propagating that
126
+ permutation to an earlier layer, as most layers are quite agnostic to
127
+ ``memory_format``.
128
+
129
+ This claim might change when PyTorch supports fusion of permutation, as
130
+ there might have been a better spot to fuse the permutation other than
131
+ immediately before a convolution.
132
+
133
+ Args:
134
+ module (nn.Module): ``nn.Conv3d`` & ``nn.ConvTranspose3d`` or container
135
+ ``nn.Module``
136
+ memory_format: user specified ``memory_format``,
137
+ e.g. ``torch.channels_last`` or ``torch.contiguous_format``
138
+
139
+ Returns:
140
+ The original module with updated ``nn.Conv3d``
141
+
142
+ Example:
143
+ >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
144
+ >>> # xdoctest: +REQUIRES(env:CUBLAS_WORKSPACE_CONFIG)
145
+ >>> input = torch.randint(
146
+ ... 1, 10, (2, 8, 4, 4, 4), dtype=torch.float16, device="cuda"
147
+ ... )
148
+ >>> model = nn.Sequential(
149
+ >>> nn.Conv3d(8, 4, 3)).cuda().half()
150
+ >>> # This is identical to:
151
+ >>> # nn.utils.convert_conv3d_weight_memory_format(model, torch.channels_last_3d)
152
+ >>> model = nn.utils.convert_conv3d_weight_memory_format(
153
+ ... model, torch.channels_last_3d
154
+ ... )
155
+ >>> out = model(input)
156
+ """
157
+
158
+ # TODO: expand this to `_ConvNd` when channels_last support is extended
159
+ # beyond only 4d tensors.
160
+ if isinstance(module, (torch.nn.Conv3d, torch.nn.ConvTranspose3d)):
161
+ weight_data = module.weight.detach().clone(memory_format=memory_format)
162
+ module.weight.data = weight_data.resize_(
163
+ weight_data.size(), memory_format=memory_format
164
+ )
165
+ for child in module.children():
166
+ convert_conv3d_weight_memory_format(child, memory_format)
167
+ # pyrefly: ignore [bad-return]
168
+ return module
169
+
170
+
171
+ __all__ = [
172
+ "convert_conv2d_weight_memory_format",
173
+ "convert_conv3d_weight_memory_format",
174
+ ]