requires_grad и вычислительный граф
Отслеживайте операции, чтобы вычислять их производные
«requires_grad и вычислительный граф» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Calculus, Handled For You
Training needs derivatives, but you never compute them by hand. PyTorch's autograd watches your math and works out every gradient for you. 🤖
Tensors Can Track Themselves
A tensor only earns gradients when you ask. Set requires_grad to true and PyTorch starts recording every operation done to it.
x = torch.tensor(2.0, requires_grad=True)What Gets Recorded
Each math step on a tracked tensor is logged as a node. Together these nodes form a computation graph describing how your result was built.
The Graph Is a Recipe
Think of the graph as a recipe: inputs at the top, operations in the middle, your final loss at the bottom. Autograd reads it backward to find gradients.
Built On the Fly
PyTorch uses a dynamic graph: it is created as your code runs, not ahead of time. Normal Python loops and ifs just work inside it.
Results Stay Connected
Any tensor made from a tracked one is also tracked. Here y remembers it came from x, so its grad_fn points back to that squaring step.
y = x ** 2
print(y.grad_fn)Leaves vs Computed Nodes
Tensors you create directly are leaf nodes. Tensors produced by operations are interior nodes that link back toward those leaves.
grad_fn Names the Step
Every computed tensor carries a grad_fn telling autograd which operation made it, like PowBackward or AddBackward. Leaves have no grad_fn.
No Tracking, No Graph
If a tensor has requires_grad false, autograd ignores it and builds no graph. That saves memory whenever you do not need gradients.
Why the Graph Matters
The graph is what makes the backward pass possible. Without this recorded history, PyTorch would have no way to know how the loss depends on each weight.
You Just Write Forward
The beauty is you only code the forward math. Autograd silently assembles the graph so the gradients are ready the moment you ask for them.
Quick Check
Recap
Set requires_grad and PyTorch records your math into a computation graph. That recorded history is what autograd later reads backward to find every gradient. ✨
Часто задаваемые вопросы
Урок «requires_grad и вычислительный граф» бесплатный?
Да — полный текст урока «requires_grad и вычислительный граф» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «requires_grad и вычислительный граф»?
Отслеживайте операции, чтобы вычислять их производные Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «requires_grad и вычислительный граф»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- requires_grad и вычислительный граф
- Вызовите backward(), чтобы получить градиенты
- Чтение и обнуление .grad
- torch.no_grad() для вывода