中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁(yè) > news >正文

在中國(guó)可以做國(guó)外的域名網(wǎng)站嗎免費(fèi)做網(wǎng)站軟件

在中國(guó)可以做國(guó)外的域名網(wǎng)站嗎,免費(fèi)做網(wǎng)站軟件,營(yíng)銷網(wǎng)站建設(shè)定制,福田蒙派克10座黃牌使用自定義 C 類擴(kuò)展 TorchScript 本教程是自定義運(yùn)算符教程的后續(xù)教程,并介紹了我們?yōu)閷?C 類同時(shí)綁定到 TorchScript 和 Python 而構(gòu)建的 API。 該 API 與 pybind11 非常相似,如果您熟悉該系統(tǒng),則大多數(shù)概念都將轉(zhuǎn)移過來。 在 C 中實(shí)現(xiàn)和…

使用自定義 C ++類擴(kuò)展 TorchScript

本教程是自定義運(yùn)算符教程的后續(xù)教程,并介紹了我們?yōu)閷?C ++類同時(shí)綁定到 TorchScript 和 Python 而構(gòu)建的 API。 該 API 與 pybind11 非常相似,如果您熟悉該系統(tǒng),則大多數(shù)概念都將轉(zhuǎn)移過來。

在 C ++中實(shí)現(xiàn)和綁定類

在本教程中,我們將定義一個(gè)簡(jiǎn)單的 C ++類,該類在成員變量中保持持久狀態(tài)。

// This header is all you need to do the C++ portions of this
// tutorial
#include <torch/script.h>
// This header is what defines the custom class registration
// behavior specifically. script.h already includes this, but
// we include it here so you know it exists in case you want
// to look at the API or implementation.
#include <torch/custom_class.h>#include <string>
#include <vector>template <class T>
struct Stack : torch::jit::CustomClassHolder {std::vector<T> stack_;Stack(std::vector<T> init) : stack_(init.begin(), init.end()) {}void push(T x) {stack_.push_back(x);}T pop() {auto val = stack_.back();stack_.pop_back();return val;}c10::intrusive_ptr<Stack> clone() const {return c10::make_intrusive<Stack>(stack_);}void merge(const c10::intrusive_ptr<Stack>& c) {for (auto& elem : c->stack_) {push(elem);}}
};

有幾件事要注意:

  • torch/custom_class.h是您需要使用自定義類擴(kuò)展 TorchScript 的標(biāo)頭。
  • 注意,無論何時(shí)使用自定義類的實(shí)例,我們都通過c10::intrusive_ptr&lt;&gt;的實(shí)例來實(shí)現(xiàn)。 將intrusive_ptr視為類似于std::shared_ptr的智能指針。 使用此智能指針的原因是為了確保在語(yǔ)言(C ++,Python 和 TorchScript)之間對(duì)對(duì)象實(shí)例進(jìn)行一致的生命周期管理。
  • 注意的第二件事是用戶定義的類必須繼承自torch::jit::CustomClassHolder。 這確保了所有設(shè)置都可以處理前面提到的生命周期管理系統(tǒng)。

現(xiàn)在讓我們看一下如何使該類對(duì) TorchScript 可見,該過程稱為_綁定_該類:

// Notice a few things:
// - We pass the class to be registered as a template parameter to
//   `torch::jit::class_`. In this instance, we've passed the
//   specialization of the Stack class ``Stack<std::string>``.
//   In general, you cannot register a non-specialized template
//   class. For non-templated classes, you can just pass the
//   class name directly as the template parameter.
// - The single parameter to ``torch::jit::class_()`` is a
//   string indicating the name of the class. This is the name
//   the class will appear as in both Python and TorchScript.
//   For example, our Stack class would appear as ``torch.classes.Stack``.
static auto testStack =torch::jit::class_<Stack<std::string>>("Stack")// The following line registers the contructor of our Stack// class that takes a single `std::vector<std::string>` argument,// i.e. it exposes the C++ method `Stack(std::vector<T> init)`.// Currently, we do not support registering overloaded// constructors, so for now you can only `def()` one instance of// `torch::jit::init`..def(torch::jit::init<std::vector<std::string>>())// The next line registers a stateless (i.e. no captures) C++ lambda// function as a method. Note that a lambda function must take a// `c10::intrusive_ptr<YourClass>` (or some const/ref version of that)// as the first argument. Other arguments can be whatever you want..def("top", [](const c10::intrusive_ptr<Stack<std::string>>& self) {return self->stack_.back();})// The following four lines expose methods of the Stack<std::string>// class as-is. `torch::jit::class_` will automatically examine the// argument and return types of the passed-in method pointers and// expose these to Python and TorchScript accordingly. Finally, notice// that we must take the *address* of the fully-qualified method name,// i.e. use the unary `&` operator, due to C++ typing rules..def("push", &Stack<std::string>::push).def("pop", &Stack<std::string>::pop).def("clone", &Stack<std::string>::clone).def("merge", &Stack<std::string>::merge);

