# Can ChatGPT turn LaTeX equations into Python code?

ChatGPT seems to have good skills to turn equations into code. This opens the following question: can we use ChatGPT to turn the complicated LaTeX equations into Python code?

# What

Given an equation written in LaTeX, ChatGPT can convert it in Python. We test this premise with a simple exercise.

# Why

It is quite a powerfull concept. We can turn the theory from the publications into code and make it actionable.

# How

To quickly test the ChatGPT abilities to turn LaTeX equations into code we can set up a simple “experiment”.

On the one hand we take the multi-headed attention code from the well-known guide “The Annotated Transformer”:

On the other hand we prompt ChatGPT with the following sentence:

Can you write a Python code using PyTorch for the following equation
written in LaTeX: a = softmax(\frac{QK^T}{\sqrt{d_k}})V


after which the following code snippet is generated:

For convenience, the function was renamed to attention_chatgpt (originally it was named softmax_attention).

For testing purposes we randomly generate the input tensors Q, K and V:

Finally we compare the output tensors from both implementations to conclude they are close enough to be considered equal:

If this is something you like and would like to see similar content you could follow me on LinkedIn or Twitter. Additionally, you can subscribe to the mailing list below to get similar updates from time to time.

Tags:

Updated: