I have a torch tensor k1 of shape (B, N) that takes >50% of my GPU's memory. I want to…
- User
I have a torch tensor
k1of shape (B, N) that takes >50% of my GPU's memory. I want to create a new tensork2of shape (B, N+n), where the first N cols are equal tok1. I don't care aboutk1, so it can be deleted/overwritten in the process. The following does NOT work:k2 = torch.cat([k1, torch.zeros(B, n, device=k1.device)], dim=-1)Because the
catoperation allocates the entire new tensor before copying data into it, so I get OOM. How else can I approach this without hitting OOM? Assistant
You're correct that
torch.catcreates a new tensor and copies the data, which causes the OOM issue. Since you don't need to preservek1, you can use one of these memory-efficient approaches:Option 1: In-place expansion (preferred if possible)
If
k1is contiguous in memory and has enough capacity (unlikely but worth checking), you could try:k1.resize_(B, N+n) # Try in-place resize (may fail if not contiguous) k1[:, N:] = 0 # Zero out the new elements k2 = k1Option 2: Pre-allocate and copy (most reliable)
# Create new tensor first (this will be the only large allocation) k2 = torch.zeros(B, N+n, device=k1.device, dtype=k1.dtype) # Copy data into first N columns k2[:, :N] = k1 # Now you can delete k1 if needed del k1Option 3: Chunked operations (for extreme memory constraints)
If even the above fails, you can process in chunks:
k2 = torch.zeros(B, N+n, device=k1.device, dtype=k1.dtype) chunk_size = B // 4 # Adjust based on your memory for i in range(0, B, chunk_size): k2[i:i+chunk_size, :N] = k1[i:i+chunk_size] del k1- User
Unfortunately
resize_still allocates enough memory for the whole new tensor, and the other operations create the new tensor before coping. Any other ideas? Assistant
You're right—most operations will temporarily require memory for both tensors. Here’s a true in-place approach that avoids allocating a full second tensor by reusing
k1's memory without a full copy. This works if you can tolerate destructive modification ofk1(which you said is fine):Solution: Use
uninitializedmemory + manual copy (minimal peak memory)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.