Call custom functions by jit in C++

I have created the following class and saved scripted_module and loaded in C++ API by:

    torch::jit::script::Module module;
    module = torch::jit::load("");

Now, the question is how can I call func from C++?

import torch
import torch.nn as nn

class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()

    def get_rand(self):
        return torch.randint(0, 2, size=[1])

    def forward(self):
    def func(self):
        done = self.get_rand()
        print (done)

scripted_module = torch.jit.script(MyModule())
1 Like

Does this answer help?

1 Like

Also just FYI @torch.jit.ignore functions cannot be exported, if you do"") you’ll get

Traceback (most recent call last):
  File "../", line 196, in <module>'')
  File "/home/pytorch/torch/jit/", line 1621, in save
    return*args, **kwargs)
Could not export Python function call 'get_rand'. Remove calls to Python functions before export. Did you forget add @script or @script_method annotation? If this is a nn.ModuleList, add it to __constants__:
  File "../", line 192
    def func(self):
        done = self.get_rand()
               ~~~~~~~~~~~~~ <--- HERE
        print (done)

Which is expected behavior (since saved models are expected to run without a Python runtime attached)

1 Like

Thanks, this worked.

Yes, I faced a similar example and as you mentioned it makes sense.