r/MachineLearning • Researcher • Dec 04 '21

Discussion [Discussion] Why are Einstein Sum Notations not popular in ML? They changed my life.

I recently discovered `torch.einsum` and now I am mad at every friend, mentor, acquaintance for not telling me about it.

They are just way more intuitive and can handle most operations that I would want to do with tensors so elegantly. No more of having to remember which way is axis=0, No more of having to remember which way is dim=1 and no more of remembering so many numpy and torch functions only to misuse np.unsqueeze and torch.expand_dims.

It takes only 30 mins or so to learn the notation and become somewhat proficient but then you are sorted for life.

What are the arguments for and against using einstein notations for everything? Will I be writing code which others find difficult to understand? Kindly pitch in your thoughts and theories on why are they so seldom used when they are one-size-fit-all.

546 Upvotes

114 comments sorted by

34

u/noobbodyjourney Researcher Dec 04 '21

Since this post has gotten some traction, I want to add a resource for those who don't use it yet but are intrigued by how ppl are reacting.

Check this link out for a tutorial on how to use torch.einsum:

https://rockt.github.io/2018/04/30/einsum

Disclaimer: I don't know the author nor have I checked if all the content in the blogpost is accurate but it does seem famous.

22

u/LappenX Dec 04 '21 edited Oct 04 '23

crush heavy worry aware alive station workable run entertain simplistic this message was mass deleted/edited with redact.dev

3

u/[deleted] Dec 04 '21

Why is this better? Seems like the resulting code will be less readable than a single einsum call.

6

u/M4mb0 Dec 04 '21 edited Dec 04 '21

Ok, let's consider a simple example: Implement the quadratic function f(x) = xᵀ⋅A⋅x in a properly vectorized manner, i.e.

  • if x is a d-vector you should return a scalar.

  • if x is n×d matrix you should return a n-vector

  • if x is a m×n×d tensor it should return a m×n matrix

  • ....

With einsum, this is trivial:einsum("...d, ...e, de -> ...", x, x, A). How would you implement it?

→ More replies (3)

-1

u/noobbodyjourney Researcher Dec 04 '21

What to do when we are in torch land dear sire?

17

u/LappenX Dec 04 '21 edited Oct 04 '23

frame uppity saw lock combative chief dolls whole existence rain this message was mass deleted/edited with redact.dev

→ More replies (4)

4

u/theWizz991 Dec 05 '21

If you're looking for even faster einsum, try this library

https://pypi.org/project/opt-einsum/

1

u/noobbodyjourney Researcher Dec 05 '21

Woah, thanks a lot. I didn't know about this.

2

u/robml Dec 05 '21

I love you for this post

1

u/noobbodyjourney Researcher Dec 05 '21

<3

1

u/robml Dec 05 '21

Btw have you worked much with TF? I do most mine on PyTorch wanted to see if you had any insights

1

u/noobbodyjourney Researcher Dec 05 '21

I too have almost exclusively used only pytorch for my research. Couple of years ago, the popular opinion was that pytorch is more friendly for research mainly because of the pythonic way of writing code whereas tensorflow was more reliable and appropriate when production and scalability was the main concern. I am not so sure if that is still the case though.

→ More replies (1)

207

u/txgrizfan Dec 04 '21

I strongly agree that Einstein notation should be more widely taught, it is such an elegant way to generalize most linear algebra operations and I would love to see it used more often.

One concern that I'm sure a lot of people have is that if they use einsum, their code won't be readable like you mentioned. It might also be the case that the einsum operation isn't as optimized as the special-purpose operations provided by numpy/torch/others, although I haven't benchmarked it myself.

81

u/LurkingSinus Dec 04 '21

As a matematician I couldn't agree less about the readability. An einsum call describes exactly which operation is done, super readable and exact.

40

u/MuonManLaserJab Dec 04 '21

Yeah; there's readability in the sense that you already know how to read something, and readability in the sense that you can read it easily once you have practice.

→ More replies (6)

9

u/Deto Dec 04 '21

If you write code at a company than readability for other engineers is very very important.

10

u/AuspiciousApple Dec 04 '21

As a matematician I couldn't agree less about the readability.

That makes sense, but your experience might be different from a lot of people in the ML space that aren't mathematicians by training.

56

u/farmingvillein Dec 04 '21

One concern that I'm sure a lot of people have is that if they use einsum, their code won't be readable like you mentioned.