使用 CMake 將示例構(gòu)建為 C ++項(xiàng)目

現(xiàn)在,我們將使用 CMake 構(gòu)建系統(tǒng)來構(gòu)建上述 C ++代碼。 首先,將到目前為止介紹的所有 C ++代碼放入class.cpp文件中。 然后,編寫一個(gè)簡(jiǎn)單的CMakeLists.txt文件并將其放置在同一目錄中。 CMakeLists.txt的外觀如下:

cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
project(custom_class)find_package(Torch REQUIRED)# Define our library target
add_library(custom_class SHARED class.cpp)
set(CMAKE_CXX_STANDARD 14)
# Link against LibTorch
target_link_libraries(custom_class "${TORCH_LIBRARIES}")

另外,創(chuàng)建一個(gè)build目錄。 您的文件樹應(yīng)如下所示:

custom_class_project/class.cppCMakeLists.txtbuild/

現(xiàn)在,要構(gòu)建項(xiàng)目,請(qǐng)繼續(xù)從 PyTorch 網(wǎng)站下載適當(dāng)?shù)?libtorch 二進(jìn)制文件。 將 zip 存檔解壓縮到某個(gè)位置(在項(xiàng)目目錄中可能很方便),并記下將其解壓縮到的路徑。 接下來,繼續(xù)調(diào)用 cmake,然后進(jìn)行構(gòu)建項(xiàng)目:

$ cd build
$ cmake -DCMAKE_PREFIX_PATH=/path/to/libtorch ..-- The C compiler identification is GNU 7.3.1-- The CXX compiler identification is GNU 7.3.1-- Check for working C compiler: /opt/rh/devtoolset-7/root/usr/bin/cc-- Check for working C compiler: /opt/rh/devtoolset-7/root/usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Check for working CXX compiler: /opt/rh/devtoolset-7/root/usr/bin/c++-- Check for working CXX compiler: /opt/rh/devtoolset-7/root/usr/bin/c++ -- works-- Detecting CXX compiler ABI info-- Detecting CXX compiler ABI info - done-- Detecting CXX compile features-- Detecting CXX compile features - done-- Looking for pthread.h-- Looking for pthread.h - found-- Looking for pthread_create-- Looking for pthread_create - not found-- Looking for pthread_create in pthreads-- Looking for pthread_create in pthreads - not found-- Looking for pthread_create in pthread-- Looking for pthread_create in pthread - found-- Found Threads: TRUE-- Found torch: /torchbind_tutorial/libtorch/lib/libtorch.so-- Configuring done-- Generating done-- Build files have been written to: /torchbind_tutorial/build
$ make -jScanning dependencies of target custom_class[ 50%] Building CXX object CMakeFiles/custom_class.dir/class.cpp.o[100%] Linking CXX shared library libcustom_class.so[100%] Built target custom_class

您會(huì)發(fā)現(xiàn),構(gòu)建目錄中現(xiàn)在有一個(gè)動(dòng)態(tài)庫(kù)文件。 在 Linux 上,它可能名為libcustom_class.so。 因此,文件樹應(yīng)如下所示:

custom_class_project/class.cppCMakeLists.txtbuild/libcustom_class.so

從 Python 和 TorchScript 使用 C ++類

現(xiàn)在我們已經(jīng)將我們的類及其注冊(cè)編譯為.so文件,我們可以將 <cite>.so</cite> 加載到 Python 中并進(jìn)行嘗試。 這是一個(gè)演示腳本的腳本:

