184 Commits
Author SHA1 Message Date
Egemen TuncarslanandClaude Opus 5 33b24bf218 Check num_heads in F::multi_head_attention_forward (#195381)
Fixes #106700.

`torch::nn::functional::multi_head_attention_forward` divides before it validates:

```cpp
const auto head_dim = embed_dim / num_heads;
TORCH_CHECK(head_dim * num_heads == embed_dim, "embed_dim must be divisible by num_heads");
```

so `num_heads == 0` is an integer division by zero. That is not a catchable exception — the
process dies. Running the call in a subprocess on Windows exits with `0xC0000094`
(`STATUS_INTEGER_DIVIDE_BY_ZERO`) with no stdout, no stderr and no traceback; the original report
shows the same as SIGFPE on Linux.

### Half of this issue is already fixed — this is the other half

#186376 added `TORCH_CHECK(options.num_heads() > 0, ...)` to `MultiheadAttentionImpl::reset`
(`activation.cpp:504`) and landed as `e71ac681afa`. That closed the case in the issue *body*: the
module constructor. The reporter raised a second case in a follow-up comment — the functional
entry point — and it was never covered. This adds the same check with the same message,
immediately before the division.

@malfet approved the earlier #106778, which fixed both halves; it went stale on unrelated CI in
2023 and closed without landing.

### Test

`ModulesTest.MultiheadAttentionZeroNumHeads` covers both halves — the module constructor and the
functional call. #186376 already covered the constructor with `MultiheadAttentionRejectsZeroNumHeads`;
this adds the missing coverage for the functional entry point.

The crash cannot be caught in-process, so I verified through a `cpp_extension` harness run in a
subprocess. Against current headers:

```
stdout: (empty)
stderr: (empty)
exit code: 3221225620          # 0xC0000094, STATUS_INTEGER_DIVIDE_BY_ZERO
```

With this change, the same harness:

```
stdout: RAISED RuntimeError num_heads must be greater than 0
exit code: 0
```

`cl.exe /Zs test\cpp\api\modules.cpp` is clean against the build's flags; the gtest binary itself
is left to CI, as this machine cannot launch freshly linked executables.

Developed with AI assistance (Claude); I reproduced the crash, wrote the fix and ran the checks
above.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/195381
Approved by: https://github.com/drisspg

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 03:17:45 +00:00
PyTorch MergeBot 569f1f64e1 Revert "Add keepdim parameter to cosine_similarity (#189654)"
This reverts commit 805674d784.

Reverted https://github.com/pytorch/pytorch/pull/189654 on behalf of https://github.com/meta-codesync due to Diff reverted internally ([comment](https://github.com/pytorch/pytorch/pull/189654#issuecomment-5098656931))
2026-07-28 01:05:12 +00:00
Raj FirkeandalbanD via mergedog 805674d784 Add keepdim parameter to cosine_similarity (#189654)
Fixes #149120

Adds a `keepdim` parameter to `torch.cosine_similarity`, consistent with other reduction-like ops (`sum`, `norm`, `pairwise_distance`).

```python
>>> x1 = torch.randn(2, 3, 4)
>>> x2 = torch.randn(2, 3, 4)
>>> torch.cosine_similarity(x1, x2, dim=1).shape
torch.Size([2, 4])
>>> torch.cosine_similarity(x1, x2, dim=1, keepdim=True).shape
torch.Size([2, 1, 4])
```

**Changes:**
- `native_functions.yaml`: Add `bool keepdim=False` to `cosine_similarity` schema
- `Distance.cpp`: Pass `keepdim` to final `.sum(dim, keepdim)` call
- C++ API: Add `keepdim` to `CosineSimilarityOptions`, plumb through functional and module layers
- ONNX symbolic: Accept `keepdim` and pass to `keepdims_i` in reduce ops
- `torch/overrides.py`: Add `keepdim` to override lambda
- Tests: Add `keepdim=True` shape and value tests in Python (`test_nn.py`, OpInfo samples) and C++ (`modules.cpp`)

The default `keepdim=False` preserves full backward compatibility.

**Note:** Per the FC window policy, a follow-up PR will update the Python frontend (`F.cosine_similarity` docstring and `nn.CosineSimilarity` module) to expose `keepdim` after these C++ changes land.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/189654
Approved by: https://github.com/albanD

Co-authored-by: albanD via mergedog <desmaison.alban@gmail.com>
2026-07-19 19:40:47 +00:00
praful-srinivasan-027 e71ac681af Validate num_heads before division in MultiheadAttention (#186376)
# Fix: Division-by-Zero in `MultiheadAttentionImpl::reset()` When `num_heads == 0`

## Summary
Fixes #186237
Fixed a division-by-zero in `MultiheadAttentionImpl::reset()` triggered when `num_heads` is `0`.

Previously, `head_dim` was computed before any validation of `num_heads`:

```cpp
head_dim = options.embed_dim() / options.num_heads();
```

Constructing `MultiheadAttention` with `num_heads = 0` could invoke undefined behavior (integer division by zero / floating-point exception) before any validation logic was reached.

This PR adds a `TORCH_CHECK` to validate that `num_heads > 0` **before** performing the division, replacing the silent UB with a clear, actionable error message.

## Changes

- Added a `TORCH_CHECK(options.num_heads() > 0, ...)` guard in `MultiheadAttentionImpl::reset()` prior to the `head_dim` computation.

## Test Plan

Added a C++ API test verifying that constructing:

```cpp
MultiheadAttention(MultiheadAttentionOptions(0, 0))
```

throws a `c10::Error`.

**Before this change:** the test triggered a floating-point exception due to division by zero.

**After this change:** the test passes and the invalid configuration is reported via a proper error.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/186376
Approved by: https://github.com/drisspg
2026-06-12 17:29:37 +00:00
Joel Schlosser 00512145ec Remove named tensor (#173895)
BE project hard-removing the deprecated named tensor feature to remove overhead and code bloat. This was nearly all done by wrestling with Claude Code, so it needs some personal review and probably needs to be split into multiple PRs to help reviewers.

The process was me absent-mindedly doing this throughout the week while working on other stuff:
```
me: remove named tensor along with all associated APIs, tests, and docs from the codebase
claude: <does stuff>

while not built:
    me: <tries to build>
    if error:
        me: there are still remnants of named tensor (with build-error related example); remove all these
        claude: <does more stuff, usually very good at generalizing from the example>
```

This wasn't particularly efficient (it built after ~27 iterations) but didn't require much thought or time from my end. The only part Claude Code did NOT do is add a couple now-necessary `#include <ATen/WrapDimUtils.h>` statements.

It builds! Testing is still a WIP.

Having Claude Code break this into manageable PRs, the breakdown is:
```
1. Remove named tensor tests and documentation

  - test/test_namedtensor.py
  - test/compiled_autograd_skips/TestNamedTensor.*
  - test/dynamo_expected_failures/TestNamedTensor.*
  - docs/source/named_tensor.md
  - docs/source/name_inference.md
  - Test file updates (test_ops.py, test_overrides.py, test_builtins.py, test_torch.py, etc.)
  - functorch/op_analysis/annotated_ops
  - Expect file updates (HasDecompTest)
  - test/allowlist_for_publicAPI.json

  2. Remove named tensor operators from native_functions.yaml

  - All Dimname-based operator overloads
  - align_tensors, align_as, align_to, rename, refine_names
  - Factory function names variants (empty.names, zeros.names, etc.)

  3. Remove Python named tensor APIs

  - torch/_namedtensor_internals.py
  - torch/_tensor.py (names property, rename methods)
  - torch/functional.py (align_tensors)
  - torch/overrides.py references
  - torch/_dynamo/trace_rules.py references
  - torch/multiprocessing/reductions.py references

  4. Remove C++ named tensor infrastructure and build system

  - Dimname type system (Dimname.h/cpp, python_dimname.h/cpp, python_arg_parser changes)
  - Core infrastructure (NamedTensor.h/cpp, NamedTensorUtils.h/cpp, TensorNames.h/cpp)
  - TensorImpl changes (NamedTensorMetaInterface)
  - Structured kernels (names parameter from set_output_* and all call sites)
  - Guards (NoNamesGuard, NamesMode, guard.reset() calls)
  - Build system (CMakeLists.txt, build_variables.bzl, cmake/prioritized_text.txt)
  - Codegen (torchgen/, tools/autograd/ templates)
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/173895
Approved by: https://github.com/malfet, https://github.com/guangyey, https://github.com/cota
2026-06-04 18:06:46 +00:00
PyTorch MergeBot dd7dcb1ced Revert "Remove named tensor (#173895)"
This reverts commit 991d22dd38.

Reverted https://github.com/pytorch/pytorch/pull/173895 on behalf of https://github.com/jeanschmidt due to breaks internal signals, see D106831244 ([comment](https://github.com/pytorch/pytorch/pull/173895#issuecomment-4589252870))
2026-06-01 03:18:56 +00:00
Joel Schlosser 991d22dd38 Remove named tensor (#173895)
BE project hard-removing the deprecated named tensor feature to remove overhead and code bloat. This was nearly all done by wrestling with Claude Code, so it needs some personal review and probably needs to be split into multiple PRs to help reviewers.

The process was me absent-mindedly doing this throughout the week while working on other stuff:
```
me: remove named tensor along with all associated APIs, tests, and docs from the codebase
claude: <does stuff>

while not built:
    me: <tries to build>
    if error:
        me: there are still remnants of named tensor (with build-error related example); remove all these
        claude: <does more stuff, usually very good at generalizing from the example>
```

This wasn't particularly efficient (it built after ~27 iterations) but didn't require much thought or time from my end. The only part Claude Code did NOT do is add a couple now-necessary `#include <ATen/WrapDimUtils.h>` statements.

It builds! Testing is still a WIP.

Having Claude Code break this into manageable PRs, the breakdown is:
```
1. Remove named tensor tests and documentation

  - test/test_namedtensor.py
  - test/compiled_autograd_skips/TestNamedTensor.*
  - test/dynamo_expected_failures/TestNamedTensor.*
  - docs/source/named_tensor.md
  - docs/source/name_inference.md
  - Test file updates (test_ops.py, test_overrides.py, test_builtins.py, test_torch.py, etc.)
  - functorch/op_analysis/annotated_ops
  - Expect file updates (HasDecompTest)
  - test/allowlist_for_publicAPI.json

  2. Remove named tensor operators from native_functions.yaml

  - All Dimname-based operator overloads
  - align_tensors, align_as, align_to, rename, refine_names
  - Factory function names variants (empty.names, zeros.names, etc.)

  3. Remove Python named tensor APIs

  - torch/_namedtensor_internals.py
  - torch/_tensor.py (names property, rename methods)
  - torch/functional.py (align_tensors)
  - torch/overrides.py references
  - torch/_dynamo/trace_rules.py references
  - torch/multiprocessing/reductions.py references

  4. Remove C++ named tensor infrastructure and build system

  - Dimname type system (Dimname.h/cpp, python_dimname.h/cpp, python_arg_parser changes)
  - Core infrastructure (NamedTensor.h/cpp, NamedTensorUtils.h/cpp, TensorNames.h/cpp)
  - TensorImpl changes (NamedTensorMetaInterface)
  - Structured kernels (names parameter from set_output_* and all call sites)
  - Guards (NoNamesGuard, NamesMode, guard.reset() calls)
  - Build system (CMakeLists.txt, build_variables.bzl, cmake/prioritized_text.txt)
  - Codegen (torchgen/, tools/autograd/ templates)
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/173895
Approved by: https://github.com/malfet, https://github.com/guangyey
2026-05-29 14:00:48 +00:00
PyTorch MergeBot 676ae521aa Revert "Remove named tensor (#173895)"
This reverts commit b5e90ff502.

Reverted https://github.com/pytorch/pytorch/pull/173895 on behalf of https://github.com/jbschlosser due to c++-20 modernize-use-constraints lint changes break vLLM and tpu ([comment](https://github.com/pytorch/pytorch/pull/173895#issuecomment-4567258753))
2026-05-28 18:57:09 +00:00
Joel Schlosser b5e90ff502 Remove named tensor (#173895)
BE project hard-removing the deprecated named tensor feature to remove overhead and code bloat. This was nearly all done by wrestling with Claude Code, so it needs some personal review and probably needs to be split into multiple PRs to help reviewers.

The process was me absent-mindedly doing this throughout the week while working on other stuff:
```
me: remove named tensor along with all associated APIs, tests, and docs from the codebase
claude: <does stuff>

while not built:
    me: <tries to build>
    if error:
        me: there are still remnants of named tensor (with build-error related example); remove all these
        claude: <does more stuff, usually very good at generalizing from the example>
```

This wasn't particularly efficient (it built after ~27 iterations) but didn't require much thought or time from my end. The only part Claude Code did NOT do is add a couple now-necessary `#include <ATen/WrapDimUtils.h>` statements.

It builds! Testing is still a WIP.

Having Claude Code break this into manageable PRs, the breakdown is:
```
1. Remove named tensor tests and documentation

  - test/test_namedtensor.py
  - test/compiled_autograd_skips/TestNamedTensor.*
  - test/dynamo_expected_failures/TestNamedTensor.*
  - docs/source/named_tensor.md
  - docs/source/name_inference.md
  - Test file updates (test_ops.py, test_overrides.py, test_builtins.py, test_torch.py, etc.)
  - functorch/op_analysis/annotated_ops
  - Expect file updates (HasDecompTest)
  - test/allowlist_for_publicAPI.json

  2. Remove named tensor operators from native_functions.yaml

  - All Dimname-based operator overloads
  - align_tensors, align_as, align_to, rename, refine_names
  - Factory function names variants (empty.names, zeros.names, etc.)

  3. Remove Python named tensor APIs

  - torch/_namedtensor_internals.py
  - torch/_tensor.py (names property, rename methods)
  - torch/functional.py (align_tensors)
  - torch/overrides.py references
  - torch/_dynamo/trace_rules.py references
  - torch/multiprocessing/reductions.py references

  4. Remove C++ named tensor infrastructure and build system

  - Dimname type system (Dimname.h/cpp, python_dimname.h/cpp, python_arg_parser changes)
  - Core infrastructure (NamedTensor.h/cpp, NamedTensorUtils.h/cpp, TensorNames.h/cpp)
  - TensorImpl changes (NamedTensorMetaInterface)
  - Structured kernels (names parameter from set_output_* and all call sites)
  - Guards (NoNamesGuard, NamesMode, guard.reset() calls)
  - Build system (CMakeLists.txt, build_variables.bzl, cmake/prioritized_text.txt)
  - Codegen (torchgen/, tools/autograd/ templates)
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/173895
Approved by: https://github.com/malfet, https://github.com/guangyey
2026-05-28 16:12:16 +00:00
cyy 3c2324c64a [2/N] Fix cppcoreguidelines-init-variables suppression (#146237)
This PR removes all `cppcoreguidelines-init-variables` suppressions.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/146237
Approved by: https://github.com/ezyang
2025-06-19 23:26:42 +00:00
Nikita Shulga c4d1ff02f8 [Lint] Update clang-format to 19.1.4 (#153889)
All changes other than the one to `tools/linter/adapters/s3_init_config.json` are generated by newer clang-format
Pull Request resolved: https://github.com/pytorch/pytorch/pull/153889
Approved by: https://github.com/cyyever, https://github.com/atalman
2025-05-20 14:12:46 +00:00
Alvaro-Kothe e86b6b2a19 Add tests to check pretty print when padding is a string in C++ API (#153126)
Currently there are no tests to verify the behaviour of pretty print when padding is `torch::kSame` or `torch::kValid`. This PR just adds this tests to check for future regressions.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/153126
Approved by: https://github.com/Skylion007
2025-05-08 17:55:25 +00:00
Scott Wolchok c73a526599 Extract reusable portions of elu_kernel into header (#149673)
Similar to #140425, we are making the implementation usable via header-only code sharing.

Review note: #62546 by @yanbing-j removed expm1 usage from this path. I don't know why and expm1 should be more efficient, so I've put it back. Please let me know if there is a good reason I shouldn't.

Testing: existing correctness tests should cover.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/149673
Approved by: https://github.com/cyyever, https://github.com/Skylion007
2025-03-21 23:54:26 +00:00
Richard Barnes fddabc6e0b C10_UNUSED to [[maybe_unused]] (#6357) (#138364)
Summary: Pull Request resolved: https://github.com/pytorch/executorch/pull/6357

Pull Request resolved: https://github.com/pytorch/pytorch/pull/138364
Approved by: https://github.com/Skylion007, https://github.com/eqy
2024-10-19 13:17:43 +00:00
Richard Barnes b7f798caa4 Use C10_UNUSED instead of (void)X (#137239)
Summary:
Auto-generated with
```
buck run //scripts/rbarnes/regex_multiline_replacer:regex_multiline_replacer -- --find '^(\s*for\s*\()(const.*\n)\s*\(void\)[A-Za-z]+;\s*//\s*Suppress.*\s*\n(.*)'  --replace '\1C10_UNUSED \2\3' `find caffe2/ -regex ".*\.\(cpp\|h\)"`
```

Differential Revision: D33432600

Pull Request resolved: https://github.com/pytorch/pytorch/pull/137239
Approved by: https://github.com/Skylion007
2024-10-15 14:32:59 +00:00
cyy 73d0f484b3 [structural binding][11/N] Replace std::tie with structural binding (#130830)
Follows  #130784

Pull Request resolved: https://github.com/pytorch/pytorch/pull/130830
Approved by: https://github.com/janeyx99
2024-07-18 00:45:06 +00:00
cyy 28f6ae2718 [9/N] Replace c10::optional with std::optional (#130674)
Follows  #130509

Pull Request resolved: https://github.com/pytorch/pytorch/pull/130674
Approved by: https://github.com/Skylion007
2024-07-15 00:48:43 +00:00
Nikita Shulga d7caef7996 [CI] Update clang-format (#116002)
To 17.0.6 build using https://github.com/pytorch/test-infra/blob/main/.github/workflows/clang-tidy-linux.yml

Pull Request resolved: https://github.com/pytorch/pytorch/pull/116002
Approved by: https://github.com/suo
2023-12-18 14:58:46 +00:00
Wongboo 68f74dd162 Add python and C++ support for LPPool3d (#114199)
Add python and C++ support for LPPool3d to Fixes #114114

Pull Request resolved: https://github.com/pytorch/pytorch/pull/114199
Approved by: https://github.com/mikaylagawarecki
2023-12-08 18:18:44 +00:00
FFFrog 541591dd79 Add the appropriate check on div_value to the cpp frontend (#114671)
Fixes #114334

As the title stated.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/114671
Approved by: https://github.com/mikaylagawarecki
2023-12-04 01:28:11 +00:00
shibo19 a5e1d38025 add check for torch_arg (#108397)
Fixes https://github.com/pytorch/pytorch/issues/108219
add check for torch_arg marco, as for inchannel/outchannel/groups, it should be greater than 0.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/108397
Approved by: https://github.com/mikaylagawarecki
2023-09-08 23:18:27 +00:00
FFFrog f30f9fec87 Fix the issue described by #106769 (#108340)
Fixes #106769

Align the behavior of the C++ interface with the Python interface

1. Remove some checks in C++ frontend api ,which duplicate with below
https://github.com/pytorch/pytorch/blob/50fa5880e831c0a1d5e0c2469dacfd0b0b8ff85d/aten/src/ATen/native/RNN.cpp#L676-L690
3. Add some checks
4. support 1D
5. Add Test
Pull Request resolved: https://github.com/pytorch/pytorch/pull/108340
Approved by: https://github.com/mikaylagawarecki
2023-09-08 22:22:09 +00:00
Rishub Tamirisa f3b8638074 Adding nn.ZeroPad1d and nn.ZeroPad3d (#96295)
Fixes #95796

### Implementation
Adds python implementation for `nn.ZeroPad1d` and `nn.ZeroPad3d` in `torch/nn/modules/padding.py`.

Adds cpp implementation for `nn::ZeroPad1d` and `nn::ZeroPad3d` in the following 3 files, refactored with templates similarly to `nn::ConstantPad`'s implementation: <br>
- `torch/crsc/api/include/torch/nn/modules/padding.h`
- `torch/csrc/api/include/torch/nn/options/padding.h`
- `torch/csrc/api/src/nn/modules/padding.cpp`

Also added relevant definitions in `torch/nn/modules/__init__.py`.
### Testing
Adds the following tests:
-  cpp tests of similar length and structure as `ConstantPad` and the existing `ZeroPad2d` impl in `test/cpp/api/modules.cpp`
- cpp API parity tests in `torch/testing/_internal/common_nn.py`
- module init tests in `test/test_module_init.py`

Also added relevant definitions in `test/cpp_api_parity/parity-tracker.md`

Pull Request resolved: https://github.com/pytorch/pytorch/pull/96295
Approved by: https://github.com/soulitzer
2023-03-10 03:51:41 +00:00
lezcano 787028cadb Implement col2im decomposition and fix im2col and add a few preconditions (#85541)
As per title
Pull Request resolved: https://github.com/pytorch/pytorch/pull/85541
Approved by: https://github.com/jansel
2022-09-30 09:31:53 +00:00
Peter Bell 8d0cbce069 Lower randint default dtype to the C++ API (#81410)
The default dtype for randint is currently handled with manual python
binding code, this moves it into the `native_functions.yaml` declaration
for API consistency.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/81410
Approved by: https://github.com/albanD
2022-07-21 16:42:49 +00:00
Michael Suo 30fb2c4aba [lint] autoformat test/cpp and torch/csrc
Let's have some fun.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/78828

Approved by: https://github.com/ezyang
2022-06-11 21:11:16 +00:00
Ryan Spring 4f8b986e28 Implement Tanh Gelu Approximation (#61439)
Summary:
1. Implements https://github.com/pytorch/pytorch/issues/39853
2. Adds approximate boolean flag to Gelu
3. Enables Tanh Gelu approximation
4. Adds double backward support for Gelu
5. Enable Tanh Gelu in NvFuser

```
def gelu(x, approximate : str = 'none'):
    if approximate == 'tanh':
        # sqrt(2/pi) = 0.7978845608028654
        return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * (x + 0.044715 * torch.pow(x, 3.0))))
    else:
        return x * normcdf(x)
```

Linking XLA PR - https://github.com/pytorch/xla/pull/3039

Pull Request resolved: https://github.com/pytorch/pytorch/pull/61439

Reviewed By: VitalyFedyunin

Differential Revision: D33894937

Pulled By: jbschlosser

fbshipit-source-id: b65e8fb6ea66168af8f34f45ed50e92737a33851
(cherry picked from commit 6e986f91a9)
2022-02-14 03:40:32 +00:00
kshitij12345 02f6226bff [fix] Dropout2d-3d no-batch-dim (#69885)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/69801

TODO:
* [x] Update C++ API

cc albanD mruberry jbschlosser walterddr kshitij12345

Pull Request resolved: https://github.com/pytorch/pytorch/pull/69885

Reviewed By: mruberry

Differential Revision: D33175470

Pulled By: jbschlosser

fbshipit-source-id: c9d7d9e0f59ba290a0157725c338a345f3d58b9f
(cherry picked from commit 7e4271a156)
2022-02-02 16:40:32 +00:00
Nikita Shulga 74c44ba9d6 Revert D33850228: [pytorch][PR] Implement Tanh Gelu Approximation
Test Plan: revert-hammer

Differential Revision:
D33850228 (https://github.com/pytorch/pytorch/commit/23d03025dc870a26c63a9d0e01aa59f644fd6cbe)

Original commit changeset: 3cc33fb298e4

Original Phabricator Diff: D33850228 (https://github.com/pytorch/pytorch/commit/23d03025dc870a26c63a9d0e01aa59f644fd6cbe)

fbshipit-source-id: 9436e7df73c2b2e2011f321674f24973316d3692
(cherry picked from commit c9efb58223)
2022-01-31 17:44:19 +00:00
Ryan Spring 23d03025dc Implement Tanh Gelu Approximation (#61439)
Summary:
1. Implements https://github.com/pytorch/pytorch/issues/39853
2. Adds approximate boolean flag to Gelu
3. Enables Tanh Gelu approximation
4. Adds double backward support for Gelu
5. Enable Tanh Gelu in NvFuser

```
def gelu(x, approximate : str = 'none'):
    if approximate == 'tanh':
        # sqrt(2/pi) = 0.7978845608028654
        return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * (x + 0.044715 * torch.pow(x, 3.0))))
    else:
        return x * normcdf(x)
```

Linking XLA PR - https://github.com/pytorch/xla/pull/3039

Pull Request resolved: https://github.com/pytorch/pytorch/pull/61439

Reviewed By: cpuhrsch

Differential Revision: D33850228

Pulled By: jbschlosser

fbshipit-source-id: 3cc33fb298e480d7ecc5c67716da019d60c6ab33
(cherry picked from commit 3a53b3e94f)
2022-01-31 17:07:45 +00:00
Joel Schlosser cb823d9f07 Revert D33744717: [pytorch][PR] Implement Tanh Gelu Approximation
Test Plan: revert-hammer

Differential Revision:
D33744717 (https://github.com/pytorch/pytorch/commit/f499ab9ceff49be0b64a15020103c6baec3387ea)

Original commit changeset: d64532a562ed

Original Phabricator Diff: D33744717 (https://github.com/pytorch/pytorch/commit/f499ab9ceff49be0b64a15020103c6baec3387ea)

fbshipit-source-id: 396c3f63de5865f894dbc353d0790a01a624be93
(cherry picked from commit e9fb2d1db1)
2022-01-28 18:35:01 +00:00
Ryan Spring f499ab9cef Implement Tanh Gelu Approximation (#61439)
Summary:
1. Implements https://github.com/pytorch/pytorch/issues/39853
2. Adds approximate boolean flag to Gelu
3. Enables Tanh Gelu approximation
4. Adds double backward support for Gelu
5. Enable Tanh Gelu in NvFuser

```
def gelu(x, approximate : str = 'none'):
    if approximate == 'tanh':
        # sqrt(2/pi) = 0.7978845608028654
        return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * (x + 0.044715 * torch.pow(x, 3.0))))
    else:
        return x * normcdf(x)
```

Linking XLA PR - https://github.com/pytorch/xla/pull/3039

Pull Request resolved: https://github.com/pytorch/pytorch/pull/61439

Reviewed By: mikaylagawarecki

Differential Revision: D33744717

Pulled By: jbschlosser

fbshipit-source-id: d64532a562ed53247bb4fa52bb16722634d5c187
(cherry picked from commit 4713dd9cca)
2022-01-28 16:59:09 +00:00
Joel Schlosser e6befbe85c Add flag to optionally average output attention weights across heads (#70055)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/47583

Pull Request resolved: https://github.com/pytorch/pytorch/pull/70055

Reviewed By: bhosmer

Differential Revision: D33457866

Pulled By: jbschlosser

fbshipit-source-id: 17746b3668b0148c1e1ed8333227b7c42f1e3bf5
2022-01-06 17:32:37 -08:00
George Qi 8af39b7668 AdaptiveLogSoftmaxWithLoss no_batch_dim support (#69054)
Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/69054

Test Plan: Imported from OSS

Reviewed By: jbschlosser

Differential Revision: D33200166

Pulled By: george-qi

fbshipit-source-id: 9d953744351a25f372418d2a64e8402356d1e9b7
2021-12-29 10:25:26 -08:00
Richard Barnes afb742382a use irange for loops 10 (#69394)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/69394

Modified loops in files under fbsource/fbcode/caffe2/ from the format
```
for(TYPE var=x0;var<x_max;x++)
```
to the format
```
for(const auto var: irange(xmax))
```

This was achieved by running r-barnes's loop upgrader script (D28874212) with some modification to exclude all files under /torch/jit and a number of reversions or unused variable suppression warnings added by hand.

Test Plan: Sandcastle

Reviewed By: malfet

Differential Revision: D32837991

fbshipit-source-id: fc7c4f76d2f32a17a0faf329294b3fe7cb81df32
2021-12-09 09:49:34 -08:00
Ramanpreet Nara f587267dc7 Revert D31705359: use irange for loops 8
Test Plan: revert-hammer

Differential Revision:
D31705359 (https://github.com/pytorch/pytorch/commit/17e52004410453bcc490087917ca163efd819695)

Original commit changeset: c9ea2fbc0f9c

fbshipit-source-id: 08fff2d12beca953ad30dd0baabf86e39ac84f14
2021-12-02 12:55:08 -08:00
Richard Barnes 17e5200441 use irange for loops 8 (#66743)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/66743

Modified loops in files under fbsource/fbcode/caffe2/ from the format

`for(TYPE var=x0;var<x_max;x++)`

to the format

`for(const auto var: irange(xmax))`

This was achieved by running r-barnes's loop upgrader script (D28874212) with some modification to exclude all files under /torch/jit and a number of reversions or unused variable suppression warnings added by hand.

Test Plan: Sandcastle

Reviewed By: malfet

Differential Revision: D31705359

fbshipit-source-id: c9ea2fbc0f9cd29e97a52dcb203addc5f2abb09b
2021-12-02 10:21:29 -08:00
Xue Li 2f099c7555 Revert D30652629: use irange for loops
Test Plan: revert-hammer

Differential Revision:
D30652629 (https://github.com/pytorch/pytorch/commit/687c2267d4dfb69138483f90deb4d4f5921a2965)

Original commit changeset: 0ae6c4bbbb55

fbshipit-source-id: 5c4f067b584a021c8c9656454d1ee60999600fb3
2021-10-15 15:23:10 -07:00
Richard Barnes 687c2267d4 use irange for loops (#66234)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/66234

Modified loops in files under fbsource/fbcode/caffe2/ from the format

`for(TYPE var=x0;var<x_max;x++)`

to the format

`for(const auto var: irange(xmax))`

This was achieved by running r-barnes's loop upgrader script (D28874212) with some modification to exclude all files under /torch/jit and a number of reversions or unused variable suppression warnings added by hand.

bypass_size_limit
allow-large-files

Test Plan: Sandcastle

Reviewed By: ngimel

Differential Revision: D30652629

fbshipit-source-id: 0ae6c4bbbb554bad42e372792a6430e1acf15e3e
2021-10-15 13:50:33 -07:00
kshitij12345 a012216b96 [nn] Fold : no batch dim (#64909)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/64907
Reference: https://github.com/pytorch/pytorch/issues/60585

Pull Request resolved: https://github.com/pytorch/pytorch/pull/64909

Reviewed By: cpuhrsch, heitorschueroff

Differential Revision: D30991087

Pulled By: jbschlosser

fbshipit-source-id: 91a37e0b1d51472935ff2308719dfaca931513f3
2021-09-23 08:37:32 -07:00
Peter Bell d701357d92 Factor out TensorBase that doesn't depend on native operators (#63612)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/63612

This makes Tensor inherit from a new class TensorBase, that provides a subset of Tensor that doesn't
directly depend on native_functions.yaml. Code that only includes TensorBase.h with thus not need to
be rebuilt every time someone changes an operator signature.

Making `Tensor` inherit from this class means that `const TensorBase&` parameters will be callable
with an ordinary `Tensor`. I've also made `Tensor` constructible and assignable from `TensorBase` to
minimize friction in code mixing the two types.

To help enforce that `Tensor.h` and `Functions.h` aren't accidentally included, I've added an error
into `Operators.h` if `TORCH_ASSERT_NO_OPERATORS` is defined. We can either set this in the build
system for certain folders, or just define it at the top of any file.

I've also included an example of manually special-casing the commonly used `contiguous` operator.
The inline function's slow path defers to `TensorBase::__dispatch_contiguous` which is defined in
`Tensor.cpp`. I've made it so `OptionalTensorRef` is constructible from `TensorBase`, so I can
materialize a `Tensor` for use in dispatch without actually increasing its refcount.

Test Plan: Imported from OSS

Reviewed By: gchanan

Differential Revision: D30728580

Pulled By: ezyang

fbshipit-source-id: 2cbc8eee08043382ee6904ea8e743b1286921c03
2021-09-08 13:28:54 -07:00
Thomas J. Fan d3bcba5f85 ENH Adds label_smoothing to cross entropy loss (#63122)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/7455

Partially resolves pytorch/vision#4281

Pull Request resolved: https://github.com/pytorch/pytorch/pull/63122

Reviewed By: iramazanli

Differential Revision: D30586076

Pulled By: jbschlosser

fbshipit-source-id: 06afc3aa1f8b9edb07fe9ed68c58968ad1926924
2021-08-29 23:33:04 -07:00
yanbing-j 33a163d886 Enable BFloat16 LeakyReLU and RReLU in CPU path (#61514)
Summary:
Enable and optimize BFloat16 LeakyReLU and RReLU in CPU path.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/61514

Reviewed By: ejguan

Differential Revision: D30257612

Pulled By: VitalyFedyunin

fbshipit-source-id: 8cc0d1faacd02dcc9827af724a86d95b6952748f
2021-08-24 08:34:56 -07:00
yanbing-j c7a7c2b62f Enable Gelu fp32/bf16 in CPU path using Mkldnn implementation (#58525)
Summary:
Enable Gelu bf16/fp32 in CPU path using Mkldnn implementation. User doesn't need to_mkldnn() explicitly. New Gelu fp32 performs better than original one.

Add Gelu backward for https://github.com/pytorch/pytorch/pull/53615.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/58525

Reviewed By: ejguan

Differential Revision: D29940369

Pulled By: ezyang

fbshipit-source-id: df9598262ec50e5d7f6e96490562aa1b116948bf
2021-08-03 06:52:23 -07:00
Nikita Shulga a9b0a921d5 Disable avoid-non-const-global-variables lint check (#62008)
Summary:
As GoogleTest `TEST` macro is non-compliant with it as well as `DEFINE_DISPATCH`

All changes but the ones to `.clang-tidy` are generated using following script:
```
for i in `find . -type f -iname "*.c*" -or -iname "*.h"|xargs grep cppcoreguidelines-avoid-non-const-global-variables|cut -f1 -d:|sort|uniq`;  do sed -i "/\/\/ NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)/d" $i; done
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/62008

Reviewed By: driazati, r-barnes

Differential Revision: D29838584

Pulled By: malfet

fbshipit-source-id: 1b2f8602c945bd4ce50a9bfdd204755556e31d13
2021-07-22 18:04:40 -07:00
Thomas J. Fan c16f87949f ENH Adds nn.ReflectionPad3d (#59791)
Summary:
Fixes https://github.com/pytorch/pytorch/issues/27655

This PR adds a C++ and Python version of ReflectionPad3d with structured kernels. The implementation uses lambdas extensively to better share code from the backward and forward pass.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/59791

Reviewed By: gchanan

Differential Revision: D29242015

Pulled By: jbschlosser

fbshipit-source-id: 18e692d3b49b74082be09f373fc95fb7891e1b56
2021-06-21 10:53:14 -07:00
Adnios 09a8f22bf9 Add mish activation function (#58648)
Summary:
See issus: https://github.com/pytorch/pytorch/issues/58375

Pull Request resolved: https://github.com/pytorch/pytorch/pull/58648

Reviewed By: gchanan

Differential Revision: D28625390

Pulled By: jbschlosser

fbshipit-source-id: 23ea2eb7d5b3dc89c6809ff6581b90ee742149f4
2021-05-25 10:36:21 -07:00
Nikita Shulga 3a66a1cb99 [clang-tidy] Exclude cppcoreguidelines-avoid-magic-numbers (#57841)
Summary:
Add cppcoreguidelines-avoid-magic-numbers exclusion to clang-tidy
Remove existing nolint warnings using following script:
```
for file in `git ls-files | grep -v \.py`; do gsed '/^ *\/\/ NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers)/d' -i  $file; done
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/57841

Reviewed By: samestep

Differential Revision: D28295045

Pulled By: malfet

fbshipit-source-id: 7c6e8d1213c9593f169ed3df6a916498f1a97163
2021-05-07 20:02:33 -07:00
Nikita Shulga 4cb534f92e Make PyTorch code-base clang-tidy compliant (#56892)
Summary:
This is an automatic change generated by the following script:
```
#!/usr/bin/env python3
from subprocess import check_output, check_call
import os

def get_compiled_files_list():
    import json
    with open("build/compile_commands.json") as f:
        data = json.load(f)
    files = [os.path.relpath(node['file']) for node in data]
    for idx, fname in enumerate(files):
        if fname.startswith('build/') and fname.endswith('.DEFAULT.cpp'):
            files[idx] = fname[len('build/'):-len('.DEFAULT.cpp')]
    return files

def run_clang_tidy(fname):
    check_call(["python3", "tools/clang_tidy.py", "-c", "build", "-x", fname,"-s"])
    changes = check_output(["git", "ls-files", "-m"])
    if len(changes) == 0:
        return
    check_call(["git", "commit","--all", "-m", f"NOLINT stubs for {fname}"])

def main():
    git_files = check_output(["git", "ls-files"]).decode("ascii").split("\n")
    compiled_files = get_compiled_files_list()
    for idx, fname in enumerate(git_files):
        if fname not in compiled_files:
            continue
        if fname.startswith("caffe2/contrib/aten/"):
            continue
        print(f"[{idx}/{len(git_files)}] Processing {fname}")
        run_clang_tidy(fname)

if __name__ == "__main__":
    main()
```

Pull Request resolved: https://github.com/pytorch/pytorch/pull/56892

Reviewed By: H-Huang

Differential Revision: D27991944

Pulled By: malfet

fbshipit-source-id: 5415e1eb2c1b34319a4f03024bfaa087007d7179
2021-04-28 14:10:25 -07:00
Kurt Mohler 3fe4718d16 Add padding_idx argument to EmbeddingBag (#49237)
Summary:
This PR adds a `padding_idx` parameter to `nn.EmbeddingBag` and `nn.functional.embedding_bag`. As with `nn.Embedding`'s `padding_idx` argument, if an embedding's index is equal to `padding_idx` it is ignored, so it is not included in the reduction.

This PR does not add support for `padding_idx` for quantized or ONNX `EmbeddingBag` for opset10/11 (opset9 is supported). In these cases, an error is thrown if `padding_idx` is provided.

Fixes https://github.com/pytorch/pytorch/issues/3194

Pull Request resolved: https://github.com/pytorch/pytorch/pull/49237

Reviewed By: walterddr, VitalyFedyunin

Differential Revision: D26948258

Pulled By: jbschlosser

fbshipit-source-id: 3ca672f7e768941f3261ab405fc7597c97ce3dfc
2021-04-14 09:38:01 -07:00