Einsum makes it way too easy to make your code look like it is auditioning for a obfuscated C competition.

It doesn't have to, but it is a tool that tends to encourage--or at least enable--bad habits.

Of course, there are different philosophies about this broader issue in coding:

  • a) leave tools like this and encourage people to use them the right way, vs. discourage usage of tools that can be misused, and,

  • b) whether responsibility for grokkable code sits more so with the reader or the writer.

Without engaging in a software philosophical flame war, what we can objectively say is that the trendline has been toward the latter for both (a) and (b). Einsum sits much more so in the former category.

18

u/Appropriate_Ant_4629 Dec 05 '21

Einsum makes it way too easy to make your code look like it is auditioning for a obfuscated C competition.

I think this package:

https://github.com/arogozhnikov/einops

makes Einstein notation even cleaner, and also works the same with Pytorch, Numpy Jax, Tensorflow, etc; which makes switching frameworks less obfuscated.

25

u/[deleted] Dec 04 '21

how so? It tells you the shapes up front, how is that not more readable than a string of transposes and matmuls?

41

u/farmingvillein Dec 04 '21 edited Dec 04 '21

Several things:

As a general rule, more steps shown directly are simply more explicit. More explicit is--within the common modern school of thought re:software--generally superior to less, as it 1) typically encourages the writer to be very step-by-step formulaic with their thoughts, decreasing errors and 2) typically makes it easier for the reader to follow along, step-by-step.

2)

Modern software design has pushed very heavily against complex operations in a single line.

And if you do want to put a complex operation on a single line, modern software design pushes towards a named function to be used.

2a)

Relatedly, modern software design pushes for operations to be named idiomatically, so that the function name itself guides you on what is happening.

torch.einsum means that almost anything could be happening to the tensors/matrices.

torch.sum tells you that a summation is occurring somewhere (and then you can read the params to learn more, if desired).

2b)

Idiomatic code, by extension, tends to make for easier CR, and thus more effective software development.


(But wait!  Can I prove all of the above?  Offhand, no--most of the above is very difficult to prove.  But I think it *does* represent general consensus thought...whether or not that consensus is correct or not.)

To be super clear, I'm *not* saying that you're wrong if you think the opposite, nor am I saying that this trendline in modern thought around software is inherently true and correct (although I will admit I have a personal bias toward it).

What I am trying to say is that consensus thought helps explain why you don't see einsum dominating the ML software world.
→ More replies (11)

4

u/mrtransisteur Dec 04 '21

Telling if it's a good notation is kind of like an NP problem: a certain easiness-level to check correctness while reading & potentially not-so-easy to check correctness while coming up w/ the solution/encoding. But that means that if generating it is easy, reading it (for the same type of reader) should be, too :)

And I do believe einops solves the readability issue imo.

To this day I pretty much can never tell when einsum is applicable to some transformation I am envisioning - and if it is, the right way to write it out.. - but I often get it right on the first try with einops, so I think that demonstrates that it has a really commonsense design, and since hardness(checking) < hardness(generating), easy to check while reading also :)

4

u/M4mb0 Dec 04 '21

It might also be the case that the einsum operation isn't as optimized as the special-purpose operations provided by numpy/torch/others, although I haven't benchmarked it myself.

For many people who are not careful about order of operations, an optimizing Einsum (not torch unfortunately) might be an order of magnitude faster in some scenarios.

53

u/yiyuen Dec 04 '21

This could be said of math and it's implementations in programming in general. You know how many computer science students I've met that said they don't want to learn (multi)linear algebra but want to learn machine learning? My friend, it's all linear algebra.

22

u/cderwin15 Dec 04 '21

Sure, but as someone who wanted to learn multilinear algebra and was not interested in ML for a very long time, I've never seen a tensor product (or any nontrivial multilinear algebra) in ML except for maybe some pretty niche and very theoretical scenarios (like manifold learning, topological data science, etc.)

8

u/yiyuen Dec 04 '21

I should've said basic multilinear algebra. Obviously, there's a lot to be learned--too much unless you plan to do research in more niche topics as your said. The problem is a lot of people are even scared by the word "tensor" and don't even mathematically know what contractions are for example. Yet, they want to jump into programming models right away.

11

u/111llI0__-__0Ill111 Dec 04 '21

Im not sure why ML is sold as a programmer or software eng field, numerical computation is quite different from that and is more on the mathematical side

6

u/comradeswitch Dec 04 '21