import torch# `torch.classes.load_library()` allows you to pass the path to your .so file
# to load it in and make the custom C++ classes available to both Python and
# TorchScript
torch.classes.load_library("libcustom_class.so")
# You can query the loaded libraries like this:
print(torch.classes.loaded_libraries)
# prints {'/custom_class_project/build/libcustom_class.so'}# We can find and instantiate our custom C++ class in python by using the
# `torch.classes` namespace:
#
# This instantiation will invoke the Stack(std::vector<T> init) constructor
# we registered earlier
s = torch.classes.Stack(["foo", "bar"])# We can call methods in Python
s.push("pushed")
assert s.pop() == "pushed"# Returning and passing instances of custom classes works as you'd expect
s2 = s.clone()
s.merge(s2)
for expected in ["bar", "foo", "bar", "foo"]:assert s.pop() == expected# We can also use the class in TorchScript
# For now, we need to assign the class's type to a local in order to
# annotate the type on the TorchScript function. This may change
# in the future.
Stack = torch.classes.Stack@torch.jit.script
def do_stacks(s : Stack): # We can pass a custom class instance to TorchScripts2 = torch.classes.Stack(["hi", "mom"]) # We can instantiate the classs2.merge(s) # We can call a method on the classreturn s2.clone(), s2.top()  # We can also return instances of the class# from TorchScript function/methodsstack, top = do_stacks(torch.classes.Stack(["wow"]))
assert top == "wow"
for expected in ["wow", "mom", "hi"]:assert stack.pop() == expected

使用自定義類保存,加載和運(yùn)行 TorchScript 代碼

我們也可以在使用 libtorch 的 C ++進(jìn)程中使用自定義注冊(cè)的 C ++類。 舉例來說,讓我們定義一個(gè)簡(jiǎn)單的nn.Module,該實(shí)例在我們的 Stack 類上實(shí)例化并調(diào)用一個(gè)方法:

import torchtorch.classes.load_library('libcustom_class.so')class Foo(torch.nn.Module):def __init__(self):super().__init__()def forward(self, s : str) -> str:stack = torch.classes.Stack(["hi", "mom"])return stack.pop() + sscripted_foo = torch.jit.script(Foo())
print(scripted_foo.graph)scripted_foo.save('foo.pt')

我們文件系統(tǒng)中的foo.pt現(xiàn)在包含我們剛剛定義的序列化 TorchScript 程序。

現(xiàn)在,我們將定義一個(gè)新的 CMake 項(xiàng)目,以展示如何加載此模型及其所需的.so 文件。 有關(guān)如何執(zhí)行此操作的完整說明,請(qǐng)查看在 C ++教程中加載 TorchScript 模型。

與之前類似,讓我們創(chuàng)建一個(gè)包含以下內(nèi)容的文件結(jié)構(gòu):

cpp_inference_example/infer.cppCMakeLists.txtfoo.ptbuild/custom_class_project/class.cppCMakeLists.txtbuild/

請(qǐng)注意,我們已經(jīng)復(fù)制了序列化的foo.pt文件以及上面custom_class_project的源代碼樹。 我們將添加custom_class_project作為對(duì)此 C ++項(xiàng)目的依賴項(xiàng),以便我們可以將自定義類構(gòu)建到二進(jìn)制文件中。

讓我們用以下內(nèi)容填充infer.cpp

#include <torch/script.h>#include <iostream>
#include <memory>int main(int argc, const char* argv[]) {torch::jit::script::Module module;try {// Deserialize the ScriptModule from a file using torch::jit::load().module = torch::jit::load("foo.pt");}catch (const c10::Error& e) {std::cerr << "error loading the model\n";return -1;}std::vector<c10::IValue> inputs = {"foobarbaz"};auto output = module.forward(inputs).toString();std::cout << output->string() << std::endl;
}

同樣,讓我們??定義我們的 CMakeLists.txt 文件:

cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
project(infer)find_package(Torch REQUIRED)add_subdirectory(custom_class_project)# Define our library target
add_executable(infer infer.cpp)
set(CMAKE_CXX_STANDARD 14)
# Link against LibTorch
target_link_libraries(infer "${TORCH_LIBRARIES}")
# This is where we link in our libcustom_class code, making our
# custom class available in our binary.
target_link_libraries(infer -Wl,--no-as-needed custom_class)

您知道練習(xí):cd buildcmakemake

