René's URL Explorer Experiment


Title: FAQ — PyTorch main documentation

Description: Frequently asked questions about the PyTorch C++ API and libtorch.

Keywords:

direct link

Domain: docs.pytorch.org


Hey, it has json ld scripts:
    {
       "@context": "https://schema.org",
       "@type": "Article",
       "name": "FAQ",
       "headline": "FAQ",
       "description": "Frequently asked questions about the PyTorch C++ API and libtorch.",
       "url": "/faq.html",
       "articleBody": "FAQ# Listed below are a number of common issues users face with the various parts of the C++ API. C++ Extensions# Undefined symbol errors from PyTorch/ATen# Problem: You import your extension and get an ImportError stating that some C++ symbol from PyTorch or ATen is undefined. For example: \u003e\u003e\u003e import extension Traceback (most recent call last): File \"\u003cstdin\u003e\", line 1, in \u003cmodule\u003e ImportError: /home/user/.pyenv/versions/3.7.1/lib/python3.7/site-packages/extension.cpython-37m-x86_64-linux-gnu.so: undefined symbol: _ZN2at19UndefinedTensorImpl10_singletonE Fix: The fix is to import torch before you import your extension. This will make the symbols from the PyTorch dynamic (shared) library that your extension depends on available, allowing them to be resolved once you import your extension. I created a tensor using a function from at:: and get errors# Problem: You created a tensor using e.g. at::ones or at::randn or any other tensor factory from the at:: namespace and are getting errors. Fix: Replace at:: with torch:: for factory function calls. You should never use factory functions from the at:: namespace, as they will create tensors. The corresponding torch:: functions will create variables, and you should only ever deal with variables in your code. LibTorch# How do I move a model to GPU?# Problem: You want to run your model on GPU but are unsure how to move both the model and tensors to the correct device. Fix: Use the to() method to move your model and tensors to a CUDA device: torch::Device device(torch::kCUDA); model-\u003eto(device); auto input = torch::randn({1, 3, 224, 224}).to(device); auto output = model-\u003eforward(input); You can also check for CUDA availability before moving: torch::Device device(torch::cuda::is_available() ? torch::kCUDA : torch::kCPU); Make sure to compile with the TorchScript headers by including \u003ctorch/script.h\u003e. My model runs slower in C++ than in Python# Problem: Your model inference is slower in C++ compared to Python. Fix: There are several common causes: Enable inference mode: Wrap your inference code with torch::NoGradGuard to disable gradient computation: torch::NoGradGuard no_grad; auto output = model-\u003eforward(input); Enable optimizations: For TorchScript models, use optimize_for_inference: module = torch::jit::optimize_for_inference(module); Warm up the model: Run a few inference passes before benchmarking to allow JIT compilation and memory allocation to complete. Check thread settings: Ensure proper thread configuration: at::set_num_threads(4); // Adjust based on your hardware Neural Network Modules# How do I register submodules in a custom module?# Problem: You created a custom module but the submodules are not being recognized during forward() or when saving/loading the model. Fix: You must register submodules in the constructor using register_module(): struct MyModel : torch::nn::Module { MyModel() { fc1 = register_module(\"fc1\", torch::nn::Linear(784, 128)); fc2 = register_module(\"fc2\", torch::nn::Linear(128, 10)); } torch::Tensor forward(torch::Tensor x) { x = torch::relu(fc1-\u003eforward(x)); return fc2-\u003eforward(x); } torch::nn::Linear fc1{nullptr}, fc2{nullptr}; }; How do I set a module to evaluation mode?# Problem: Layers like Dropout and BatchNorm behave differently during training and evaluation, and you need to switch between modes. Fix: Use the eval() and train() methods: model-\u003eeval(); // Set to evaluation mode // ... run inference ... model-\u003etrain(); // Set back to training mode Data Loading# How do I create a custom dataset?# Problem: You want to load your own data instead of using built-in datasets. Fix: Create a class that inherits from torch::data::datasets::Dataset and implement the get() and size() methods: class CustomDataset : public torch::data::datasets::Dataset\u003cCustomDataset\u003e { public: explicit CustomDataset(const std::string\u0026 data_path) { // Load your data here } torch::data::Example\u003c\u003e get(size_t index) override { // Return a single data sample torch::Tensor data = /* load data at index */; torch::Tensor label = /* load label at index */; return {data, label}; } torch::optional\u003csize_t\u003e size() const override { return dataset_size_; } private: size_t dataset_size_; }; Then use it with a DataLoader: auto dataset = CustomDataset(\"path/to/data\") .map(torch::data::transforms::Stack\u003c\u003e()); auto dataloader = torch::data::make_data_loader( std::move(dataset), torch::data::DataLoaderOptions().batch_size(32).workers(4)); Serialization# How do I save and load model weights?# Problem: You want to save trained model weights and load them later. Fix: Use torch::save() and torch::load(): // Saving torch::save(model, \"model.pt\"); // Loading torch::load(model, \"model.pt\"); For saving only specific tensors or state: torch::serialize::OutputArchive archive; model-\u003esave(archive); archive.save_to(\"model_weights.pt\"); // Loading torch::serialize::InputArchive archive; archive.load_from(\"model_weights.pt\"); model-\u003eload(archive); Build and Compilation# CMake cannot find Torch# Problem: When building your project with CMake, you get an error that Torch package cannot be found. Fix: You need to specify the path to the LibTorch installation using CMAKE_PREFIX_PATH: cmake -DCMAKE_PREFIX_PATH=/path/to/libtorch .. Alternatively, set Torch_DIR to point to the directory containing TorchConfig.cmake: cmake -DTorch_DIR=/path/to/libtorch/share/cmake/Torch .. Linker errors with undefined references# Problem: Your project compiles but you get linker errors with undefined references to PyTorch symbols. Fix: Ensure you\u2019re linking against all required libraries in your CMakeLists.txt: find_package(Torch REQUIRED) add_executable(my_app main.cpp) target_link_libraries(my_app \"${TORCH_LIBRARIES}\") set_property(TARGET my_app PROPERTY CXX_STANDARD 17) Also ensure that the compiler flags are set correctly: set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}\")",
       "author": {
         "@type": "Organization",
         "name": "PyTorch Contributors",
         "url": "https://pytorch.org"
       },
       "image": "https://pytorch.org/docs/stable/_static/img/pytorch_seo.png",
       "mainEntityOfPage": {
         "@type": "WebPage",
         "@id": "/faq.html"
       },
       "datePublished": "2023-01-01T00:00:00Z",
       "dateModified": "2023-01-01T00:00:00Z"
     }
 

docsearch:languageen
llm:site-typedocumentation
llm:frameworkPyTorch
llm:descriptionFrequently asked questions about the PyTorch C++ API and libtorch.
llm:navigation-filehttps://pytorch.org/docs/stable/llms.txt
llm:sitemaphttps://pytorch.org/docs/stable/sitemap.xml
llm:versionmain
llm:projectPyTorch
llm:page-typedocumentation
og:imagehttps://docs.pytorch.org/docs/stable/_static/img/pytorch_seo.png
None1

Links:

Skip to main contenthttps://docs.pytorch.org/cppdocs/faq.html#main-content
Home https://docs.pytorch.org/cppdocs/index.html
mainhttps://docs.pytorch.org/cppdocs/index.html
Installing C++ Distributions of PyTorch https://docs.pytorch.org/cppdocs/installing.html
The C++ Frontend https://docs.pytorch.org/cppdocs/frontend.html
C++ API Reference https://docs.pytorch.org/cppdocs/api/index.html
ATen: Tensor Library https://docs.pytorch.org/cppdocs/api/aten/index.html
C10: Core Utilities https://docs.pytorch.org/cppdocs/api/c10/index.html
Autograd: Automatic Differentiation https://docs.pytorch.org/cppdocs/api/autograd/index.html
CUDA Support https://docs.pytorch.org/cppdocs/api/cuda/index.html
XPU Support https://docs.pytorch.org/cppdocs/api/xpu/index.html
Neural Network Modules (torch::nn) https://docs.pytorch.org/cppdocs/api/nn/index.html
Optimizers (torch::optim) https://docs.pytorch.org/cppdocs/api/optim/index.html
Data Loading (torch::data) https://docs.pytorch.org/cppdocs/api/data/index.html
Serialization (torch::serialize) https://docs.pytorch.org/cppdocs/api/serialize/index.html
Torch Library API https://docs.pytorch.org/cppdocs/api/library/index.html
Torch Stable API https://docs.pytorch.org/cppdocs/api/stable/index.html
FAQ https://docs.pytorch.org/cppdocs/faq.html
Go to pytorch.org https://pytorch.org
Xhttps://x.com/PyTorch
GitHubhttps://github.com/pytorch/pytorch
PyTorch Forumhttps://discuss.pytorch.org/
PyPihttps://pypi.org/project/torch/
mainhttps://docs.pytorch.org/cppdocs/index.html
Installing C++ Distributions of PyTorch https://docs.pytorch.org/cppdocs/installing.html
The C++ Frontend https://docs.pytorch.org/cppdocs/frontend.html
C++ API Reference https://docs.pytorch.org/cppdocs/api/index.html
ATen: Tensor Library https://docs.pytorch.org/cppdocs/api/aten/index.html
C10: Core Utilities https://docs.pytorch.org/cppdocs/api/c10/index.html
Autograd: Automatic Differentiation https://docs.pytorch.org/cppdocs/api/autograd/index.html
CUDA Support https://docs.pytorch.org/cppdocs/api/cuda/index.html
XPU Support https://docs.pytorch.org/cppdocs/api/xpu/index.html
Neural Network Modules (torch::nn) https://docs.pytorch.org/cppdocs/api/nn/index.html
Optimizers (torch::optim) https://docs.pytorch.org/cppdocs/api/optim/index.html
Data Loading (torch::data) https://docs.pytorch.org/cppdocs/api/data/index.html
Serialization (torch::serialize) https://docs.pytorch.org/cppdocs/api/serialize/index.html
Torch Library API https://docs.pytorch.org/cppdocs/api/library/index.html
Torch Stable API https://docs.pytorch.org/cppdocs/api/stable/index.html
FAQ https://docs.pytorch.org/cppdocs/faq.html
Go to pytorch.org https://pytorch.org
Xhttps://x.com/PyTorch
GitHubhttps://github.com/pytorch/pytorch
PyTorch Forumhttps://discuss.pytorch.org/
PyPihttps://pypi.org/project/torch/
https://docs.pytorch.org/cppdocs/index.html
#https://docs.pytorch.org/cppdocs/faq.html#faq
#https://docs.pytorch.org/cppdocs/faq.html#c-extensions
#https://docs.pytorch.org/cppdocs/faq.html#undefined-symbol-errors-from-pytorch-aten
#https://docs.pytorch.org/cppdocs/faq.html#i-created-a-tensor-using-a-function-from-at-and-get-errors
#https://docs.pytorch.org/cppdocs/faq.html#libtorch
#https://docs.pytorch.org/cppdocs/faq.html#how-do-i-move-a-model-to-gpu
#https://docs.pytorch.org/cppdocs/faq.html#my-model-runs-slower-in-c-than-in-python
#https://docs.pytorch.org/cppdocs/faq.html#neural-network-modules
#https://docs.pytorch.org/cppdocs/faq.html#how-do-i-register-submodules-in-a-custom-module
#https://docs.pytorch.org/cppdocs/faq.html#how-do-i-set-a-module-to-evaluation-mode
#https://docs.pytorch.org/cppdocs/faq.html#data-loading
#https://docs.pytorch.org/cppdocs/faq.html#how-do-i-create-a-custom-dataset
#https://docs.pytorch.org/cppdocs/faq.html#serialization
#https://docs.pytorch.org/cppdocs/faq.html#how-do-i-save-and-load-model-weights
#https://docs.pytorch.org/cppdocs/faq.html#build-and-compilation
#https://docs.pytorch.org/cppdocs/faq.html#cmake-cannot-find-torch
#https://docs.pytorch.org/cppdocs/faq.html#linker-errors-with-undefined-references
previous Utilities https://docs.pytorch.org/cppdocs/api/stable/utilities.html
PyData Sphinx Themehttps://pydata-sphinx-theme.readthedocs.io/en/stable/index.html
previous Utilities https://docs.pytorch.org/cppdocs/api/stable/utilities.html
C++ Extensionshttps://docs.pytorch.org/cppdocs/faq.html#c-extensions
Undefined symbol errors from PyTorch/ATenhttps://docs.pytorch.org/cppdocs/faq.html#undefined-symbol-errors-from-pytorch-aten
I created a tensor using a function from at:: and get errorshttps://docs.pytorch.org/cppdocs/faq.html#i-created-a-tensor-using-a-function-from-at-and-get-errors
LibTorchhttps://docs.pytorch.org/cppdocs/faq.html#libtorch
How do I move a model to GPU?https://docs.pytorch.org/cppdocs/faq.html#how-do-i-move-a-model-to-gpu
My model runs slower in C++ than in Pythonhttps://docs.pytorch.org/cppdocs/faq.html#my-model-runs-slower-in-c-than-in-python
Neural Network Moduleshttps://docs.pytorch.org/cppdocs/faq.html#neural-network-modules
How do I register submodules in a custom module?https://docs.pytorch.org/cppdocs/faq.html#how-do-i-register-submodules-in-a-custom-module
How do I set a module to evaluation mode?https://docs.pytorch.org/cppdocs/faq.html#how-do-i-set-a-module-to-evaluation-mode
Data Loadinghttps://docs.pytorch.org/cppdocs/faq.html#data-loading
How do I create a custom dataset?https://docs.pytorch.org/cppdocs/faq.html#how-do-i-create-a-custom-dataset
Serializationhttps://docs.pytorch.org/cppdocs/faq.html#serialization
How do I save and load model weights?https://docs.pytorch.org/cppdocs/faq.html#how-do-i-save-and-load-model-weights
Build and Compilationhttps://docs.pytorch.org/cppdocs/faq.html#build-and-compilation
CMake cannot find Torchhttps://docs.pytorch.org/cppdocs/faq.html#cmake-cannot-find-torch
Linker errors with undefined referenceshttps://docs.pytorch.org/cppdocs/faq.html#linker-errors-with-undefined-references
Show Source https://docs.pytorch.org/cppdocs/_sources/faq.md.txt
ExecuTorchhttps://docs.pytorch.org/executorch
Helionhttps://docs.pytorch.org/helion
torchaohttps://docs.pytorch.org/ao
kinetohttps://github.com/pytorch/kineto
torchtitanhttps://github.com/pytorch/torchtitan
TorchRLhttps://docs.pytorch.org/rl
torchvisionhttps://docs.pytorch.org/vision
torchaudiohttps://docs.pytorch.org/audio
tensordicthttps://docs.pytorch.org/tensordict
PyTorch on XLA Deviceshttps://docs.pytorch.org/xla
View Docshttps://docs.pytorch.org/docs/stable/index.html
View Tutorialshttps://docs.pytorch.org/tutorials
View Resourceshttps://pytorch.org/resources
Privacy Policyhttps://www.linuxfoundation.org/privacy/
https://www.facebook.com/pytorch
https://twitter.com/pytorch
https://www.youtube.com/pytorch
https://www.linkedin.com/company/pytorch
https://pytorch.slack.com
https://pytorch.org/wechat
Policieshttps://www.linuxfoundation.org/legal/policies
Trademark Usagehttps://www.linuxfoundation.org/trademark-usage
Privacy Policyhttp://www.linuxfoundation.org/privacy
Cookies Policyhttps://opensource.fb.com/legal/cookie-policy
Sphinxhttps://www.sphinx-doc.org/
PyData Sphinx Themehttps://pydata-sphinx-theme.readthedocs.io/en/stable/index.html

Viewport: width=device-width, initial-scale=1


URLs of crawlers that visited me.