i have a torch tensor of shape # [B, 768, Q] , how can i l2 norm that inner dim?
- User
i have a torch tensor of shape
# [B, 768, Q], how can i l2 norm that inner dim? Assistant
You can L2 normalize the middle dimension (768) using
torch.nn.functional.normalize:import torch.nn.functional as F # Assuming your tensor is called 'tensor' with shape [B, 768, Q] normalized_tensor = F.normalize(tensor, p=2, dim=1)This will normalize each 768-dimensional vector across the batch and Q dimensions. The
dim=1parameter specifies that normalization should happen along dimension 1 (the 768 dimension).Alternatively, you can do it manually:
# Manual L2 normalization norm = torch.norm(tensor, p=2, dim=1, keepdim=True) normalized_tensor = tensor / normThe
keepdim=Trueensures the dimensions are preserved for broadcasting during the division.Both approaches will give you a tensor of the same shape
[B, 768, Q]where each 768-dimensional vector has unit L2 norm.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.