einsum_impl 0.1.1

Macro crate impl for `einsum`
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424

use core::fmt;
use std::{collections::HashMap, io::Write, process::{Command, Stdio}, vec, fmt::Display};

use proc_macro::{Span, TokenStream};
use proc_macro2::TokenStream as TokenStream2;
use syn::{parse::{self, Parse, ParseStream}, parse_macro_input, punctuated::Punctuated, spanned::Spanned, Error, Expr, ExprTuple, Ident, Member};
use quote::{format_ident, quote, ToTokens};

macro_rules! expect_token_err {
    ($token:expr, $types:expr) => {
        Err(Error::new($token.span(), format!("Expected a token of type(s) {}; got {:#?}", $types, $token)))
    };
}

macro_rules! err {
    ($($tt:tt),+) => {
        Error::new(Span::call_site().into(), format!($($tt),+))
    };
}

macro_rules! cast_expr {
    ($token:expr, $ty:tt) => {
        {
            match $token {
                Expr::$ty(expr) => Ok(expr),
                Expr::Group(group) => {
                    let expr = group.expr;
                    match *expr {
                        Expr::$ty(expr) => Ok(expr),
                        _ => expect_token_err!(expr, stringify!(Expr::$ty))
                    }
                },
                _ => expect_token_err!($token, stringify!(Expr::$ty))
            }
        }
    };
}

macro_rules! cast_expr_ref {
    ($token:expr, $ty:tt) => {
        {
            match $token {
                Expr::$ty(expr) => Ok(expr),
                Expr::Group(group) => {
                    match &*group.expr {
                        Expr::$ty(expr) => Ok(expr),
                        _ => expect_token_err!(group.expr, stringify!(Expr::$ty))
                    }
                },
                _ => expect_token_err!($token, stringify!(Expr::$ty))
            }
        }
    };
}

fn expr_ident_string(expr: &Expr) -> Result<String, Error> {
    match expr {
        Expr::Path(path) => {
            Ok(path.path.segments
                .first()
                .ok_or(Error::new_spanned(expr, "Couldn't get first item of path for ident string"))?
                .ident.to_string()
            )
        }
        _ => expect_token_err!(expr, "Expr::Path"),
    }
}

#[derive(Debug)]
struct Mat {
    pub expr: Expr,
    pub axes: String,
}

impl Mat {
    pub fn from_expr(expr: Expr) -> Result<Self, Error> {
        let field = cast_expr!(expr, Field)?;

        let axes = if let Member::Named(ident) = &field.member {
            ident.to_string()
        } else {
            return expect_token_err!(field.member, "Member::Named")
        };

        let expr = *field.base;


        Ok(Self {
            expr,
            axes,
        })
    }
}

#[derive(Debug)]
struct Axis {
    char: char,
    size: usize,
    ident: Ident,
}

impl Axis {
    pub fn new(char: char, size: usize) -> Self {
        Self {
            char,
            size,
            ident: Ident::new(&format!("axis_{}", char), Span::call_site().into()),
        }
    }

}

impl ToTokens for Axis {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        self.ident.to_tokens(tokens);
    }
}

impl Display for Axis {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({})", self.char, self.size)
    }
}

fn parse_mat_tuple(tuple: ExprTuple) -> Result<Vec<Mat>, Error> {
    tuple.elems.into_iter().map(|x| Mat::from_expr(x)).collect::<Result<Vec<Mat>, Error>>()
}

#[derive(Debug)]
struct EinsumArgs {
    crate_expr: Expr,
    input: Vec<Mat>,
    output: Vec<Mat>,
    axes: HashMap<char, Axis>,
}

impl Parse for EinsumArgs {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let punct: Punctuated<ExprTuple, syn::token::Comma> = Punctuated::parse_terminated(input)?;
        let mut iter = punct.into_iter();
        let err = Error::new(input.span(), "Not enough args");
        let [crate_expr, input_expr, output_expr, dims_expr] = [
            iter.next().ok_or(err.clone())?,
            iter.next().ok_or(err.clone())?,
            iter.next().ok_or(err.clone())?,
            iter.next().ok_or(err)?
        ];

        Ok(Self {
            crate_expr: crate_expr.elems.first().ok_or(Error::new(crate_expr.span(), "Couldn't get first item of crate_expr"))?.clone(),
            input: parse_mat_tuple(input_expr)?,
            output: parse_mat_tuple(output_expr)?,
            axes: dims_expr.elems.iter().map(|x| {
                let x = match x {
                    Expr::Tuple(x) => x,
                    _ => return expect_token_err!(x, "Expr::Tuple")
                };
                let axis = expr_ident_string(&x.elems[0])?;

                let dim_expr = cast_expr_ref!(&x.elems[1], Lit)?;
                let dim = match &dim_expr.lit {
                    syn::Lit::Int(int) => int.base10_parse::<usize>()?,
                    _ => return Err(Error::new(dim_expr.lit.span(), format!("Expected an integer, got {:?}", dim_expr.lit)))
                };

                let char = axis.chars().next().ok_or(Error::new(input.span(), "Couldn't read axis chars"))?;
                Ok((char, Axis::new(char, dim)))
            }).collect::<Result<HashMap<_, _>, Error>>()?,
        })
    }
}


//https://optimized-einsum.readthedocs.io/en/stable/autosummary/opt_einsum.contract.ContractExpression.html#opt_einsum.contract.ContractExpression"


// Reference: einsum!(a.ij, b.jk => c.kj; a 1, b 2)
//              => ((a.ij, b.jk), (c.kj), ((a, 1), (b, 2)))

#[proc_macro]
pub fn einsum_impl(stream: TokenStream) -> TokenStream {
    println!("Start");
    let args = parse_macro_input!(stream);

    let res = handle_errors(do_einsum(&args));
    
    quote!{{ #res }}.into()
}

fn handle_errors(result: Result<TokenStream2, Error>) -> TokenStream2 {
    match result {
        Ok(res) => res,
        Err(err) => err.to_compile_error()
    }
}

fn do_einsum(args: &EinsumArgs) -> Result<TokenStream2, Error> {
    // Get the optimized contraction order.
    let opt = get_opt(&args)?;

    let EinsumArgs { crate_expr, input, output: _, axes: dims, .. } = args;

    let mut tokens: Vec<TokenStream2> = vec![];

    struct MatInfo {
        ident: Ident,
        axes: String,
        id: usize,
    }

    impl ToTokens for MatInfo {
        fn to_tokens(&self, tokens: &mut TokenStream2) {
            self.ident.to_tokens(tokens);
        }
    }

    let mut idents = vec![];
    let mut exprs = vec![];

    let mut mats = vec![];
    for (i, mat) in input.iter().enumerate() {
        let ident = Ident::new(&format!("mat_{}", i), mat.expr.span());
        let expr = &mat.expr;
        idents.push(ident.clone());
        exprs.push(expr);
        
        mats.push(MatInfo { ident, axes: mat.axes.clone(), id: i });
    }

    tokens.push(quote!{
        // Do this all on one line to avoid accidentally shadowing the variables.
    });

    let mut lhs = mats.iter().map(|x| x.id).collect::<Vec<usize>>();
    let mut out_dim = vec![];

    for (mut i, mut j, contraction) in opt {
        if i > j {
            std::mem::swap(&mut i, &mut j);
        }

        let out = MatInfo {
            ident: Ident::new(&format!("mat_{}", mats.len()), Span::call_site().into()),
            axes: contraction.split("->").nth(1)
                .ok_or(err!("Where is the second part of the contraction? Implicit contractions aren't allowed"))?
                .to_string(),
            id: mats.len(),
        };

        let mut dim_tuple = vec![];

        println!("Contraction: {}", contraction);
        println!("---");

        for axis in out.axes.chars() {
            let size = dims.get(&axis).expect(format!("Axis {} not found in dims", axis).as_str()).size;
            dim_tuple.push(quote! {
                #size,
            });
        }

        tokens.push(quote! {
            let mut #out = ndarray::Array::<T, _>::zeros((#(#dim_tuple)*));
        });

        mats.push(out);

        // The two matrices to contract
        let a = &mats[lhs.remove(i)];
        let b = &mats[lhs.remove(j - 1)];
        let out = &mats.last().unwrap();
        let out_axes = out.axes.chars().map(|x| dims.get(&x).expect("Internal error: no dim?"));
        out_dim = out.axes.chars().map(|x| dims.get(&x).expect("Internal error: no dim?").size).collect();

        lhs.push(out.id);

        // For usage inside quote!{}
        let a_axes = a.axes.chars().map(|x| dims.get(&x));
        let b_axes = b.axes.chars().map(|x| dims.get(&x));

        let mut all_axes: Vec<char> = vec![];

        for axis in (a.axes.clone() + &b.axes + &out.axes).chars() {
            if !all_axes.contains(&axis) {
                all_axes.push(axis);
            }   
        }

        // Now we actually do the math.

        // This is the inner body of the loop. We will build this,
        // then wrap it in the next loop, and so on.
        let mut body = quote! {
            #out[(#(#out_axes),*)] += #a[(#(#a_axes),*)] * #b[(#(#b_axes),*)];
        };

        // Reverse the iterator, since we are doing C ordering (as opposed to Fortran)
        // TODO: Support Fortran ordering
        for axis in all_axes.iter().rev() {
            let axis = dims.get(axis).expect("Internal error: no dim?");
            let size = axis.size;

            body = quote! {
                for #axis in 0..#size {
                    #body
                }
            }
        }

        tokens.push(body);
    }

    let out = &mats[lhs[0]];

    let mut input_generics_defs = vec![];
    let mut input_generics = vec![];
    for i in 0..idents.len() {
        let ident = format_ident!("I{}", i);
        input_generics.push(ident.clone());
        input_generics_defs.push(quote! {
            #ident: ndarray::Dimension
        });
    }

    let dim_len = out_dim.len();
    let input_index_tys = input.iter().map(|x| (0..x.axes.len()).map(|_| quote!{usize}).collect::<Vec<_>>()).collect::<Vec<_>>();

    let final_expr = quote! {
        // Use a function for type inference.
        #[inline]
        fn __einsum_impl<T: #crate_expr::ArrayNumericType, #(#input_generics_defs),*>
        (#(#idents: &ndarray::Array<T, #input_generics>),*) -> ndarray::Array<T, ndarray::Dim<[usize; #dim_len]>>
        where #((#(#input_index_tys),*): ndarray::NdIndex<#input_generics>),* {
            #(#tokens)*
            #out
        }
        __einsum_impl(#(&#exprs),*)
    };

    Ok(final_expr.into())
}

fn get_opt(args: &EinsumArgs) -> Result<Vec<(usize, usize, String)>, Error> {
    let EinsumArgs { input, output, axes: dims, .. } = args;
    let str_input = input.iter().map(|x| x.axes.clone()).collect::<Vec<String>>().join(",");
    let str_output = output.iter().map(|x| x.axes.clone()).collect::<Vec<String>>().join(",");
    let opt_einsum_input = format!("{str_input}->{str_output}");

    let mut dim_str = String::new();

    for mat in input {
        dim_str.push_str("(");
        for axis in mat.axes.chars() {
            let Some(axis) = dims.get(&axis) else {
                return Err(Error::new(Span::call_site().into(), format!("Axis {} not found in dims", axis)));
            };

            dim_str.push_str(format!("{},", axis.size).as_str());
        }
        dim_str.push_str("), ");
    }

    fn pyerr(pretext: &str) -> impl Fn(std::io::Error) -> Error {
        let pretext = pretext.to_string();
        move |err| Error::new(Span::call_site().into(), format!("{}: {}", pretext, err))
    }

    let py = Command::new("python")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(pyerr("Error while trying to spawn Python process"))?;

    let code = format!(r#"
import opt_einsum as oe
expr = oe.contract_expression("{opt_einsum_input}", {dim_str})
print("\n".join([";".join([str(contraction[0][0]), str(contraction[0][1]), contraction[2]]) for contraction in expr.contraction_list]))
"#);
    println!("{}", code);
    
    let mut stdin = py.stdin.as_ref().ok_or(err!("Couldn't get stdin for Python process"))?;
    stdin.write(code.as_bytes()).map_err(pyerr("Error while writing to Python process"))?;

    let output = py.wait_with_output()
        .map_err(pyerr("Couldn't wait on Python process"))?;

    if !output.status.success() {
        let code = output.status.code().unwrap_or(-1);
        let err = String::from_utf8(output.stderr).unwrap_or("Error while reading Python process stderr".to_string());
        let out = String::from_utf8(output.stdout).unwrap_or("Error while reading Python process stdout".to_string());
        return Err(err!("Python process failed with non-zero exit code: {}\nstdout:\n{}\nstderr: {}", code, err, out));
    }

    let out = String::from_utf8(
        output.stdout
    ).map_err(|x| Error::new(
        Span::call_site().into(),
        format!("Error while parsing Python output as utf8: {}", x)
    ))?;

    let mut list = Vec::new();

    println!("{}", out);

    let int_err = |err| Error::new(Span::call_site().into(), format!("Error while parsing integer from Python opt_einsum: {}", err));
    let not_enough_err = Error::new(Span::call_site().into(), "Not enough items in contraction list returned from Python opt_einsum");

    for line in out.lines() {
        let line = line.trim();

        let mut iter = line.split(";").peekable();
        while iter.peek().is_some() {
            list.push((
                iter.next().ok_or(not_enough_err.clone())?.parse().map_err(int_err)?,
                iter.next().ok_or(not_enough_err.clone())?.parse().map_err(int_err)?,
                iter.next().ok_or(not_enough_err.clone())?.to_string()
            ));
        }   
    }

    Ok(list)
}