Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expected a value of type 'Tensor' for argument 'b' but instead found type 'Optional[Tensor]' #126648

Closed
adonnini opened this issue May 19, 2024 · 1 comment

Comments

@adonnini
Copy link

adonnini commented May 19, 2024

Hi,
When I attempt to process my model with torchscript in order to lower the model for use for inference by my Android application using pytorch mobile, execution fails.
Below you will find:

  1. Code. The failure occurs at
    emb = emb + self.temporal_embedding(input_time, input_weekday)

  2. Sample output for tensor_time and tensor_weekday where

           input_time = tensor_time
           input_weekday = tensor_weekday

  1. Traceback log

  2. Environment

Please note that the structure of the forward call may be awkward. I defined it in this way because I wanted to make sure that the forward parameters were tensors.

I tried to work around the issue of optional tensor in many of the ways suggested in results of searches about the topic. None of them worked. I may have (probably) made some mistakes.

Please also note that when I remove the torchscript code, model train and validation run without problems.

At this point, I am stuck. I would appreciate any suggestions on next steps. Please let me know if you need any information.

Thanks

Alex Donnini

CODE

      def forward(self, src, tensor_len, tensor_user, tensor_time, tensor_diff, tensor_duration, tensor_weekday) -> Tensor:
        emb = self.emb_loc(src)

        print("LocationPrediction - embed.py - AllEmbedding.forward - tensor_time - ",tensor_time)
        print("LocationPrediction - embed.py - AllEmbedding.forward - tensor_weekday - ",tensor_weekday)

        input_time = tensor_time
        input_weekday = tensor_weekday
        if self.if_include_time:
            if self.emb_type == "add":
                emb = emb + self.temporal_embedding(input_time, input_weekday)
            else:
                emb = torch.cat([emb, self.temporal_embedding(tensor_time, tensor_weekday)], dim=-1)
 
        if self.if_include_duration:
            emb = emb + self.emb_duration(tensor_duration)

        if self.if_pos_encoder:
            return self.pos_encoder(emb * math.sqrt(self.d_input))
        else:
            return self.dropout(emb)

SAMPLE tensor_time AND tensor_weekday OUTPUT

LocationPrediction - embed.py - TemporalEmbedding - forward - time -  tensor([[73, 73],
        [15, 15],
        [41, 41],
        [65, 65],
        [90, 90],
        [ 0,  0],
        [ 6,  6],
        [ 9,  9],
        [23, 23],
        [28, 28],
        [34, 34],
        [48, 48],
        [ 3,  3],
        [ 9,  9],
        [13, 13],
        [24, 24],
        [38, 38],
        [46, 46],
        [77, 77],
        [23, 23],
        [34, 34],
        [ 0, 81]])
LocationPrediction - embed.py - TemporalEmbedding - forward - weekday -  tensor([[3, 3],
        [4, 4],
        [4, 4],
        [4, 4],
        [4, 4],
        [5, 5],
        [5, 5],
        [5, 5],
        [5, 5],
        [5, 5],
        [5, 5],
        [5, 5],
        [6, 6],
        [6, 6],
        [6, 6],
        [6, 6],
        [6, 6],
        [6, 6],
        [6, 6],
        [0, 0],
        [0, 0],
        [0, 0]])

TRACEBACK LOG

