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

Add support for conversion of torch scalar to taichi scalar #8373

Open
obust opened this issue Oct 18, 2023 · 1 comment
Open

Add support for conversion of torch scalar to taichi scalar #8373

obust opened this issue Oct 18, 2023 · 1 comment
Assignees
Labels
feature request Suggest an idea on this project

Comments

@obust
Copy link

obust commented Oct 18, 2023

Torch scalars are 0-dimensional tensors.

Currently taichi cannot convert a zero dimensional tensor (e.g. torch.tensor(2, dtype=torch.int32)) to taichi scalar (e.g. ti.int32).

Example

Suppose you have this fill kernel:

import torch
import taichi as ti

@ti.kernel
def fill(out: ti.types.ndarray(dtype=ti.int32), value: ti.int32):
    for I in ti.grouped(out):
        out[I] = value

We can pass a python scalar

out = torch.empty((10,), dtype=torch.int32)
value = 2  # python scalar
fill(out, value)
tensor([2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=torch.int32)

We can also pass a numpy scalar

out = np.empty((10,), dtype=np.int32)
value = np.int32(2)  # numpy scalar
fill(out, value)
array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2], dtype=int32)

but we cannot pass a torch scalar

out = torch.empty((10,), dtype=torch.int32)
value = torch.tensor(2, dtype=torch.int32)  # torch scalar
fill(out, value)
TaichiRuntimeTypeError: 
Argument 1 (type=<class 'torch.Tensor'>) cannot be converted into required type i32
@obust obust added the feature request Suggest an idea on this project label Oct 18, 2023
@github-project-automation github-project-automation bot moved this to Untriaged in Taichi Lang Oct 18, 2023
@jim19930609
Copy link
Contributor

As you just mentioned, "torch-scalar" is a "zero-dimension" tensor, so basically you still need to treat it as a Ndarray in Taichi:

import torch
import taichi as ti

ti.init(arch=ti.cpu)

@ti.kernel
def fill(out: ti.types.ndarray(), value: ti.types.ndarray()):
    for I in ti.grouped(out):
        out[I] = value[None]

out = torch.empty((10,), dtype=torch.int32)
value = torch.tensor(2, dtype=torch.int32)  # torch scalar
fill(out, value)

Try this out.

@jim19930609 jim19930609 moved this from Untriaged to Backlog in Taichi Lang Oct 20, 2023
@jim19930609 jim19930609 self-assigned this Oct 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Suggest an idea on this project
Projects
Status: Backlog
Development

No branches or pull requests

2 participants