If to you the entirety of machine learning is neural models, then yeah you're gonna need some working knowledge of tensor arithmetic...But there's a lot more than that out there.

Once again, there's a world outside tensorflow/torch/etc. and neural models and there's more than enough topics to keep a serious academic busy for lifetimes without dealing with any multilinear algebra beyond linear algebra.

6

u/st-memory Dec 05 '21

"Tensor" is rightfully a scary word in its mathematical context. However, this is almost never the context in ML where everything is called a tensor nowadays.

7

u/significantfadge Dec 04 '21

I wish it was all linear algebra

I got polynomial equations in my research. I have been calculating Gröbner bases for months

2

u/yellowcake12345 Dec 05 '21

what area of ML requires you to compute Gröbner bases?

4

u/significantfadge Dec 05 '21

Causal ML with structural equation models

→ More replies (1)

2

u/NFTrot Dec 04 '21

I wonder if computer science degrees are going to change to include more linear algebra going forward.

2

u/JohnnyB03 Dec 04 '21

If you look at Stanford’s curriculum, EE and CS have a ton of linear algebra.

2

u/[deleted] Dec 05 '21

If you had a EE-flavored CS degree such as typical ECE programs, you probably got exposed to a lot of continuous math, perhaps things like signal processing such are very LA-heavy.

12

u/Megatron_McLargeHuge Dec 04 '21

For a while the gradient wasn't implemented in Theano, and then when it was they were much slower than alternate expressions. I'm not sure if that's still an issue in recent tf or torch but a lot of people probably tried them and gave up.

Their main value is with true 3D and higher data so they weren't as valuable back when 95% of the published work was on static images.

12

u/johnnymo1 Dec 04 '21 edited Dec 05 '21

When I started my current job, I got to implement some pairwise Mahalanobis distance computations with almost just one line of einsum (modulo a couple shape operations first). It was beautiful.

Then I wrote about 12 lines of comments to explain the 1 line of code in case any poor soul has to tinker with it.

9

u/dogs_like_me Dec 04 '21

I think they're becoming a bit more widely known courtesy of some examples in the einops docs.

Similarly, I feel like there's a lot of opportunity for tensor network representations/operators in ML.

6

u/jesuslop Dec 04 '21

4

u/dogs_like_me Dec 04 '21

Clearly ML needs more cross-pollination with physics

5

u/CaptMartelo Dec 04 '21

As a physicist, I fully agree. Simply minimizing a cost function is equivalent to the principle of minimum energy. And that is just the start.

4

u/serrations_ Dec 05 '21

Computational Physics here and i also agree.

9

u/HjalmarLucius Dec 04 '21

I would argue it's because it shines best when dimensions are named (e.g. `torch.randn(5,4,3,names=('batch', 'width', 'channels')` - and very few libs support that apart from xarray (pytorch's version is half baked at best). Without named dims you still need to which dim is where (either by memory or convention).

3

u/NowanIlfideme Dec 05 '21

Wait, torch has named dims now?

3

u/jiminiminimini Dec 05 '21

Yes but it is still a work in progress. Shouldn't be used in production code.

2

u/HjalmarLucius Dec 05 '21