Traceback (most recent call last):
  File "/home/adonnini1/Development/ContextQSourceCode/NeuralNetworks/LocationPrediction/main.py", line 68, in <module>
    res_single = single_run(train_loader, val_loader, test_loader, config, device, log_dir)
  File "/home/adonnini1/Development/ContextQSourceCode/NeuralNetworks/LocationPrediction/main.py", line 23, in single_run
    model, perf = get_trainedNets(config, model, train_loader, val_loader, device, log_dir)
  File "/home/adonnini1/Development/ContextQSourceCode/NeuralNetworks/LocationPrediction/utils/utils.py", line 47, in get_trainedNets
    best_model, performance = trainNet(config, model, train_loader, val_loader, device, log_dir=log_dir)
  File "/home/adonnini1/Development/ContextQSourceCode/NeuralNetworks/LocationPrediction/utils/train.py", line 520, in trainNet
    torchscript_model = torch.jit.script(model)
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_script.py", line 1338, in script
    return torch.jit._recursive.create_script_module(
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_recursive.py", line 558, in create_script_module
    return create_script_module_impl(nn_module, concrete_type, stubs_fn)
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_recursive.py", line 631, in create_script_module_impl
    script_module = torch.jit.RecursiveScriptModule._construct(cpp_module, init_fn)
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_script.py", line 647, in _construct
    init_fn(script_module)
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_recursive.py", line 607, in init_fn
    scripted = create_script_module_impl(
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_recursive.py", line 635, in create_script_module_impl
    create_methods_and_properties_from_stubs(
  File "/home/adonnini1/anaconda3/envs/executorch/lib/python3.10/site-packages/torch/jit/_recursive.py", line 467, in create_methods_and_properties_from_stubs
    concrete_type._create_methods_and_properties(
RuntimeError: 
Arguments for call are not valid.
The following variants are available:
  
  aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor:
  Expected a value of type 'Tensor' for argument 'other' but instead found type 'Optional[Tensor]'.
  
  aten::add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor:
  Expected a value of type 'number' for argument 'other' but instead found type 'Optional[Tensor]'.
  
  aten::add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!):
  Expected a value of type 'Tensor' for argument 'other' but instead found type 'Optional[Tensor]'.
  
  aten::add.Scalar_out(Tensor self, Scalar other, Scalar alpha=1, *, Tensor(a!) out) -> Tensor(a!):
  Expected a value of type 'number' for argument 'other' but instead found type 'Optional[Tensor]'.
  
  aten::add.t(t[] a, t[] b) -> t[]:
  Could not match type Tensor to List[t] in argument 'a': Cannot match List[t] to Tensor.
  
  aten::add.str(str a, str b) -> str:
  Expected a value of type 'str' for argument 'a' but instead found type 'Tensor'.
  
  aten::add.int(int a, int b) -> int:
  Expected a value of type 'int' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.complex(complex a, complex b) -> complex:
  Expected a value of type 'complex' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.float(float a, float b) -> float:
  Expected a value of type 'float' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.int_complex(int a, complex b) -> complex:
  Expected a value of type 'complex' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.complex_int(complex a, int b) -> complex:
  Expected a value of type 'int' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.float_complex(float a, complex b) -> complex:
  Expected a value of type 'complex' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.complex_float(complex a, float b) -> complex:
  Expected a value of type 'float' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.int_float(int a, float b) -> float:
  Expected a value of type 'float' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add.float_int(float a, int b) -> float:
  Expected a value of type 'int' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  aten::add(Scalar a, Scalar b) -> Scalar:
  Expected a value of type 'number' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  add(float a, Tensor b) -> Tensor:
  Expected a value of type 'Tensor' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  add(int a, Tensor b) -> Tensor:
  Expected a value of type 'Tensor' for argument 'b' but instead found type 'Optional[Tensor]'.
  
  add(complex a, Tensor b) -> Tensor:
  Expected a value of type 'Tensor' for argument 'b' but instead found type 'Optional[Tensor]'.

The original call is:
  File "/home/adonnini1/Development/ContextQSourceCode/NeuralNetworks/LocationPrediction/models/embed.py", line 219
                # tmp_tensor = torch.tensor(tmp_list)
                # emb = emb + tmp_tensor
                emb = emb + self.temporal_embedding(input_time, input_weekday)
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
                # emb = emb + self.temporal_embedding(context_dict["time"], context_dict["weekday"])
            else:

ENVIRONMENT

wget https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py
# For security purposes, please check the contents of collect_env.py before running it.
python collect_env.py
--2024-05-19 11:02:18--  https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.111.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 22068 (22K) [text/plain]
Saving to: ‘collect_env.py’

collect_env.py           100%[===============================>]  21.55K  --.-KB/s    in 0s      

2024-05-19 11:02:18 (224 MB/s) - ‘collect_env.py’ saved [22068/22068]

Collecting environment information...
PyTorch version: 2.3.0+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Debian GNU/Linux 12 (bookworm) (x86_64)
GCC version: (Debian 12.2.0-14) 12.2.0
Clang version: 14.0.6
CMake version: version 3.29.2
Libc version: glibc-2.36

Python version: 3.10.0 (default, Mar  3 2022, 09:58:08) [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-6.1.0-20-amd64-x86_64-with-glibc2.36
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               12
On-line CPU(s) list:                  0-11
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) W-11855M CPU @ 3.20GHz
CPU family:                           6
Model:                                141
Thread(s) per core:                   2
Core(s) per socket:                   6
Socket(s):                            1
Stepping:                             1
CPU(s) scaling MHz:                   60%
CPU max MHz:                          4900.0000
CPU min MHz:                          800.0000
BogoMIPS:                             6374.40
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 invpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
L1d cache:                            288 KiB (6 instances)
L1i cache:                            192 KiB (6 instances)
L2 cache:                             7.5 MiB (6 instances)
L3 cache:                             18 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] executorch==0.2.0a0+4f79832
[pip3] numpy==1.26.4
[pip3] optree==0.11.0
[pip3] pytorch-forecasting==1.0.0
[pip3] pytorch-lightning==2.2.1
[pip3] pytorch_optimizer==2.12.0
[pip3] torch==2.3.0+cpu
[pip3] torchaudio==2.3.0+cpu
[pip3] torchmetrics==1.3.2
[pip3] torchsr==1.0.4
[pip3] torchvision==0.18.0+cpu
[conda] executorch                0.2.0a0+4f79832          pypi_0    pypi
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] optree                    0.11.0                   pypi_0    pypi
[conda] torch                     2.3.0+cpu                pypi_0    pypi
[conda] torchaudio                2.3.0+cpu                pypi_0    pypi
[conda] torchsr                   1.0.4                    pypi_0    pypi
[conda] torchvision               0.18.0+cpu               pypi_0    pypi
@adonnini
Copy link
Author

Hi, I solved this issue by changing the code to:

        input_time = tensor_time
        input_weekday = tensor_weekday
        if self.if_include_time:
            if self.emb_type == "add":
                temporal_embedding_time_weekday = self.temporal_embedding(input_time, input_weekday)
                if temporal_embedding_time_weekday is not None:
                    emb = emb + temporal_embedding_time_weekday
            else:
                temporal_embedding_time_weekday = self.temporal_embedding(input_time, input_weekday)
                if temporal_embedding_time_weekday is not None:
                    emb = torch.cat([emb, temporal_embedding_time_weekday], dim=-1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant