R markdown preview for latex equations sometimes works and then knitr pdf generation fails.

This sometimes seems to happen for me if there are blank lines in equation or some strangenesses in RMardown latex document e.g.:

```
---
title: "test"
output: pdf_document
---
Works in Rstudio but not in knitr:
$$
\tilde a^\tilde b
$$
Works in both:
$$
{\tilde a}^{\tilde b}
$$
```

These differences are tricky to debug, The question is: what engine is RStudio using to generate the previews? Can I use the exact same engine with knitr to generate the pdf output? If so how?

Many thanks.