Repository: pytorch
Issue: Libtorch C++ register_module raise "read access violation error"
Labels: module: cpp,triaged

### 🐛 Describe the bug

🐛 Describe the bug

I'm trying to run the sample end-to-end network in LibTorch to test my configurations (https://pytorch.org/cppdocs/frontend.html#end-to-end-example). However, when the program reaches the line `fc1 = register_module("fc1", torch::nn::Linear(784, 64));`, it raises a read access violation error.

Error traceback:
```cpp
// main.cpp
// ...
fc1 = register_module("fc1", torch::nn::Linear(784, 64)); // raise error
// ...

// $(CPP_ENVIRONMENT)libtorch\include\torch\csrc\api\include\torch\nn\module.h
// line 663
template <typename ModuleType>
std::shared_ptr<ModuleType> Module::register_module(
    std::string name,
    ModuleHolder<ModuleType> module_holder) {
  return register_module(std::move(name), module_holder.ptr());  // raise error
}

// $(CPP_ENVIRONMENT)libtorch\include\torch\csrc\api\include\torch\nn\module.h
// line 649
template <typename ModuleType>
std::shared_ptr<ModuleType> Module::register_module(
    std::string name,
    std::shared_ptr<ModuleType> module) {
  TORCH_CHECK(!name.empty(), "Submodule name must not be empty");
  TORCH_CHECK(
      name.find('.') == std::string::npos,
      "Submodule name must not contain a dot (got '",
      name,
      "')");
  auto& base_module = children_.insert(std::move(name), std::move(module));  // raise error
  return std::dynamic_pointer_cast<ModuleType>(base_module);
}

// $(CPP_ENVIRONMENT)libtorch\include\torch\csrc\api\include\torch\ordered_dict.h
// line 363
template <typename Key, typename Value>
template <typename K, typename V>
Value& OrderedDict<Key, Value>::insert(K&& key, V&& value) {
  TORCH_CHECK(
      index_.count(key) == 0, key_description_, " '", key, "' already defined");   // raise error
  // Copy `key` here and move it into the index.
  items_.emplace_back(key, std::forward<V>(value));
  index_.emplace(std::forward<K>(key), size() - 1);
  return items_.back().value();
}

// D:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.35.32215\include\xhash
// line 1563
    template <class _Keyty>
    _NODISCARD _Hash_find_last_result<_Nodeptr> _Find_last(const _Keyty& _Keyval, const size_t _Hashval) const {
        // find the insertion point for _Keyval and whether an element identical to _Keyval is already in the container
        const size_type _Bucket = _Hashval & _Mask;
        _Nodeptr _Where         = _Vec._Mypair._Myval2._Myfirst[(_Bucket << 1) + 1]._Ptr;  // raise error
        const _Nodeptr _End     = _List._Mypair._Myval2._Myhead;
        if (_Where == _End) {
            return {_End, _Nodeptr{}};
        }
// ...
```
error output:
```text
Exception thrown: read access violation.
this->_Vec._Mypair._Myval2.**_Myfirst** was 0x111011101110111.
```

Here is my environment:

* OS: windows 11
* nvidia-smi: 537.13
* CUDA: 12.2
* CUDNN: 8.9.7.29
* libtorch: 2.3.0.dev20231229+cu121

Project config:
* IDE: visual studio 2022
* C++ language standard: ISO C++ 17 Standard (C++ 20 and preview version are also tested with same result)
* external include directories: 
  * `$(CPP_ENVIRONMENT)libtorch\include\torch\csrc\api\include;`
  * `$(CPP_ENVIRONMENT)libtorch\include;`
* linker > additional library directories:
  * `$(CPP_ENVIRONMENT)libtorch\lib;`
* linker > additional dependencies:
  * `asmjit.lib`; `c10.lib`; `c10_cuda.lib`; `caffe2_nvrtc.lib`; `cpuinfo.lib`; `dnnl.lib`; `fbgemm.lib`; `fbjni.lib`; `fmt.lib`; `kineto.lib`; `libprotobuf.lib`; `libprotoc.lib`; `pthreadpool.lib`; `pytorch_jni.lib`; `torch.lib`; `torch_cpu.lib`; `torch_cuda.lib`; `XNNPACK.lib`;

other:
The simple example of creating a tensor works without any problems.

### Versions

PyTorch version: N/A
Is debug build: N/A
CUDA used to build PyTorch: N/A
ROCM used to build PyTorch: N/A

OS: Microsoft Windows 11 Home China
GCC version: Could not collect
Clang version: Could not collect
CMake version: version 3.28.1
Libc version: N/A

Python version: 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)] (64-bit runtime)
Python platform: Windows-10-10.0.22621-SP0
Is CUDA available: N/A
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: Quadro P520
Nvidia driver version: 537.13
cuDNN version: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.2\bin\cudnn_ops_train64_8.dll
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: N/A

CPU:










Revision=

Versions of relevant libraries:
[pip3] No relevant packages
[conda] blas                      1.0                         mkl  
[conda] mkl                       2023.1.0         h8bd8f75_46356  
[conda] mkl-service               2.4.0           py311h2bbff1b_1  
[conda] mkl_fft                   1.3.6           py311hf62ec03_1  
[conda] mkl_random                1.2.2           py311hf62ec03_1  
[conda] numpy                     1.24.3          py311hdab7c0b_1  
[conda] numpy-base                1.24.3          py311hd01c5d8_1  
[conda] numpydoc                  1.5.0           py311haa95532_0  

cc @jbschlosser