Deep Learning Academy · Урок

torch.no_grad() для вывода

Отключите отслеживание графа, чтобы сэкономить память

Урок 4 из 413 шагов

«torch.no_grad() для вывода» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Not Every Pass Needs Grads

You only need gradients while training. When you just want predictions, tracking the graph is wasted work, so PyTorch lets you turn it off. 🛑

Meet torch.no_grad

Wrap code in a torch.no_grad() block and autograd stops recording inside it. No graph is built, and no gradients are stored.

with torch.no_grad():
    preds = model(x)

Why Skip the Graph

Building the graph costs memory to remember every step for a backward pass that will never come. During inference that overhead is pure waste.

Faster and Lighter

Inside no_grad your forward pass uses less memory and runs a little faster. On big models this lets you fit larger batches when only predicting.

Outputs Are Detached

Tensors created inside the block have requires_grad false. They are plain results you can print, save, or turn into NumPy without complaint.

Use It for Evaluation

Validation and test loops should always run under no_grad. You are scoring the model, not training it, so there is no reason to track gradients.

with torch.no_grad():
    for x, y in val_loader:
        out = model(x)

Pair It With eval Mode

For inference, set model.eval() and wrap calls in no_grad together. eval fixes layers like dropout; no_grad stops the graph. They solve different problems.

It Is a Context Manager

no_grad only affects code inside the with block. Once you leave it, autograd switches tracking back on automatically for your next training step.

The decorator form

You can also tag a whole function with @torch.no_grad(). Every tensor op inside that function then runs without building a graph.

@torch.no_grad()
def predict(x):
    return model(x)

Detach for a Single Tensor

Need to free just one tensor from the graph instead of a whole block? Call .detach() on it to get a copy that carries no gradient history.

frozen = output.detach()

A Safe, Common Habit

Reach for no_grad any time you are not learning: inference, metrics, or saving outputs. It is a tiny change that quietly saves memory and speed.

Quick Check

Confirm when to use no_grad.

Recap

Wrap inference in torch.no_grad() to skip graph building, saving memory and time. Pair it with model.eval() whenever you predict instead of train. 🚀

Можно начать бесплатно

Изучай Python с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
30
Уроки
120

Часто задаваемые вопросы

Урок «torch.no_grad() для вывода» бесплатный?

Да — полный текст урока «torch.no_grad() для вывода» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.

Чему я научусь в уроке «torch.no_grad() для вывода»?

Отключите отслеживание графа, чтобы сэкономить память Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Deep Learning Academy?

Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «torch.no_grad() для вывода»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Deep Learning Academy?

Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. requires_grad и вычислительный граф
  2. Вызовите backward(), чтобы получить градиенты
  3. Чтение и обнуление .grad
  4. torch.no_grad() для вывода
← Назад к Deep Learning Academy