Skip to content
Skills Library
AI & agents · Building & coding

pytorch-loss-implementation

/pytorch-loss-implementation

How to implement custom loss functions in PyTorch. Use this skill whenever the user asks to implement a loss function, write a custom criterion, or mentions PyTorch tensor operations for backpropagation.

Licence
MIT
Last repository change
02.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 02.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

How to implement custom loss functions in PyTorch. Use this skill whenever the user asks to implement a loss function, write a custom criterion, or mentions PyTorch tensor operations for backpropagation.

Original author description

How to implement custom loss functions in PyTorch. Use this skill whenever the user asks to implement a loss function, write a custom criterion, or mentions PyTorch tensor operations for backpropagation.

How it works

  1. Key Principles
  2. Example Pattern
Original SKILL.md headings · 38 lines, 199 words
SKILL.md preview
---
name: pytorch-loss-implementation
description: How to implement custom loss functions in PyTorch. Use this skill whenever the user asks to implement a loss function, write a custom criterion, or mentions PyTorch tensor operations for backpropagation.
---

# PyTorch Loss Implementation

This skill provides guidelines for implementing custom loss functions in PyTorch. 

## Key Principles

1. **Use PyTorch Primitives:** Always use `torch.*` operations (e.g., `torch.log`, `torch.exp`, `torch.sum`, `F.log_softmax`) to ensure operations are differentiable and can be tracked by autograd.
2. **Numerical Stability:** Be careful with operations like log and exp. Use numerically stable functions like `F.log_softmax` instead of taking the log of a softmax, and `F.binary_cross_entropy_with_logits` instead of applying sigmoid then BCE.
3. **Handling Padding and Masks:** When working with NLP or sequence data, always apply attention masks or ignore_index appropriately to prevent padded tokens from contributing to the loss.
4. **Batch Reductions:** By default, loss functions should support different reduction methods ('mean', 'sum', 'none'). Be explicit about how reductions are applied across batch and sequence dimensions.

## Example Pattern

```python
import torch
import torch.nn.functional as F

def custom_loss(logits, targets, mask=None, reduction='mean'):
    # Apply operations
    loss = F.cross_entropy(logits, targets, reduction='none')
    
    # Apply mask if provided
    if mask is not None:
        loss = loss * mask
        if reduction == 'mean':
            return loss.sum() / mask.sum()
        elif reduction == 'sum':
            return loss.sum()
        return loss
        
    if reduction == 'mean':
        return loss.mean()
    elif reduction == 'sum':
        return loss.sum()
    return loss
```

Versions

The database has no other skills named pytorch-loss-implementation.

Database snapshot: 13.11.2026 · package version ca35ec215484 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 2 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100pytorch-testing-logging
    Run PyTorch unit tests, save results to NumPy files, and log environment information for reproducibility. Use this skill when executing test suites for neural network functions, validating loss computations, saving tensor outputs for verification, and creating reproducibility…
  • 100simpo-loss-implementation
    Implement the SimPO loss function for preference-aligned language models. Use this skill when implementing SimPO training objectives, computing length-normalized rewards, or translating the SimPO paper's mathematical formulas into PyTorch code. Essential for LLM alignment tasks…
  • 100pytorch-model-trainer
    Build pytorch model trainer operations. Auto-activating skill for ML Training. Triggers on: pytorch model trainer, pytorch model trainer Part of the ML Training skill category. Use when working with pytorch model trainer functionality. Trigger with phrases like "pytorch model…
  • 100pytorch-deep-learning-fundamentals
    Use this skill when building and training custom neural network architectures using PyTorch tensors, autograd, and DataLoader modules.
  • 86pytorch
    PyTorch开发专家助手。当用户需要进行PyTorch深度学习开发、神经网络训练、模型推理、GPU计算或AI模型工程化时调用。
  • 95docstring
    Write docstrings for PyTorch functions and methods following PyTorch conventions. Use when writing or updating docstrings in PyTorch code.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.