| name | pytorch-loss-implementation |
| description | Implement loss functions in PyTorch with proper tensor operations. |
PyTorch Loss Implementation
Key Concepts
1. Tensor Operations
import torch
sigmoid_output = torch.sigmoid(input_tensor)
log_output = torch.log(input_tensor)
mean_loss = loss.mean()
sum_loss = loss.sum()
2. Batch Processing
batch_size = tensor.shape[0]
x = tensor[:batch_size//2]
y = tensor[batch_size//2:]
tensor = tensor.to(device=model.device, dtype=torch.float32)
3. Numerical Stability
Log-Sigmoid Stability
stable_loss = torch.nn.functional.logsigmoid(x)
loss = -torch.log(torch.sigmoid(x) + 1e-10)
Handling Small Values
safe_log = torch.log(value + 1e-8)
clamped = torch.clamp(value, min=1e-10, max=1.0)
4. Device Handling
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
tensor = tensor.to(device)
device = next(model.parameters()).device
tensor = tensor.to(device)
Loss Function Pattern
def compute_loss(logits, labels, temperature=1.0, margin=0.5):
rewards = logits / (sequence_length + 1e-8)
diff = temperature * rewards[:n//2] - temperature * rewards[n//2:] - margin
loss_per_pair = -torch.log(torch.sigmoid(diff) + 1e-10)
loss = loss_per_pair.mean()
return loss
Debugging Tips
- Check tensor shapes at each step
- Use .detach() for inspecting values without affecting gradients
- Verify numerical stability with small inputs
- Test gradients with
loss.backward()
- Print intermediate values for debugging
Performance Tips
- Use in-place operations where safe:
tensor.log_()
- Avoid unnecessary cloning/copying
- Batch operations are faster than loops
- Use PyTorch functions over custom loops