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

How to compute Atan2 for tensors? #2622

Open
cryscan opened this issue Nov 16, 2024 · 1 comment
Open

How to compute Atan2 for tensors? #2622

cryscan opened this issue Nov 16, 2024 · 1 comment

Comments

@cryscan
Copy link

cryscan commented Nov 16, 2024

I am trying to implement DeepPhase in candle but I am struggling figuring out how to calculate the phase angles from two tensors using atan2 operation.

@cryscan
Copy link
Author

cryscan commented Nov 16, 2024

Okay I found out that we can implement custom ops. So is this correct?

use candle_core::{CpuStorage, CustomOp2, Layout, Result, Shape, Tensor};

pub struct Atan2;

impl CustomOp2 for Atan2 {
    fn name(&self) -> &'static str {
        "atan2"
    }

    fn cpu_fwd(
        &self,
        s1: &CpuStorage,
        l1: &Layout,
        s2: &CpuStorage,
        l2: &Layout,
    ) -> Result<(CpuStorage, Shape)> {
        if l1.shape() != l2.shape() {
            candle_core::bail!("operands must have the same shape");
        }

        let s1 = match l1.contiguous_offsets() {
            None => candle_core::bail!("input has to be contiguous"),
            Some((o1, o2)) => &s1.as_slice::<f32>()?[o1..o2],
        };
        let s2 = match l2.contiguous_offsets() {
            None => candle_core::bail!("input has to be contiguous"),
            Some((o1, o2)) => &s2.as_slice::<f32>()?[o1..o2],
        };

        let dst = itertools::zip_eq(s1, s2)
            .map(|(&y, &x)| y.atan2(x))
            .collect();
        let storage = candle_core::WithDType::to_cpu_storage_owned(dst);
        Ok((storage, l1.shape().clone()))
    }

    fn bwd(
        &self,
        y: &Tensor,
        x: &Tensor,
        _: &Tensor,
        _: &Tensor,
    ) -> Result<(Option<Tensor>, Option<Tensor>)> {
        let d = (x.sqr()? + y.sqr()?)?;
        Ok((Some(x.div(&d)?), Some(y.div(&d)?.neg()?))))
    }
}

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