Yeah, I would argue that named tensors are best done with a pretty much entirely revamped function namespace. View etc no longer has any meaning (as it's done automatically behind the scenes) and all matmul operations are best done with dot.

Currently, only about half the functions work with named tensors so I've made my own for a project I'm working on.

→ More replies (2)
→ More replies (1)

8

u/float16 Dec 04 '21

I use it quite a lot, but it took me quite a bit of reading before I was confident in what I was doing.

For context, I've only taken one linear algebra course, where no one ever said "tensor".

13

u/cderwin15 Dec 04 '21

tensors in ML and tensors in math are entirely unrelated

8

u/float16 Dec 04 '21

You exaggerate.

18

u/cderwin15 Dec 04 '21

No exaggeration. Tensors in ML are just a confusing way to talk about multidimensional arrays when we load them into gpu memory. Tensors in math are vector spaces through which multilinear maps factor. There's no relation.

14

u/float16 Dec 04 '21

Use the standard basis, then a multidimensional array represents a multilinear map. Is that not a relation?

12

u/cderwin15 Dec 04 '21

I see your point. Yes, a multidimensional array can be interpreted as an element of a tensor product (or equivalently as a multilinear map). I guess this is most likely where the name comes from, probably doing large multilinear computations in coordinates. That said, in the context of ML I've never seen multidimensional arrays interpreted this way, and tbh don't think that interpretation would be useful outside the narrow context high performance computing. But yes, I admit there is a narrow relation between the two.

→ More replies (2)

12

u/LurkingSinus Dec 04 '21

torch.einsum is THE shit.

5

u/[deleted] Dec 04 '21 edited Dec 04 '21

I learned einstein notation fully on my Bachelor in Physics, and then when my (ML) boss said "this part is complex, let's redo it in einsum" I got a small hearth attack. Turns out torch don't even support div/curl/grad or Levi-Civita symbol, or other vector identities.

Which makes einsum really neat and clean; "readability" seems to be one concern for people here but I disagree. Because einsum rules are not that (math) complex or anything, learning it is not such an big (math) hurdle than the bootcamp people having a crash course in linear algebra and learning basic matrix/vector operations, or even learning the basic if/for/while/lambda functions and scoping in programming.

Even with it being more than 8 years ago I ever did it before, just a quick read was enough to remember/reuse it again.

5

u/Ulfgardleo Dec 04 '21

there is a speed argument to be made- unlike matrix operations, there are no high end tuned implementations of the general einsum. Most often, they will use some algorithm that determines the decomposition of einsum into those primitives - but those algorithms are often difficult or incompletely implemented. your code might run pretty slow and you have no idea, why.

1

u/themiro Dec 05 '21

Don't know why this isn't higher. Most people who are very serious about this stuff know about einsum, but it is hard to translate to CUDA accelerated ops.

5

u/[deleted] Dec 05 '21

Just one thing people advocating for "modern SWE practices" are missing: "modern SWE practitioners" already have a really hard time dealing with terse vectorized and functional programming anyway, and would probably vouch for loops everywhere they could. We aren't dealing with traditional SWE, we are ML practitioners and learning/sharing notations for the sake of brevity is a mean to reduce cognitive overload (as in maths in general).

So using or not einsum is just a matter of going further on one of two diverging directions - not that any of them is particularly right over the other.

2

u/EternityForest Dec 05 '21

I think math is different from pretty much anything else people do, other than maybe mechanical design.

Non math programmers just don't deal much with anything other than discrete timesteps.

The idea of even something basic like X+Y=10 while X/Y=7 is completely and utterly different from anything I've seen on real projects.

Nothing about it has anything to do with steps or time, it's a statement of something that's always true. In programming, things are purely feedforward and can't affect previous work except as a separate iteration.

Here, the first equation requires X get smaller if Y gets bigger, the second requires they stay in a constant ratio.... and it all happens at the same exact time. There's no "first step" to code here, the first step is "solve the math".

It's almost like tightrope walking or juggling, it's not just a "big project" like washing 100 dishes, it's something where no part of the task is like anything you can even imagine if you haven't done something similar.

11

u/Thorusss Dec 04 '21

Einstein notation was taught in Bachelors Physics Degree in Germany, and is indeed very much liked.

1

u/NegatioNZor Dec 05 '21 edited Dec 05 '21

One thing I haven't seen mentioned is potential speedups that come because of einsum. Generally add operations are many cycles quicker than mul operations, and I'm pretty sure einsum in torch preallocates only once, which also helps.

Sometimes it feels quite terse to read through, but it's potentially a real timesaver when you're trying to optimize in my experience. Would love to hear other people's experience with this.

1

u/noobbodyjourney Researcher Dec 05 '21

This is an interesting take that einsum may win against the normal torch operations in certain cases.

24

u/Icarium-Lifestealer Dec 04 '21

As a physicist I think ESN is stupid. It saves a couple of characters in exchange for being very implicit. Writing down which variables you're summing over is hardly too much to ask (leaving the bounds implicit is fine).

12

u/[deleted] Dec 04 '21

I understood OP to be talking about numpy.einsum, not Einstein notation on paper.

10

u/Rioghasarig Dec 04 '21

I think you're underestimating the importance of notation. Just a few weeks for my Numerical Differential equations class I was working on a problem involving computing a particularly complicated Taylor expansion. I couldn't for the life of me wrap my head around the calculations until I switched to using Einstein notation. Then the pattern became much easier to see.

So yeah I'd say it definitely has it's uses.

23

u/uoftsuxalot Dec 04 '21

I don’t think he was talking about leaving out the summation notation. In comp sci people generally write out vector equations, because working with numpy it’s all vectors. It gets hard to keep track of dimensions and which axis to sum on, especially when the rank of the tensor becomes large

9

u/Icarium-Lifestealer Dec 04 '21

Leaving out the summation sign and variables you sum over (implicitly summing over all duplicate indices) is the difference between standard sum notation and Einstein sum notation.

12

u/uoftsuxalot Dec 04 '21

You know I’m something of a physicist myself. Again the issue is that computer scientists use vector equations. The biggest advantage of Einstein summation convention is the use of indicies, to differentiate between the different axis’

7

u/CaptMartelo Dec 04 '21

Einstein notation was key in studying relativity and electrodynamics. Simplified much of the work and was way lighter to write

3

u/nonconvexopt Dec 05 '21

I use einsum whenever I can since I have learn it. I guess many people don't use it cause they don' know about it.

5

u/Appropriate_Ant_4629 Dec 04 '21 edited Dec 05 '21

It takes only 30 mins or so to learn the notation and become somewhat proficient but then you are sorted for life.

.... Will I be writing code which others find difficult to understand?

Yes....

... but as you pointed out ... 30 minutes later they'll be thanking you!!!

8

u/TheDeviousPanda Researcher Dec 04 '21

To be honest a lot of torch code looks like someone just tried random arguments until they worked, and you don't really need to understand more than that, so if you know all the torch functions there's no problem with code readability. I agree that for more complex operations torch.einsum should absolutely be preferred, but when I read torch code that uses einsum I have to actually try and see what is going on, vs not using einsum I can just look at the functions and know what is going on. I think that's the biggest reason einsum hasn't really become as popular as it could.

2

u/serrations_ Dec 05 '21

Oh yeah i learned this in my General Relativity class and have just been using it causally when coding or traversing and using n-dimensional arrays in my head. Its probably not widespread for the same reason certain Clifford Algebras arent - we havent gushed about it enough.

 

So gush forward my fellow programmers. Gush to your hearts content. You fucking gushers

2

u/serge_cell Dec 05 '21

It's kind of the same problem as why functional languages did not replace imperative. More elegant, short and less bug prone but more difficult to understand. On the gripping hand they are not more computationally efficient in low-level implementation (cuda/openmp/vector ops)

2

u/cthorrez Dec 06 '21

I think a lot of it is inertia. It isn't taught in many university ML courses so most people don't become familiarized with it.

3

u/VordeMan Dec 04 '21

IMO einsum and pandas are both deals with the devil. You make things really complicated to understand and grok, and in return conveying a few specific things that are usually medium-difficult become trivial.

Broadly I agree with /u/farmingvillein above: sometimes using these tools are just perfect and beautiful, the problem is that you start having these fanboys that insist on using it everywhere possible, not just everywhere useful.

2

u/synonymous1964 Dec 04 '21

I like using it a lot for its elegance, but i’m not sure if the time complexity of common operations (matmul, trace, etc) is affected in any way?

1

u/svnhddbst Dec 05 '21

I am pretty new to both data science and pytorch/linear algebra, when I looked at the einsum documentation I basically just said "looks like physics formulas or something. no clues to be had hear." so you'd spend more time explaining what those do, than actually explaining the analysis it was used in.

1

u/[deleted] Dec 05 '21

Isn't it xTx?

1

u/andreichiffa Professor Dec 07 '21

Redundancy for error-proofing.

I can't tell how many times I've stared in equations in papers that made no sense because an output index was forgotten or omitted because being "natural" and mentioned somewhere in text around page 59 of supplementary materials.

Same thing for code.

1

u/TrickyRedditName Dec 14 '21

Here’s another best practice, that combined with einops, helps make code very clear: include the dimensions in the variable name!

For example if you have a tensor that represents a batch of images , you can name it like batch_b_h_w

Now wherever this variable occurs you immediately know its shape. It’s useful to me because I find that when trying to understand what’s going on in a piece of code, I have to step into the debugger and check the shapes of tensors.

1

u/MrAcurite Researcher Dec 04 '21

Just looked it up

Holy fucking shit...

1

u/harponen Dec 04 '21

Most ML scientists/ practitioners don't have a background in relativity so I guess it seems somewhat alien... but I agree 100% with you.

0

u/scraper01 Dec 04 '21

Can see it happening, but there should first be explicit agreement on the operands shape. Anything beyond dim 1 (for example) should still be handled explicitly.