Advanced Memory Management and Profiling with torch.memory

Advanced Memory Management and Profiling with torch.memory

A tensor’s shape describes the values you can address; it does not, by itself, describe how many bytes the process has requested. The basic payload size is the number of elements multiplied by the size of each element. A tensor with 1,000,000 float32 values needs 4,000,000 bytes for its values, before allocator bookkeeping or other overhead.

import torch

x = torch.empty((1000, 1000), dtype=torch.float32)

print(x.numel())          # 1000000
print(x.element_size())   # 4
print(x.numel() * x.element_size())  # 4000000

That calculation gives the size of the tensor’s logical contents. PyTorch tensors also carry metadata: shape, dtype, device, strides, and a reference to storage. A view can have a different shape and strides while sharing the original tensor’s storage, so counting each tensor’s logical bytes can count the same memory more than once.

base = torch.empty((1000, 1000), device="cuda")
view = base[:, :100]

print(base.shape, base.stride())
print(view.shape, view.stride())
print(base.untyped_storage().nbytes())
print(view.untyped_storage().nbytes())

Here, view contains fewer addressable elements, but it still refers to the storage owned by base. The stride tells PyTorch how to move through that storage to find the next element in each dimension. Operations such as slicing often create views; operations that need a new layout, such as contiguous() on a non-contiguous tensor, may allocate new storage.

Allocation also depends on the device. CPU tensors use the CPU allocator. CUDA tensors use a caching allocator: when a tensor is released, its block may remain reserved by PyTorch for reuse rather than being returned immediately to the CUDA driver. Consequently, memory reported as reserved can exceed memory currently occupied by live tensors. Tools that show device-wide usage may also include CUDA context costs and allocations made by libraries outside PyTorch’s tensor allocator.

if torch.cuda.is_available():
    torch.cuda.synchronize()

    print("live tensor allocations:",
          torch.cuda.memory_allocated())
    print("memory held by PyTorch's allocator:",
          torch.cuda.memory_reserved())

For CUDA measurements, synchronization matters because kernels and memory operations are asynchronous with respect to Python. Without it, a measurement may occur before queued work has finished. memory_allocated() reports memory occupied by tensors managed by the CUDA allocator; memory_reserved() includes cached blocks available for later allocations. Releasing a tensor can reduce the first number without changing the second.

Measuring memory use across a computation

A useful measurement is not just the memory in use after an operation, but the highest point reached while it ran. PyTorch records CUDA peak usage separately from current usage. Synchronize before reading these counters so that queued work has completed, and reset the peak counter immediately before the part of the computation you want to measure.

if torch.cuda.is_available():
    device = torch.device("cuda")
    x = torch.randn(4096, 4096, device=device)

    torch.cuda.synchronize(device)
    torch.cuda.reset_peak_memory_stats(device)

    y = x @ x
    torch.cuda.synchronize(device)

    print("current:", torch.cuda.memory_allocated(device))
    print("peak:", torch.cuda.max_memory_allocated(device))
    print("reserved:", torch.cuda.memory_reserved(device))

max_memory_allocated() reports the largest amount of memory occupied by live tensors since the last reset. The current allocation can be much smaller: temporary tensors may have been created and released during the matrix multiplication. reset_peak_memory_stats() resets the recorded peak; it does not free tensors or return cached blocks to the driver.

For a sequence of operations, record a baseline and then measure each stage. Keeping the measurements in bytes makes them easy to compare with the allocator’s counters; dividing by 1024 ** 2 displays mebibytes.

def report_cuda_memory(label, device="cuda"):
    torch.cuda.synchronize(device)
    allocated = torch.cuda.memory_allocated(device)
    peak = torch.cuda.max_memory_allocated(device)
    reserved = torch.cuda.memory_reserved(device)

    mib = 1024 ** 2
    print(
        f"{label:16s}"
        f" allocated={allocated / mib:8.1f} MiB"
        f" peak={peak / mib:8.1f} MiB"
        f" reserved={reserved / mib:8.1f} MiB"
    )

device = torch.device("cuda")
model = torch.nn.Linear(4096, 4096).to(device)
inputs = torch.randn(256, 4096, device=device)
target = torch.randn(256, 4096, device=device)

torch.cuda.reset_peak_memory_stats(device)
report_cuda_memory("before forward", device)

prediction = model(inputs)
report_cuda_memory("after forward", device)

loss = (prediction - target).square().mean()
loss.backward()
report_cuda_memory("after backward", device)

The backward pass often has a higher peak than the forward pass because autograd retains intermediate values needed to calculate gradients. The model’s parameters, the input, the output, and saved intermediates all contribute to live allocation. A measurement after a stage shows the current allocation at that point, while the peak column includes any temporary allocations made since the reset.

