Unit 2 of 9 · about 4 hours · explain, measure

Streams, asynchronous copies and honest timing

Every speedup claim in this section stands or falls on timing discipline. Async execution makes naive timers lie, and a hidden sync can pose as a slow kernel.

You'll be able to

  • Explain why GPU launches return before the work finishes and where PyTorch syncs for you.
  • Order wait_stream and record_stream correctly when a side stream consumes a default-stream tensor.
  • Time a GPU operation with events and show why a bare wall clock understates it.

Covers

Device streams, asynchronous copies and synchronizationAccidental synchronization and measurement error
1

Read

In this order, only the parts listed

0 of 3 done

  1. Asynchronous execution and CUDA streamsPyTorch - checkpointing, numerical accuracy and CUDA semantics

    Asynchronous execution: enqueue semantics, CUDA_LAUNCH_BLOCKING, and the Event timing example; CUDA streams: default-stream auto-sync, the wait_stream plus record_stream fix, and Stream semantics of backward passes

    Skip the TF32, GEMM precision, allocator-tuning and CUDA-graph sections here. They belong to later units.

  2. Pinned memory and asynchronous copiesPyTorch - checkpointing, numerical accuracy and CUDA semantics

    Best practices, Use pinned memory buffers: pin_memory, non_blocking copies, and overlapping transfer with compute

  3. Operations that force synchronizationPyTorch - reliability and performance recipes

    GPU specific optimizations, Avoid unnecessary CPU-GPU synchronization: the print, item, copy, nonzero and data-dependent-control-flow list

2

Focus on

  • Launches enqueue; they do not execute. On-device order is preserved per stream, and PyTorch syncs around CPU-GPU copies on the default stream only.
  • Side streams get no automatic safety. The consumer stream waits on the producer with wait_stream, and the tensor records its new stream with record_stream so its memory is not reused early.
  • non_blocking=True is a request, not a command. From pageable host memory the copy still syncs; pin the source first.
  • Backward follows forward stream placement. Grads produced under a side-stream backward must be consumed in the same stream context or after an explicit wait.
Common mistakes · 3
  • Timing with time.perf_counter and no sync, then reporting the result as kernel time. You timed the launch, not the work.
  • Calling .item(), printing a CUDA tensor, or branching on one inside the timed region. Each forces a sync and the stall gets billed to the wrong line.
  • Assuming default-stream safety extends to side streams. In the docs example, sum on a side stream may start before normal_ finishes on the default stream. The side stream must wait_stream on the default stream, and record_stream protects the tensor if it is freed while the side stream still uses it.
3

Try it yourself

Closed-book, before checking anything

On a CUDA GPU, warm up, then time a fp32 matmul both ways: CUDA events around the op with a synchronize before reading, versus a bare perf_counter around the launch. The matmul is , about 17.2 GFLOP, so the event time is a few milliseconds at most (4.1 ms on an RTX 3050 6 GB), while the bare clock reads microseconds (0.007 ms there) because it measures enqueue only. Exact numbers depend on hardware; the size of the gap is the assertion.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.An Event-timed matmul reports 4.1 ms while a bare wall clock reports 0.007 ms. Which is the kernel time and why?Answer

    The Event time. Launches are asynchronous, so the bare clock measures enqueue only. Events plus a synchronize measure the queued work.

  2. 2.Data comes from pageable host memory with .to(device, non_blocking=True). Is the copy asynchronous?Answer

    Effectively no. Asynchronous host-to-device copies need pinned source memory, so set pin_memory=True in the loader first.

  3. 3.loss.backward() runs under torch.cuda.stream(s). Where may the .grad tensors be consumed?Answer

    Inside the same stream context, or after the consuming stream waits on s. Using them on the default stream without a wait is unsafe in current PyTorch.

  4. 4.Which of print(t), t.item() and t.to('cpu') force a host sync for a CUDA tensor t?Answer

    All three. Each needs the values or the transfer finished on the host before Python continues.

You're done when

Your two-way timing shows the enqueue gap on your GPU, and you can point at the sync in any snippet that prints, copies, or branches on a CUDA tensor.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 7 more in the section
  • PyTorch - reliability and performance recipesPyTorch · primary

    Use the Profiler, Automatic Mixed Precision, model loading and Benchmark recipes, then the Performance Tuning Guide. Apply each to one compact model from an earlier section and keep a CPU fallback when CUDA is unavailable.

  • PyTorch - checkpointing, numerical accuracy and CUDA semanticsPyTorch · required

    Use the official user-guide entries for torch.utils.checkpoint, numerical accuracy, CUDA semantics, reproducibility and serialization. Predict memory categories before measuring and define resume equivalence before running.

Also in this section

  • PyTorch - compiler troubleshootingPyTorch · required

    Read graph breaks, guards, recompilations and logging. Compile one stable fragment, intentionally trigger a graph break or recompilation, inspect it, and compare eager and compiled outputs and gradients.

  • Deep Learning Training DebuggerRoadmap-Final · reference

    Use the failure-injection, measurement and evidence rules as the deeper standard. The full Tier 2 project is a later route and is not added to this stage milestone.

  • TensorTonic - mixed-precision memory and transformer FLOPsTensorTonic · support

    Solve only Mixed-Precision Training Memory Accountant and Transformer Training FLOP Estimator. Reconcile both with the compact model's profiler and document every included and excluded term.

  • Learn PyTorch - profiler walkthroughDaniel Bourke · optional

    Use notebook 10 only if the official profiler route remains unclear. Transfer the relevant annotations into the compact model instead of keeping the tutorial code.

  • TrenTorch - precision, checkpointing and resumeTrenTorch · support

    Solve Loss Scaling, FP16/BF16 Representable Range, Gradient Checkpointing and Resume-from-checkpoint in NumPy, then reproduce each behavior with the PyTorch API in the compact model.

  • Python os - `os.replace`Python Software Foundation · reference

    Read os.replace for the atomic-rename step of checkpoint writes: save to a temp file in the same directory, flush and fsync, then replace the final name.

  • Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support

    Read Appendix B, Reduced Precision Models and Mixed-Precision Training, for why float16 training underflows and what fp32 primary weights and loss scaling fix.