Eternal Two-Language Problem | nsf.name

nsf.name

Eternal Two-Language Problem

(Approx. 7 min read)

Thoughts on the two-language problem and why no solution so far really works.


For a long time it’s been well understood that there are essentially two types of languages one can use for scientific programming:

  • Lower-level languages, where more direct attention is needed to the specifics of how the computation is done and speed is the reward (Fortran, C/C++, Rust)
  • Higher-level languages, where more direct attention can be spent on just doing your task at hand and implementation speed is the reward (Python, R, MATLAB)

Development speed is usually the top priority, so higher-level languages being slow isn’t necessarily a bad thing, but it really hurts when you need to scale up your operations. Thus the traditionally flawed approach is to try and take the lower-level languages, implement your slowest parts in them, and then bridge to the higher-level languages. This is usually insufficient, as often linking the two languages requires itself a substantial amount of programming skill (your average Python user will be unable to figure out how to use the C FFI), and even when you do, you’re often bound by the speed of the slower language anyways (like a global interpreter lock, garbage collection, etc).

In an attempt to overcome this problem there have been a few more approaches explored in recent years. I would like to explain why these tools are still fundamentally inadequate and why the problem resists any form of clean solution.

Julia’s Leaky Abstractions

Julia is an up-and-coming programming language that primarily focuses on making scientific programming both fast and expressive. I think Julia gets lots of things right, and even gave it a test drive for my own thesis as a potential implementation language, but there are still a lot of areas in which Julia is severely lacking; it is not a solution to the two-language problem now and never will be.

For example, to even know why you should pick Julia over Python or R, you would need to know that its strength is that it uses LLVM to compile the code efficiently into something native, and then run it. Most of the Julia ecosystem is tailored around its GPU offloading1; you had better get an understanding of what it actually is that the GPU does well. Since Julia uses multiple (not dynamic) dispatch, you’d better get a good understanding of what distinguishes it from object-oriented or functional paradigms of programming to use it effectively. That’s a whole lot of computer science background knowledge many students and definitely quite a lot of scientists will not know before going in!

The issue with Julia is that its abstractions are leaky: they expose too many details for domain-focused scientists to use them without having to also be burdened with an enormous amount of computer science. Consider the relatively common Python case of wanting to return different types:

1def process(x):
2    return x * 2 if x > 0 else "zero"
3	# Python doesn't care about this type

In Julia, you would write this code instead:

1function process(x)
2    x > 0 ? x * 2 : "zero" 
3end # this always returns Union{Int64, String}

The difference between them is that Julia’s implementation will be much slower. Julia promises faster performance but only as long as you understand that the compiler must get concrete return types otherwise performance falls off a cliff. No such cognitive barrier exists in other languages, and it’s deeply unintuitive to most non-programmers!

Here’s another common failure case of Julia: global variables. Even though this is typically bad practice, people use them all the time in notebooks and exploratory programming, making this a serious shortcoming. In Python you simply write:

1x = 5
2def foo(): return x + 1  # fine

However in Julia you write this and then experience mysterious slowdowns everywhere:

1x = 5
2foo() = x + 1  # type-unstable and slow
3const x = 5    # now it's fine but you have to know to do this

Since mutable globals are extremely useful, most people will simply eat the performance cost, making Julia effectively slower Python with worse libraries in some of the most common use-case for high-level languages in scientific programming without being a low-level language either (no language with garbage collection can be one, and Julia’s startup times are embarrassingly slow).

maturin and Meeting In The Middle

The Julia approach of trying to be a middle language between high-level and low-level is, in my opinion, fundamentally flawed. Non-programmers are forced to learn a bunch of computer science background to be effective in a language that’s going to force substantial amounts of relearning to be productive in again, and programmers suffer from the language not being low-level enough for their high-performance needs.

What about meeting in the middle instead? I think the better solution is to just improve the ability for languages to meet in the middle. The high-level languages are that way because they’re serving an important purpose; the goal shouldn’t be to bolt on low-level features, or bolt on high-level features to a low-level language, but rather making it easier to use them together.

Enter maturin and pyo3, two projects that solve this issue (at least for Rust + Python). You simply write normal Rust, annotate it for Python, and it just works:

 1use pyo3::prelude::*;
 2
 3#[pyfunction]
 4fn sum_squares_parallel(py: Python<'_>, arr: Vec<f64>) -> f64 {
 5    py.allow_threads(|| {
 6        arr.par_iter().map(|x| x * x).sum()  // rayon!
 7    })
 8}
 9
10#[pymodule]
11fn mylib(m: &Bound<'_, PyModule>) -> PyResult<()> {
12    m.add_function(wrap_pyfunction!(sum_squares, m)?)?;
13    Ok(())
14}

Finally, in Python, it looks like any normal module and everything is beautiful:

1from somelib import sum_squares
2sum_squares([1.0, 2.0, 3.0])  # it just works

The best part is that it’s pleasingly parallel because there’s no GIL, and this approach lets you immediately take advantage of two incredible library ecosystems. A Julia implementation might, in theory, be equivalent in speed, but the beauty of Python is that numba also exists:

1from numba import njit
2import numpy as np
3
4@njit
5def sum_squares(arr):
6    s = 0.0
7    for x in arr:
8        s += x * x
9    return s	

Now you’ve got Julia native speed without needing to drop to it!

Again, all of this has come from a lot of coordinated effort on the Python side (performance improvements, immutable structures like frozendict() and soon frozenset() that can cross FFI easier, removing the GIL) and on the Rust side (creating really good libraries and build systems to automate linking pain). Nowadays you just pick the language that’s better at the domain you want, and none of them have to be some kludge between two things they’re not. Two different mindsets for two different languages lets each succeed at one thing and do it well.

Intractability of the Problem

What does the unreasonable effectiveness of the meet-in-the-middle approach teach us? It teaches us that the two-language problem has more to do with semantics than with implementation.

You can’t specify low-level details in a high-level context without fundamentally making it less accessible to those without that background, and there’s no amount of sorcery that will make a high-level language fast regardless of what you’re doing in it. At some level, you have to understand how the computer really works to get performance. Julia is yet another attempt to do this in the same way that numba and numpy are, but suffers from the additional effect of imposing cognitive and performance burdens everywhere, in all code, all the time, whereas in Python it’s purely localized to FFI boundaries and specific, optimized blocks.

The only decent solution is to make the languages meet more in the middle rather than becoming the middle. Julia tries to become the missing middle language and fails. Being able to seamlessly hand off from a high-level environment to something low-level for a brief period is more like most real workloads (where the high-level language is merely glue connecting a bunch of lower-level libraries), which is why Python and R being slow is negligible for most people in the first place.

Perhaps another, more viable approach is to make expressions which slow down performance fundamentally impossible to express, but even then adoption remains an uphill battle. Modern Fortran is headed in this direction and it shows a lot of promise, especially in the LFortran compiler, which makes Fortran interactive and GPU-friendly. Julia has a lot to learn from it.


  1. Admittedly I make fun of Julia a lot in this article but it is really good at this. Rust and Fortran are both catching up fast in this department, so Julia really is only winning by being first rather than being the best. ↩︎

<< Previous Post

|

Next Post >>

#Essay #Programming