To measure one iteration independently, reset the peak counter at its start and make sure the previous iteration’s tensors are no longer referenced. Otherwise, the recorded peak includes both the old live allocations and the new work.

optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

for step in range(3):
    optimizer.zero_grad(set_to_none=True)
    torch.cuda.reset_peak_memory_stats(device)

    prediction = model(inputs)
    loss = (prediction - target).square().mean()
    loss.backward()
    optimizer.step()

    report_cuda_memory(f"step {step}", device)

Python references determine when tensor objects become eligible for release. In this loop, prediction and loss are rebound on the next iteration, but they remain live until then. Logging a tensor, appending it to a list, or retaining a loss value for later inspection can keep its storage alive as well. For scalar logging, convert the value with loss.item(); this copies the scalar to the CPU rather than retaining the computation graph.

loss_values = []

for step in range(3):
    optimizer.zero_grad(set_to_none=True)

    prediction = model(inputs)
    loss = (prediction - target).square().mean()
    loss.backward()
    optimizer.step()

    loss_values.append(loss.item())

CPU memory needs a different measurement. Tensor byte counts still describe payload size, but the process’s resident set size includes Python objects, libraries, allocator arenas, and other native allocations. On systems where psutil is available, sample the process before and after a stage:

import os
import psutil

process = psutil.Process(os.getpid())

def report_process_memory(label):
    rss = process.memory_info().rss
    print(f"{label}: {rss / (1024 ** 2):.1f} MiB RSS")

report_process_memory("before")
result = some_cpu_computation()
report_process_memory("after")

A process-level measurement is useful for spotting growth across repeated calls, but it cannot attribute that growth to a particular tensor. For CUDA work, compare current and peak allocated memory with reserved memory, and take readings at consistent boundaries in the computation.

Finding leaks and unexpected allocations

A rising memory reading does not automatically mean that tensors are leaking. First distinguish live allocations from cached memory: if memory_allocated() keeps rising across equivalent iterations, some storage remains live; if allocated memory returns to a stable level while memory_reserved() stays high, the caching allocator is retaining blocks for reuse.

for step in range(10):
    optimizer.zero_grad(set_to_none=True)
    output = model(inputs)
    loss = loss_fn(output, target)
    loss.backward()
    optimizer.step()

    del output, loss
    torch.cuda.synchronize()
    print(
        step,
        torch.cuda.memory_allocated() // (1024 ** 2),
        torch.cuda.memory_reserved() // (1024 ** 2),
    )

One common source of persistent growth is saving tensors that still belong to an autograd graph. Appending each loss to a list can retain the graph, its saved intermediate values, and the tensors needed by backward. Store a Python number for reporting, or explicitly detach a tensor when its values must be retained.

loss_history = []

for step in range(10):
    optimizer.zero_grad(set_to_none=True)
    output = model(inputs)
    loss = loss_fn(output, target)
    loss.backward()
    optimizer.step()

    loss_history.append(loss.item())

If the saved values must remain tensors, detach them from the graph. For CUDA tensors, moving the detached copy to the CPU also prevents the history from keeping GPU storage alive.

saved_outputs = []

with torch.no_grad():
    for batch in batches:
        output = model(batch)
        saved_outputs.append(output.cpu())

A view can keep a much larger allocation alive than its shape suggests. A small slice refers to the same storage as its base tensor; storing that slice may therefore retain the entire base allocation. Copy the slice when independent, smaller storage is what you need.

large = torch.empty(4096, 4096, device="cuda")
small_view = large[:4, :4]

print(small_view.numel() * small_view.element_size())
print(small_view.untyped_storage().nbytes())

small_copy = small_view.clone()
del large, small_view

Not every increase is unexpected. Some optimizers create state tensors on the first call to step(), so memory can rise once and then stabilize. Gradients also occupy storage after backward unless they are cleared. Using zero_grad(set_to_none=True) makes parameter gradients absent until the next backward pass, rather than filling existing gradient tensors with zeros.

For an iteration that should not build a backward graph, use torch.no_grad() or, when its stricter behavior is suitable, torch.inference_mode(). Calling detach() on an output removes its connection to the graph, but it does not free storage while another reference still points to that output or to related tensors.

model.eval()

with torch.inference_mode():
    for batch in validation_batches:
        prediction = model(batch)
        score = metric(prediction, batch.target)

When memory grows only on certain iterations, inspect references and record measurements at the same point in each iteration. Python containers, callbacks, closures, and debugging tools can all retain tensors. Clearing a container releases its references, but deletion does not guarantee that the process’s resident memory or CUDA reserved memory will immediately fall.

outputs = []

for batch in batches:
    output = model(batch)
    outputs.append(output)

