Julia and Python — Use Both!
There have lately been many articles comparing Julia and Python. The most common analysis is that Julia is the better language, but the Python ecosystem is far more mature. I agree with both these statements, but it is a false choice — use both.
In this writeup I would like to advocate for my favorite development environment: program in Julia and call Python libraries. This gives you access to all the wonderful value in the Python ecosystem, while writing code that runs 50x faster. The faster Julia code allows one to write CPU intensive code in a nice productive Python-like environment, instead of the pain and time required to develop Cython or C libraries.
Here is an example from my current work. I am developing new Language Model and Decoder technology for Speech Recognition. This code runs on the output of the Deep Learning models. I don’t want to develop a whole new Speech Recognizer, just the final stage. However, the Decoder must run fast — my code is doing an enormous search on the logits coming out of the DeepLearning models. Therefore, I am using Pytorch and HuggingFace models for the first stage of my recognizer, and writing the Decoder in Julia.
Below is my Julia code for accessing PyTorch and Huggingface.
using PyCallstruct HuggingFace
torch::PyCall.PyObject
transformers::PyCall.PyObject
datasets::PyCall.PyObject
soundfile::PyCall.PyObject function HuggingFace()
torch = PyCall.pyimport(“torch”)
transformers = PyCall.pyimport(“transformers”)
datasets = PyCall.pyimport(“datasets”)
soundfile = PyCall.pyimport(“soundfile”)
new(torch,transformers,datasets,soundfile)
end
end
Note how easily Julia interfaces to Python. Accessing the PyTorch module is as simple as
torch = PyCall.pyimport(“torch”)In this code I store all the Python and HuggingFace information in a HuggingFace struct. Outside of that code, the fact that it actually running Python and C is completely hidden. Everything is just a normal Julia value.
Here is a method using the HuggingFace struct:
load_model(hf::HuggingFace,
model_name=”facebook/wav2vec2-base-960h”)=
hf.transformers.Wav2Vec2CTCTokenizer.from_pretrained(model_name)The HuggingFace struct (hf) contains a reference to the HuggingFace transformers module, which contains the Wav2Vec2CTCTokenizer class with from_pretrained method. The returned PyTorch model object is just a Julia value from the point of view of Julia code.
Get Peter Wolf’s stories in your inbox
Join Medium for free to get updates from this writer.
Here are some more examples of Julia calling Pytorch code written in Python
load_dataset(hf::HuggingFace,dataset_name=”timit_asr”) = hf.datasets.load_dataset(dataset_name)device(hf::HuggingFace) = if hf.torch.cuda.is_available() hf.torch.device(“cuda:0”) else “cpu” end
Of course, duck typing also works with Python objects. No need to declare special types
id_to_phoneme(processor) = processor.tokenizer.decoderphoneme_to_id(processor) = processor.tokenizer.encoder
You can even use the equivalent of the Python ‘with’ (@pywith) operator on Julia code calling Python
text_path = "text"
speech_path = "file"function get_logits(hf::HuggingFace,model,processor,item)
speech, _ = hf.soundfile.read(item[speech_path])
input_values = processor(speech, return_tensors="pt",
sampling_rate=16000).input_values.to(device(hf))
@pywith hf.torch.no_grad() begin
logits=model(input_values["logits"].detach().to("cpu").numpy()[1,:,:]
return logsoftmax(logits,dims=2)
end
end
Note that the returned value ‘logits’ is just a normal Julia array. PyCall automatically converts numpy objects into standard Julia objects. The only important trick here is ‘[1,:,:]’. Python uses 0 based indexing, whereas Julia uses 1 based indexing.
Once we have logits in Julia, we can use the standard math library.
return logsoftmax(logits,dims=2)As many others have written, numerical processing is where Julia really shines. As fast as C, but a far more productive development environment with a REPL, Debugger, Garbage Collector, and powerful Multiple Dispatch. No need for libraries like numpy to speed things up, and no need to vectorize your code. Easy to read algorithmic code runs just as fast. Julia also has great support for profiling, finding and fixing bottlenecks
Here is a sample function for summing a set of log probabilities. It uses the log-sum-exp trick to avoid overflow (https://gregorygundersen.com/blog/2020/02/09/log-sum-exp/). Note how I can define a local one line function e() on line 2, and then broadcast it (e.) over the sequence (xs .- m), in which ‘- m’ is broadcast over xs. This avoids for-loops, and allows the backend to potentially optimize with fusion (https://julialang.org/blog/2017/01/moredots/). Yes, I could have written an even more compact version of this, but it would not have run any faster. You can set a breakpoint on any line of this code, and no C libraries are involved.
function logsumexp(xs)
e(x) = if x==-Inf 0.0 else exp(x) end
m=maximum(xs)
if m==-Inf
return -Inf
else
return m + log(sum(e.(xs .- m)))
end
endNo environment is perfect, but I gotta say… This combo is really nice! So next time you want to write some fast code, but use all the Python libraries you enjoy, please consider Julia calling Python.
Thank you
Peter










