Профилируйте узкое место
Найдите, куда уходят время и память
«Профилируйте узкое место» — бесплатный урок Deep Learning Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Deep Learning Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Deep Learning Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Profile First
Before optimizing, find out where time actually goes. Guessing wastes effort, while a quick profile shows you the real slow spots.
Two Common Bottlenecks
Training usually stalls in one of two places: the GPU compute doing math, or the data pipeline feeding it. Knowing which one matters.
Time It Crudely First
Start simple by timing a loop section with the clock. A rough perf_counter reading often points you to the right area in seconds.
import time
t = time.perf_counter()
# run one batch
print(time.perf_counter() - t)GPU Work Is Async
CUDA runs in the background, so naive timers lie. Call synchronize first to make sure the GPU has truly finished before you read the clock.
torch.cuda.synchronize()The Built-In Profiler
For real detail, use the torch.profiler context manager. It records how long every operation takes on both CPU and GPU.
from torch.profiler import profileWrap the Code to Profile
Run the part you care about inside a profile block. Choosing both CPU and CUDA activities captures the whole picture.
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
model(x)Read the Table
Print results sorted by cost to see the heaviest ops at the top. The key_averages table groups identical operations together.
print(prof.key_averages().table(sort_by='cuda_time_total'))Spot a Data Bottleneck
If the GPU often sits idle waiting, your DataLoader is too slow. More workers or cached data usually fixes that gap.
Spot a Compute Bottleneck
If one matmul or conv dominates the table, the limit is raw compute. Mixed precision or a smaller model is the lever to pull.
Watch Memory Too
The profiler can also report peak memory. Tracking profile_memory reveals which layers eat the most, guiding what to trim.
with profile(profile_memory=True) as prof:
model(x)Measure, Change, Re-Measure
Optimization is a loop: profile, make one change, then profile again. Trust numbers, not hunches, to confirm a fix actually helped.
Quick Check
Your GPU often sits idle between batches. What is the likely bottleneck?
Recap
Profile before you tune: synchronize for honest timings, use torch.profiler to find the heaviest ops, then fix data or compute and measure again. 🔍
Часто задаваемые вопросы
Урок «Профилируйте узкое место» бесплатный?
Да — полный текст урока «Профилируйте узкое место» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Deep Learning Academy, подпишись на CoddyKit PRO. Курс Deep Learning Academy содержит 4 уроков всего.
Чему я научусь в уроке «Профилируйте узкое место»?
Найдите, куда уходят время и память Ты практикуешь Deep Learning Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Deep Learning Academy?
Предыдущий опыт не требуется. Deep Learning Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Профилируйте узкое место»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Deep Learning Academy?
Да. Каждый урок Deep Learning Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Смешанная точность с autocast и GradScaler
- Накопление градиентов для больших пакетов
- Профилируйте узкое место
- Сократите использование памяти GPU