# The list owns references to every output.
outputs.clear()

For CUDA allocation details, print the allocator’s summary after the growth has occurred. It reports active and cached blocks and can help distinguish a growing set of live allocations from fragmentation or cached capacity.

torch.cuda.synchronize()
print(torch.cuda.memory_summary(device="cuda", abbreviated=True))

When a summary is not enough, the profiler can associate recorded tensor allocations with operations. Profile a short, representative interval rather than an entire long-running job, since recording shapes and memory events adds overhead.

from torch.profiler import profile, ProfilerActivity

with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    profile_memory=True,
    record_shapes=True,
) as prof:
    output = model(inputs)
    loss = loss_fn(output, target)
    loss.backward()

print(
    prof.key_averages().table(
        sort_by="self_cuda_memory_usage",
        row_limit=20,
    )
)

Profiler results describe allocations attributed to PyTorch operations. CUDA context memory and allocations made directly by external libraries may not appear as tensor allocations, so compare profiler data with device-level readings when the two do not account for the observed usage.

Reducing memory pressure with deliberate profiling

Profiling is most useful when the measured region is small and repeatable. Warm up the operation first so one-time costs, such as library initialization or optimizer state creation, do not obscure the steady-state peak. Then reset peak statistics immediately before the workload and compare runs with the same inputs, batch size, and synchronization points.

def run_step(model, inputs, target, optimizer, device):
    optimizer.zero_grad(set_to_none=True)
    prediction = model(inputs)
    loss = loss_fn(prediction, target)
    loss.backward()
    optimizer.step()
    return loss.item()

for _ in range(3):
    run_step(model, inputs, target, optimizer, device)

torch.cuda.synchronize(device)
torch.cuda.reset_peak_memory_stats(device)

loss_value = run_step(model, inputs, target, optimizer, device)

torch.cuda.synchronize(device)
print("loss:", loss_value)
print("peak allocated MiB:",
      torch.cuda.max_memory_allocated(device) / (1024 ** 2))

Measure one change at a time. If the peak is caused by saved activations, reducing the batch size or changing the execution strategy may help; if it’s caused by optimizer state, changing activation storage will not address it. The profiler can show which operations allocate memory and how much each operation retains at its own boundary.

from torch.profiler import profile, ProfilerActivity, record_function

with profile(
    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
    profile_memory=True,
    record_shapes=True,
) as prof:
    with record_function("training_step"):
        optimizer.zero_grad(set_to_none=True)
        prediction = model(inputs)
        loss = loss_fn(prediction, target)
        loss.backward()
        optimizer.step()

print(
    prof.key_averages().table(
        sort_by="self_cuda_memory_usage",
        row_limit=15,
    )
)

For a memory-bound forward pass, automatic mixed precision can reduce the storage used by eligible intermediate tensors. The model parameters need not be converted manually; autocast selects operation-specific dtypes, while the loss calculation can remain in a numerically suitable precision.

optimizer.zero_grad(set_to_none=True)

with torch.autocast(device_type="cuda", dtype=torch.float16):
    prediction = model(inputs)
    loss = loss_fn(prediction, target)

loss.backward()
optimizer.step()

For models whose activations dominate the peak, activation checkpointing trades additional computation for reduced saved-tensor storage. A checkpointed region is run again during backward to reconstruct values needed for gradients. The region should be chosen from measured peaks, since checkpointing a small or inexpensive operation may save little memory.

from torch.utils.checkpoint import checkpoint

class Block(torch.nn.Module):
    def __init__(self, width):
        super().__init__()
        self.layers = torch.nn.Sequential(
            torch.nn.Linear(width, width),
            torch.nn.ReLU(),
            torch.nn.Linear(width, width),
        )

    def forward(self, x):
        return checkpoint(self.layers, x, use_reentrant=False)

When a full batch does not fit, gradient accumulation can divide it into smaller microbatches. Divide each microbatch loss by the number of accumulation steps so the accumulated gradient has the same scale as the mean loss over the full batch.

optimizer.zero_grad(set_to_none=True)

accumulation_steps = 4
for inputs_part, target_part in microbatches:
    prediction = model(inputs_part)
    loss = loss_fn(prediction, target_part) / accumulation_steps
    loss.backward()

optimizer.step()

During inference, avoid constructing an autograd graph. In addition to reducing memory use, this removes backward bookkeeping that has no purpose when gradients are not needed.

model.eval()

with torch.inference_mode():
    for inputs_part in batches:
        prediction = model(inputs_part)
        consume(prediction)

To compare two implementations, capture both current and peak allocation after the same warm-up and at the same point in the iteration. A lower current value alone does not establish a lower peak: a temporary allocation may have already been released by the time the measurement is taken.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *