Inside Torch and Autograd: How Deep Learning Libraries Compute Gradients

Alex Wiltschko of Twitter walks through Lua Torch, then explains automatic differentiation and what separates modern deep learning frameworks.

LFLex Fridman主持 · Lex Fridman Podcast
频道
Lex Fridman Podcast
视频
57:15
阅读
7 分钟
原文
英语
在 YouTube 打开
往下滚动阅读时,视频会缩到右下角继续播放。字幕跟随阅读语言。
阅读语言共 1 种语言可读
这篇文章还没有简体中文译文,先显示英语原文。
摘要

30 秒看懂

In this Deep Learning School talk, Alex Wiltschko introduces Torch's tensors, GPU support and the nn package, then spends the second half on Twitter's Autograd library and the ideas behind it. He explains why reverse-mode automatic differentiation is the abstraction underneath all gradient-based learning, how just-in-time, static and ahead-of-time graph libraries differ, and why Torch's thin layer over C code appeals to people who want to reason about performance.

  1. 1Lua suits deep learning as a thin glue layerLuaJIT loops run at roughly the speed of C, the language is tiny, and it embeds easily in C programs.
  2. 2A Torch tensor is a view into shared memory, not a copy: slicing returns a new tensor with its own size, stride and offset, and writing to the slice overwrites the original data.
  3. 3Reverse-mode automatic differentiation is the abstraction behind gradient-based learningForward mode would need one pass per parameter, which is hopeless for networks with millions of them.
  4. 4Autograd works by recording the trace of what your program actually did and walking it backwards, so ordinary if statements, loops and recursion differentiate without special handling.
  5. 5Libraries differ in the granularity at which you may compose models and when the graph is built: layers versus primitive operations, and static, just-in-time or ahead-of-time graphs.
  6. 6Wiltschko says people reach for Torch when they want to reason easily about performance, since extra compiler infrastructure makes slowness harder to diagnose.
全文

按章节阅读完整文稿

01

Torch brings NumPy-style array programming to a small, fast, embeddable language

Wiltschko says the first half of his talk will be practical and the second will dive into Torch Autograd and the concepts shared by all deep learning libraries. He credits the material to colleagues including Soumith Chintala, who he calls the czar of the Torch ecosystem, Hugo Larochelle and Ryan Adams. He describes Torch as an array programming language for Lua, much as NumPy is for Python, with the tensor as its core data type.

He explains why Lua is a reasonable choice. LuaJIT is unreasonably fast, with loops about as fast as C, so it works as convenient glue over high-performance C code. The language is defined by roughly 10,000 lines of C and can be learned in an afternoon, and it was designed to be embedded, which makes calling C libraries easy.

He points to Lua's use in places such as World of Warcraft quest scripting, Adobe Lightroom's interface, and Redis and nginx scripting. He relays the apocryphal story that Torch used Lua because a developer found Python frustrating on embedded chips. Torch also offers first-class interactive GPU computation, so moving data to the GPU means everything after that runs there without hand-written CUDA kernels.

Wiltschko adds that Torch has strong industry support from Twitter, Facebook AI Research and Nvidia but is not owned by any of them. He says research papers often come with high-quality Torch implementations, including image captioning, neural style transfer, sequence-to-sequence models and generative adversarial networks. The community is small compared with Python's, but strong in deep learning, and a Python programmer can become productive in Lua in about a week.

02

Torch is built for immediacy, minimal abstraction and tensors that are views into memory

Wiltschko says there is no silver bullet among deep learning libraries. In his rough positioning, TensorFlow is the largest and was engineered for industrial production, Theano for research, and Torch leans toward research, though Twitter has pulled it toward production. He says every piece of media coming into Twitter passes through a Torch model.

Torch's design tenets are immediacy with no compile step, imperative programming, and minimal abstraction, so that it usually takes only one or two jumps from a function's definition to the C code that runs. He then explains the memory model: a tensor is a view onto storage, defined by its size, stride and offset, laid out row-major. Selecting a row or column returns a new tensor with different stride and offset rather than copying data.

He demonstrates the consequence: fill a slice with a number and the original tensor's values are overwritten, because they share memory. The same operations work on GPU tensors after requiring the CUDA package.

03

The nn, optim and Autograd packages cover standard and unusual networks

Wiltschko sketches the pieces needed to train a network: data loading, training code, the network itself, a cost function and an optimizer. In Torch, the nn package lets you click together layers like Lego blocks inside a sequential container, with convolutions, nonlinearities, pooling and a log-softmax. It shines for linear architectures, has a small API for forward and backward passes, and moves a whole model to the GPU with one call.

For odd architectures, such as the complicated NLP model Richard Socher described the day before, nn becomes awkward. Twitter's Torch Autograd package handles this by letting you glue together pieces as small as addition and multiplication while still getting correct gradients.

The optim package supplies optimizers like stochastic gradient descent, Adagrad and Adadelta, using a functional style in which you pass in a function that evaluates the network and returns gradients. He warns that parameters must live in one linear tensor, so interacting networks need their parameters combined first.

04

Reverse-mode automatic differentiation is the hidden abstraction behind deep learning

Wiltschko asks the audience to appreciate stable abstractions in scientific computing, such as arrays from Fortran, linear algebra libraries and MATLAB-style collections of routines popularized by NumPy. Machine learning adds another one: automatic differentiation. He quotes a definition from Barak Pearlmutter that it mechanically calculates derivatives of functions expressed as computer programs, at machine precision and with complexity guarantees.

That separates it from finite differences, which are numerically unstable, and from symbolic differentiation, which can produce exploding expressions. He notes it has been rediscovered several times, with early descriptions by Wengert in 1964 and an implementation by Speelpenning in 1980, and that backpropagation is a special case. Fields like weather modeling and computational fluid dynamics have used it for decades with more sophisticated tools than machine learning has.

Machine learning uses reverse mode, he says, because forward mode is a bad idea. Using a small traced program, he shows that forward mode produces one derivative per pass, so a network with millions of parameters would need millions of evaluations. Reverse mode first evaluates the whole program, then walks backwards and obtains all the derivatives at once.

05

Autograd records your program as it runs, so control flow just works

Wiltschko shows that a whole neural network in Autograd is just a plain function for predictions and a loss, plus a call to `grad` on the loss function. Because `grad` is a higher-order function returning a gradient function, training is calling it and updating parameters with stochastic gradient descent. He compares the grad symbol to the nabla in mathematics.

Under the hood, Autograd replaces Torch functions with spy functions that record inputs and outputs while running them normally, building the computational graph just in time. It then walks that list backwards, looking up the partial derivatives that have been written for each Torch function. Since it only records arithmetic operations, it ignores control flow, so if statements, data-dependent for and while loops, and even recursion all differentiate correctly.

He also shows that you can override gradients. Taking the floor of a number has zero derivative almost everywhere, but you can define your own gradient to pass through it, which would matter for things like a differentiable JPEG-style compressor with a quantization step. Autograd provides an easy mechanism for plugging in such custom gradients.

06

Frameworks differ in granularity and graph type, and Autograd speeds up risky experiments

On how libraries compare, Wiltschko first looks at granularity. Some give you a fixed model, as in his "don't be a hero" regime, echoing Andrej Karpathy's advice to reuse others' networks. Middle libraries like nn, Keras and Lasagne let you assemble layers, while Autograd, Theano and TensorFlow let you compose primitive operations because their developers provide partial derivatives at that level.

A second axis is how graphs are built. Static graph libraries such as nn and Caffe fix the structure ahead of time, offering little optimization. Just-in-time libraries such as Autograd and Chainer allow any graph that can change per sample but have little room for compiler optimization, and ahead-of-time ones like TensorFlow and Theano hand a graph to a runtime that can optimize heavily but handles control flow awkwardly. He notes a pure data-flow graph has no room for control flow and mentions Cliff Click's sea-of-nodes representation as an unexplored option.

He shows a small network written three ways in Autograd: with primitive operations, with nn layers turned into functions, and with ready-made standard models. At Twitter, he says, Autograd has accelerated high-risk experiments such as a tree-structured loss that gives partial credit for guessing a related class. Models trained with it run in production, with no speed penalty at test time because the gradient machinery disappears.

07

Ideas from the autodiff world could still improve deep learning, and Q&A covers deployment

Wiltschko lists techniques from automatic differentiation that machine learning has not adopted yet. These include checkpointing, where you recompute cheap values like pointwise nonlinearities instead of storing them, mixing forward and reverse mode for unusual graph shapes, stencils for differentiating image-processing code, source-to-source transformation, and efficient higher-order gradients for Hessian-vector products. He closes by saying Lua and the tools are installable through Anaconda.

In the Q&A, he says Lua's visualization tools lag Python's, with Bokeh the best option. For production, he says calling Torch from C is easy, with no appreciable inference overhead because Autograd's training machinery is absent at test time, and Lua itself is tiny enough for embedded use. Asked why to choose Torch over Keras with TensorFlow, he says people reach for Torch when they want to reason about performance, since heavy compiler infrastructure makes problems harder to diagnose.

On serving models from Java or Python web stacks, he suggests serializing weights and loading them with a native library, or for feed-forward networks hand-writing the matrix multiplies. Twitter instead runs Lua virtual machines inside Java through JNI. He adds that the time to get predictions into a service is not their bottleneck, and he knows of no TensorFlow Serving equivalent for Torch.

同频道的其他文章

3:36:56EN → 简体中文
Lex Fridman· 2026年9月16日播客精神病学至今没有属于自己的青霉素主持 Lex Fridman历史学家 Andrew Scull 与 Lex Fridman 谈到,这门学科对症状有所缓解,但没有哪一种重大精神疾病真正被根治;过度自信的时候,代价要由病人来扛。Mental HealthPublic HealthNeuroscience
5:15:51EN → 简体中文
Lex Fridman· 2026年8月26日播客 · 2 人对谈DHH 没有亲手写一行 Omarchy Quattro 的代码嘉宾 DHH · 主持 Lex Fridman与 Lex Fridman 一次充满怀疑的对话过去十三个月后,Rails 的创造者讲述了 Opus 4.5、一群编码智能体(Agent)和一个一分钟的 Linux 安装器,如何结束了他一凿一凿手写 Ruby 的时代。编程智能体Vibe Coding智能体工程+3
3:12:58EN → 简体中文
Lex Fridman· 2026年8月12日播客 · 2 人对谈一个冷水澡,二十位冠军:Khabib Nurmagomedov 是如何炼成的嘉宾 Khabib Nurmagomedov · 主持 Lex Fridman在马哈奇卡拉的一间学校体育馆里,七十个人共用一个淋浴间,而且只有冷水。Martial ArtsCombat SportsCoaching+3
3:46:18EN → 简体中文
Lex Fridman· 2026年7月28日播客 · 2 人对谈抽掉奴隶制,就没有美国内战嘉宾 Gary Gallagher · 主持 Lex Fridman1860 年,美国奴隶主名下的奴隶价值,超过了全美所有铁路和工厂的总和。Political PhilosophyLeadershipHistory
3:51:47EN → 简体中文
Lex Fridman· 2026年6月30日播客 · 2 人对谈46% 的皇帝被暴力推翻,帝国照样延续下来嘉宾 Anthony Kaldellis · 主持 Lex Fridman历史学家 Anthony Kaldellis 与 Lex Fridman 一起走过 2200 年的罗马史,并主张我们所说的拜占庭,其实就是罗马本身。Political PhilosophyGeopoliticsLeadership
2:53:42EN → 简体中文
Lex Fridman· 2026年5月29日播客 · 2 人对谈月亮一直在下落,却总也落不到地球上嘉宾 Biggest Mysteries in Physics · 主持 Lex Fridman费米实验室(Fermilab)物理学家 Don Lincoln 在与 Lex Fridman 的对谈中说,物理学的历史就是一部统一的历史;反物质(antimatter)、暗能量(dark energy)和万物理论(theory of everything)依然远在我们能做的实验之外。Quantum MechanicsScience CommunicationPhilosophy of Science