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:codek2 = 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
Since you don't care about preserving
k1, you can resize it in-place to avoid the OOM issue:python# Resize k1 in-place k1.resize_(B, N+n) # Fill the new portion with zeros k1[:, N:].zero_() # Now k1 has become your desired tensor k2 = k1 # Optional assignment, or just use k1 directlyThis approach modifies the tensor's storage directly without allocating a completely new tensor, which should avoid the memory issues you're experiencing.
Alternatively, if
resize_doesn't work well for your case, you could try:python# Create empty tensor of target size k2 = torch.zeros(B, N+n, device=k1.device) # Copy data from k1 k2[:, :N].copy_(k1) # Free memory del k1Would you like me to explain or break down this code?
- 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
Given your severe memory constraints, we need more specialized approaches. Here are some strategies that might work:
python# Option 1: Process in smaller chunks to avoid memory spikes k2 = torch.zeros(B, N+n, device=k1.device, dtype=k1.dtype) # Copy data in manageable chunks chunk_size = max(1, B // 10) # Adjust based on memory constraints for i in range(0, B, chunk_size): end = min(i + chunk_size, B) k2[i:end, :N] = k1[i:end] torch.cuda.empty_cache() # Optional: free cache after each chunk del k1python# Option 2: CPU offloading for extreme cases # Move to CPU temporarily k1_cpu = k1.cpu() del k1 torch.cuda.empty_cache() # Free GPU memory # Create new tensor and copy back from CPU k2 = torch.zeros(B, N+n, device='cuda') k2[:, :N] = k1_cpu.to('cuda')
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.