$ cd build
$ cmake -DCMAKE_PREFIX_PATH=/path/to/libtorch ..-- The C compiler identification is GNU 7.3.1-- The CXX compiler identification is GNU 7.3.1-- Check for working C compiler: /opt/rh/devtoolset-7/root/usr/bin/cc-- Check for working C compiler: /opt/rh/devtoolset-7/root/usr/bin/cc -- works-- Detecting C compiler ABI info-- Detecting C compiler ABI info - done-- Detecting C compile features-- Detecting C compile features - done-- Check for working CXX compiler: /opt/rh/devtoolset-7/root/usr/bin/c++-- Check for working CXX compiler: /opt/rh/devtoolset-7/root/usr/bin/c++ -- works-- Detecting CXX compiler ABI info-- Detecting CXX compiler ABI info - done-- Detecting CXX compile features-- Detecting CXX compile features - done-- Looking for pthread.h-- Looking for pthread.h - found-- Looking for pthread_create-- Looking for pthread_create - not found-- Looking for pthread_create in pthreads-- Looking for pthread_create in pthreads - not found-- Looking for pthread_create in pthread-- Looking for pthread_create in pthread - found-- Found Threads: TRUE-- Found torch: /local/miniconda3/lib/python3.7/site-packages/torch/lib/libtorch.so-- Configuring done-- Generating done-- Build files have been written to: /cpp_inference_example/build
$ make -jScanning dependencies of target custom_class[ 25%] Building CXX object custom_class_project/CMakeFiles/custom_class.dir/class.cpp.o[ 50%] Linking CXX shared library libcustom_class.so[ 50%] Built target custom_classScanning dependencies of target infer[ 75%] Building CXX object CMakeFiles/infer.dir/infer.cpp.o[100%] Linking CXX executable infer[100%] Built target infer

現(xiàn)在我們可以運(yùn)行令人興奮的 C ++二進(jìn)制文件:

$ ./infermomfoobarbaz

難以置信!

定義自定義 C ++類的序列化/反序列化方法

如果您嘗試將具有自定義綁定 C ++類的ScriptModule保存為屬性,則會(huì)出現(xiàn)以下錯(cuò)誤:

# export_attr.py
import torchtorch.classes.load_library('libcustom_class.so')class Foo(torch.nn.Module):def __init__(self):super().__init__()self.stack = torch.classes.Stack(["just", "testing"])def forward(self, s : str) -> str:return self.stack.pop() + sscripted_foo = torch.jit.script(Foo())scripted_foo.save('foo.pt')
$ python export_attr.py
RuntimeError: Cannot serialize custom bound C++ class __torch__.torch.classes.Stack. Please define serialization methods via torch::jit::pickle_ for this class. (pushIValueImpl at ../torch/csrc/jit/pickler.cpp:128)

這是因?yàn)?TorchScript 無法自動(dòng)找出 C ++類中保存的信息。 您必須手動(dòng)指定。 這樣做的方法是使用class_上的特殊def_pickle方法在類上定義__getstate____setstate__方法。

注意

TorchScript 中__getstate____setstate__的語(yǔ)義與 Python pickle 模塊的語(yǔ)義相同。 您可以有關(guān)如何使用這些方法的信息。

這是一個(gè)如何更新Stack類的注冊(cè)碼以包含序列化方法的示例:

static auto testStack =torch::jit::class_<Stack<std::string>>("Stack").def(torch::jit::init<std::vector<std::string>>()).def("top", [](const c10::intrusive_ptr<Stack<std::string>>& self) {return self->stack_.back();}).def("push", &Stack<std::string>::push).def("pop", &Stack<std::string>::pop).def("clone", &Stack<std::string>::clone).def("merge", &Stack<std::string>::merge)// class_<>::def_pickle allows you to define the serialization// and deserialization methods for your C++ class.// Currently, we only support passing stateless lambda functions// as arguments to def_pickle.def_pickle(// __getstate__// This function defines what data structure should be produced// when we serialize an instance of this class. The function// must take a single `self` argument, which is an intrusive_ptr// to the instance of the object. The function can return// any type that is supported as a return value of the TorchScript// custom operator API. In this instance, we've chosen to return// a std::vector<std::string> as the salient data to preserve// from the class.[](const c10::intrusive_ptr<Stack<std::string>>& self)-> std::vector<std::string> {return self->stack_;},// __setstate__// This function defines how to create a new instance of the C++// class when we are deserializing. The function must take a// single argument of the same type as the return value of// `__getstate__`. The function must return an intrusive_ptr// to a new instance of the C++ class, initialized however// you would like given the serialized state.[](std::vector<std::string> state)-> c10::intrusive_ptr<Stack<std::string>> {// A convenient way to instantiate an object and get an// intrusive_ptr to it is via `make_intrusive`. We use// that here to allocate an instance of Stack<std::string>// and call the single-argument std::vector<std::string>// constructor with the serialized state.return c10::make_intrusive<Stack<std::string>>(std::move(state));});

Note

我們采用與 pickle API 中的 pybind11 不同的方法。 pybind11 作為傳遞給class_::def()的特殊功能pybind11::pickle(),為此我們有一個(gè)單獨(dú)的方法def_pickle。 這是因?yàn)槊Qtorch::jit::pickle已經(jīng)被使用,我們不想引起混淆。

以這種方式定義(反)序列化行為后,腳本現(xiàn)在可以成功運(yùn)行:

import torchtorch.classes.load_library('libcustom_class.so')class Foo(torch.nn.Module):def __init__(self):super().__init__()self.stack = torch.classes.Stack(["just", "testing"])def forward(self, s : str) -> str:return self.stack.pop() + sscripted_foo = torch.jit.script(Foo())scripted_foo.save('foo.pt')
loaded = torch.jit.load('foo.pt')print(loaded.stack.pop())
$ python ../export_attr.py
testing

結(jié)論

本教程向您介紹了如何向 TorchScript(以及擴(kuò)展為 Python)公開 C ++類,如何注冊(cè)其方法,如何從 Python 和 TorchScript 使用該類以及如何使用該類保存和加載代碼以及運(yùn)行該代碼。 在獨(dú)立的 C ++過程中。 現(xiàn)在,您可以使用與第三方 C ++庫(kù)接口的 C ++類擴(kuò)展 TorchScript 模型,或?qū)崿F(xiàn)需要 Python,TorchScript 和 C ++之間的界線才能平滑融合的任何其他用例。

與往常一樣,如果您遇到任何問題或疑問,可以使用我們的論壇或 GitHub 問題進(jìn)行聯(lián)系。 另外,我們的常見問題解答(FAQ)頁(yè)面可能包含有用的信息。

http://www.risenshineclean.com/news/8407.html

相關(guān)文章:

  • wordpress虛擬主機(jī)企業(yè)關(guān)鍵詞優(yōu)化最新報(bào)價(jià)
  • 企業(yè)網(wǎng)站制作公司電話怎么申請(qǐng)域名建網(wǎng)站
  • 漳州網(wǎng)站建設(shè)seo研究學(xué)院
  • 佛山網(wǎng)站建設(shè) 天博網(wǎng)絡(luò)廣告策劃
  • 網(wǎng)站如何帶來流量鄭州網(wǎng)絡(luò)推廣排名
  • 網(wǎng)站策劃主要工作是什么百度在線掃題入口
  • 奶茶加盟網(wǎng)站建設(shè)外鏈網(wǎng)盤
  • 做網(wǎng)站專家一個(gè)網(wǎng)站推廣
  • 彩票網(wǎng)站開發(fā)風(fēng)險(xiǎn)中美關(guān)系最新消息
  • wordpress彈移動(dòng)端seo關(guān)鍵詞優(yōu)化
  • app軟件系統(tǒng)定制開發(fā)網(wǎng)站內(nèi)部鏈接優(yōu)化方法
  • 南京核酸最新通知重慶網(wǎng)站seo公司
  • 做張家界旅游網(wǎng)站多少錢全網(wǎng)營(yíng)銷有哪些平臺(tái)
  • 深圳app開發(fā)公司大概價(jià)格seo關(guān)鍵詞分析表
  • 游戲源代碼網(wǎng)站百度推廣電話號(hào)碼
  • 手機(jī)網(wǎng)站開發(fā)公司百度搜索引擎api
  • 自助網(wǎng)站模板平臺(tái)北大青鳥
  • asp網(wǎng)站banner修改市場(chǎng)營(yíng)銷計(jì)劃方案
  • 建設(shè) 大型電子商務(wù)網(wǎng)站杭州seo靠譜
  • 商城網(wǎng)站建設(shè)外貿(mào)平臺(tái)排名
  • 湛江市政工程建設(shè)公司網(wǎng)站美食軟文300范例
  • b2c電子商務(wù)網(wǎng)站的特點(diǎn)及類型2020年關(guān)鍵詞排名
  • 阿里云做網(wǎng)站可以嗎寧波seo資源
  • 做網(wǎng)站的榮譽(yù)證書網(wǎng)絡(luò)營(yíng)銷這個(gè)專業(yè)怎么樣
  • 幼兒園網(wǎng)站建設(shè)情況統(tǒng)計(jì)表西安優(yōu)化seo托管
  • 宿遷哪里做網(wǎng)站內(nèi)蒙古網(wǎng)站seo
  • 最權(quán)威的做網(wǎng)站設(shè)計(jì)公司價(jià)格搜索引擎營(yíng)銷ppt
  • 鄭州網(wǎng)站seo分析湖南seo推廣系統(tǒng)
  • dede 汽車網(wǎng)站谷歌競(jìng)價(jià)排名推廣公司
  • 東湖網(wǎng)站建設(shè)啥是網(wǎng)絡(luò)推廣