Manuel de référence torch.nn de PyTorch
de PyTorchtorch.nnmodule est le module central pour construire et entraîner des réseaux de neurones. Il fournit un ensemble riche de classes et de fonctions pour définir et exploiter des réseaux de neurones.
Les suivantes sonttorch.nnquelques composants clés du module et leurs fonctions :
1. La classe nn.Module:
nn.Moduleest la classe de base pour tous les modèles personnalisés de réseaux de neurones. Les utilisateurs dérivent généralement leurs propres classes de modèle à partir de cette classe et y définissent la structure des couches du réseau et la fonction de propagation avant.
2. Couches prédéfinies (modules):
- Comprend divers types de composants de couche, tels que les couches convolutionnelles (
nn.Conv1d,nn.Conv2d,nn.Conv3d), les couches entièrement connectées (nn.Linear), les fonctions d'activation (nn.ReLU,nn.Sigmoid,nn.Tanh), etc.
3. Classes conteneurs:
nn.Sequential: Permettent de combiner plusieurs couches séquentiellement pour former un réseau simple empilé linéairement.nn.ModuleListetnn.ModuleDict: Peuvent stocker et accéder dynamiquement à des sous-modules, en prenant en charge des collections de modules de longueur variable ou nommées.
4. Fonctions de perte:
torch.nnContient une série de fonctions de perte permettant de mesurer la différence entre les prédictions du modèle et les étiquettes réelles, telles que la perte d'erreur quadratique moyenne (nn.MSELoss), la perte d'entropie croisée (nn.CrossEntropyLoss), etc.
5. Interface fonctionnelle:
nn.functional(généralement abrégée enF), contient de nombreuses fonctions qui peuvent opérer directement sur des tenseurs. Elles implémentent les mêmes fonctionnalités que les objets de couche, mais n'ont pas la capacité de sauvegarder et de mettre à jour les paramètres. Par exemple, vous pouvez utiliserF.relu()pour effectuer directement des opérations ReLU, ouF.conv2d()pour effectuer des opérations de convolution.
6. Méthodes d'initialisation:
torch.nn.initFournit quelques stratégies d'initialisation de poids couramment utilisées, telles que l'initialisation Xavier (nn.init.xavier_uniform_()) et l'initialisation Kaiming (nn.init.kaiming_uniform_()), qui sont cruciales pour réussir l'entraînement des réseaux de neurones.
7. Couches Transformer:
- PyTorch fournit des composants complets de l'architecture Transformer, notamment
nn.Transformer,nn.TransformerEncoder,nn.TransformerDecoderainsi que les mécanismes d'attentionnn.MultiheadAttentionetc.
8. Couches de normalisation:
- Inclure la normalisation par lots (
BatchNorm), la normalisation de couche (LayerNorm), la normalisation de groupe (GroupNorm), la normalisation d'instance (InstanceNorm), et RMSNorm, etc.
Manuel de référence du module torch.nn de PyTorch
Conteneurs de réseaux de neurones
| Classe/Fonction | Description |
|---|---|
torch.nn.Module |
Classe de base pour tous les modules de réseaux de neurones. |
torch.nn.Sequential(*args) |
Combine séquentiellement plusieurs modules. |
torch.nn.ModuleList(modules) |
Stocke les sous-modules dans une liste. |
torch.nn.ModuleDict(modules) |
Stocke les sous-modules dans un dictionnaire. |
torch.nn.ParameterList(parameters) |
Stocke les paramètres dans une liste. |
torch.nn.ParameterDict(parameters) |
Stocke les paramètres dans un dictionnaire. |
torch.nn.Parameter(data) |
Crée un tenseur de paramètres apprenables. |
torch.nn.Buffer(data) |
Crée un tampon persistant (paramètre non apprenable). |
torch.nn.Identity(*args, **kwargs) |
Couche de transformation identité, l'entrée est directement transmise en sortie. |
Hooks globaux
| Fonction | Description |
|---|---|
register_module_forward_pre_hook(hook) |
Enregistre un pré-hook de propagation avant. |
register_module_forward_hook(hook) |
Enregistre un hook de propagation avant. |
register_module_backward_hook(hook) |
Enregistre un hook backward. |
register_module_full_backward_pre_hook(hook) |
Enregistre un pré-hook backward complet. |
register_module_full_backward_hook(hook) |
Enregistre un hook backward complet. |
Couches linéaires
| Classe/Fonction | Description |
|---|---|
torch.nn.Linear(in_features, out_features, bias) |
Couche entièrement connectée (transformation linéaire). |
torch.nn.Bilinear(in1_features, in2_features, out_features, bias) |
Couche bilinéaire. |
torch.nn.LazyLinear(out_features, bias) |
Couche linéaire avec initialisation différée ; déduit automatiquement la dimension d'entrée lors de la première passe forward. |
Couches de convolution
| Classe/Fonction | Description |
|---|---|
torch.nn.Conv1d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) |
Couche de convolution 1D, couramment utilisée pour le texte et l'audio. |
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) |
Couche de convolution 2D, couramment utilisée pour les images. |
torch.nn.Conv3d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode) |
Couche de convolution 3D, couramment utilisée pour les vidéos et les données volumétriques. |
torch.nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) |
Convolution transposée 1D (déconvolution), utilisée pour le suréchantillonnage. |
torch.nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) |
Convolution transposée 2D (déconvolution), utilisée pour le suréchantillonnage. |
torch.nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride, padding, output_padding, groups, bias, dilation, padding_mode) |
Convolution transposée 3D (déconvolution), utilisée pour le suréchantillonnage. |
torch.nn.Unfold(kernel_size, dilation, padding, stride) |
Déplie le tenseur d'entrée en blocs de fenêtres glissantes. |
torch.nn.Fold(output_size, kernel_size, dilation, padding, stride) |
Recombine les blocs dépliés en un tenseur. |
Couches de pooling
| Classe/Fonction | Description |
|---|---|
torch.nn.MaxPool1d(kernel_size, stride, padding, dilation, return_indices) |
Couche de pooling max 1D. |
torch.nn.MaxPool2d(kernel_size, stride, padding, dilation, return_indices, ceil_mode) |
Couche de pooling max 2D. |
torch.nn.MaxPool3d(kernel_size, stride, padding, dilation, return_indices, ceil_mode) |
Couche de pooling max 3D. |
torch.nn.MaxUnpool1d(kernel_size, stride, padding) |
Couche d'unpooling max 1D. |
torch.nn.MaxUnpool2d(kernel_size, stride, padding) |
Couche d'unpooling max 2D. |
torch.nn.MaxUnpool3d(kernel_size, stride, padding) |
Couche d'unpooling max 3D. |
torch.nn.AvgPool1d(kernel_size, stride, padding) |
Couche de pooling moyen 1D. |
torch.nn.AvgPool2d(kernel_size, stride, padding, ceil_mode, count_include_pad) |
Couche de pooling moyen 2D. |
torch.nn.AvgPool3d(kernel_size, stride, padding, ceil_mode, count_include_pad) |
Couche de pooling moyen 3D. |
torch.nn.AdaptiveMaxPool1d(output_size, return_indices) |
Pooling max adaptatif 1D, taille de sortie fixe. |
torch.nn.AdaptiveMaxPool2d(output_size, return_indices) |
Pooling max adaptatif 2D, taille de sortie fixe. |
torch.nn.AdaptiveMaxPool3d(output_size, return_indices) |
Pooling max adaptatif 3D, taille de sortie fixe. |
torch.nn.AdaptiveAvgPool1d(output_size) |
Pooling moyen adaptatif 1D, taille de sortie fixe. |
torch.nn.AdaptiveAvgPool2d(output_size) |
Pooling moyen adaptatif 2D, taille de sortie fixe. |
torch.nn.AdaptiveAvgPool3d(output_size) |
Pooling moyen adaptatif 3D, taille de sortie fixe. |
torch.nn.LPPool1d(norm_type, kernel_size, stride, padding) |
Couche de pooling Lp 1D. |
torch.nn.LPPool2d(norm_type, kernel_size, stride, padding) |
Couche de pooling Lp 2D. |
torch.nn.FractionalMaxPool2d(kernel_size, output_size, output_ratio, return_indices) |
Pooling max fractionnaire 2D, utilisant des tailles de pas aléatoires. |
torch.nn.FractionalMaxPool3d(kernel_size, output_size, output_ratio, return_indices) |
Pooling max fractionnaire 3D, utilisant des tailles de pas aléatoires. |
Couches de padding
| Classe/Fonction | Description |
|---|---|
torch.nn.ReflectionPad1d(padding) |
Padding par réflexion 1D, copie en réfléchissant le long de la limite. |
torch.nn.ReflectionPad2d(padding) |
Padding par réflexion 2D, copie en réfléchissant le long de la bordure. |
torch.nn.ReflectionPad3d(padding) |
Padding par réflexion 3D, copie en réfléchissant le long de la bordure. |
torch.nn.ReplicationPad1d(padding) |
Padding par réplication 1D, copie les valeurs de bord le long de la bordure. |
torch.nn.ReplicationPad2d(padding) |
Padding par réplication 2D, copie les valeurs de bord le long de la bordure. |
torch.nn.ReplicationPad3d(padding) |
Padding par réplication 3D, copie les valeurs de bord le long de la bordure. |
torch.nn.ZeroPad1d(padding) |
Padding zéro 1D. |
torch.nn.ZeroPad2d(padding) |
Padding zéro 2D. |
torch.nn.ZeroPad3d(padding) |
Padding zéro 3D. |
torch.nn.ConstantPad1d(padding, value) |
Padding constant 1D, remplit avec une valeur spécifiée. |
torch.nn.ConstantPad2d(padding, value) |
Padding constant 2D, remplit avec une valeur spécifiée. |
torch.nn.ConstantPad3d(padding, value) |
Padding constant 3D, remplit avec une valeur spécifiée. |
torch.nn.CircularPad1d(padding) |
Padding cyclique 1D. |
torch.nn.CircularPad2d(padding) |
Rembourrage cyclique 2D. |
torch.nn.CircularPad3d(padding) |
Rembourrage cyclique 3D. |
Fonctions d'activation (activations non linéaires - somme pondérée)
| Classe/Fonction | Description |
|---|---|
torch.nn.ReLU(inplace) |
Fonction d'activation ReLU, f(x) = max(0, x). |
torch.nn.ReLU6(inplace) |
Fonction d'activation ReLU6, f(x) = min(max(0, x), 6). |
torch.nn.Sigmoid() |
Fonction d'activation sigmoïde, f(x) = 1 / (1 + exp(-x)). |
torch.nn.Tanh() |
Fonction d'activation Tanh, f(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x)). |
torch.nn.LeakyReLU(negative_slope, inplace) |
LeakyReLU, autorise de petits gradients pour les valeurs négatives. |
torch.nn.PReLU(num_parameters, init) |
ReLU paramétrique, avec un paramètre de pente négative apprenable. |
torch.nn.ELU(alpha, inplace) |
Unité linéaire exponentielle, utilise la fonction exponentielle pour les valeurs négatives. |
torch.nn.CELU(alpha, inplace) |
Unité linéaire exponentielle continûment différentiable. |
torch.nn.SELU(inplace) |
Unité linéaire exponentielle auto-normalisante. |
torch.nn.GELU() |
Unité linéaire d'erreur gaussienne, couramment utilisée dans les Transformers. |
torch.nn.SiLU(inplace) |
Unité linéaire sigmoïde (Swish), f(x) = x * sigmoid(x). |
torch.nn.Mish(inplace) |
Fonction d'activation Mish, f(x) = x * tanh(softplus(x)). |
torch.nn.Hardtanh(min_value, max_value, inplace) |
Tangente hyperbolique dure, limite la plage de sortie. |
torch.nn.Hardswish(inplace) |
Hard Swish, une version lisse de ReLU6. |
torch.nn.Hardsigmoid(inplace) |
Hard Sigmoid, approximation linéaire par morceaux. |
torch.nn.RReLU(lower, upper, inplace) |
LeakyReLU randomisé, sélectionne aléatoirement la pente négative pendant l'entraînement. |
torch.nn.Softplus(beta, threshold) |
Softplus, une approximation lisse de ReLU. |
torch.nn.Softshrink(lambda) |
Fonction d'activation Softshrink. |
torch.nn.Hardshrink(lambda) |
Fonction d'activation Hardshrink. |
torch.nn.Softsign() |
Fonction d'activation Softsign, f(x) = x / (1 + |x|). |
torch.nn.Tanhshrink() |
Tanhshrink,f(x) = x - tanh(x). |
torch.nn.LogSigmoid() |
Log Sigmoid, f(x) = log(sigmoid(x)). |
torch.nn.Threshold(threshold, value, inplace) |
Fonction d'activation à seuil. |
torch.nn.GLU(dim) |
Gated Linear Unit, divise l'entrée en deux parties selon une dimension spécifiée et les multiplie élément par élément. |
Fonctions d'activation (activations non linéaires - autres)
| Classe/Fonction | Description |
|---|---|
torch.nn.Softmax(dim) |
Fonction d'activation Softmax, convertit les valeurs en une distribution de probabilité. |
torch.nn.Softmax2d() |
Softmax sur les dimensions spatiales, utilisé pour les images. |
torch.nn.LogSoftmax(dim) |
Log Softmax, version numériquement stable de Softmax. |
torch.nn.Softmin(dim) |
Softmin, l'opposé de Softmax. |
torch.nn.AdaptiveLogSoftmaxWithLoss(in_features, n_classes, cutoffs, div_value, head_bias) |
Adaptive Log Softmax, utilisé pour la classification à grand vocabulaire. |
Couches de normalisation
| Classe/Fonction | Description |
|---|---|
torch.nn.BatchNorm1d(num_features, eps, momentum, affine, track_running_stats) |
Couche de normalisation par lots unidimensionnelle, normalise les données de mini-lots. |
torch.nn.BatchNorm2d(num_features, eps, momentum, affine, track_running_stats) |
Couche de normalisation par lots bidimensionnelle, couramment utilisée dans les réseaux convolutifs. |
torch.nn.BatchNorm3d(num_features, eps, momentum, affine, track_running_stats) |
Couche de normalisation par lots tridimensionnelle, utilisée pour les données tridimensionnelles telles que les vidéos. |
torch.nn.LazyBatchNorm1d() |
Normalisation par lots unidimensionnelle avec initialisation différée. |
torch.nn.LazyBatchNorm2d() |
Normalisation par lots bidimensionnelle avec initialisation différée. |
torch.nn.LazyBatchNorm3d() |
Normalisation par lots tridimensionnelle avec initialisation différée. |
torch.nn.LayerNorm(normalized_shape, eps, elementwise_affine) |
Normalisation de couche, couramment utilisée dans les Transformers. |
torch.nn.GroupNorm(num_groups, num_channels, eps, affine) |
Normalisation de groupe, normalise après regroupement des canaux. |
torch.nn.InstanceNorm1d(num_features, eps, momentum, affine, track_running_stats) |
Normalisation d'instance unidimensionnelle, utilisée pour le transfert de style. |
torch.nn.InstanceNorm2d(num_features, eps, momentum, affine, track_running_stats) |
Normalisation d'instance bidimensionnelle, utilisée pour le transfert de style. |
torch.nn.InstanceNorm3d(num_features, eps, momentum, affine, track_running_stats) |
Normalisation d'instance tridimensionnelle, utilisée pour le transfert de style. |
torch.nn.SyncBatchNorm(num_features, eps, momentum, affine, track_running_stats, process_group) |
Normalisation par lots synchronisée, utilisée pour l'entraînement distribué multi-GPU. |
torch.nn.LocalResponseNorm(k, alpha, beta, size) |
Normalisation de réponse locale, utilisée dans les réseaux de neurones convolutionnels pour l'inhibition latérale. |
torch.nn.RMSNorm(normalized_shape, eps, elementwise_affine) |
Normalisation RMS, couramment utilisée dans les Transformers. |
Couches de réseaux de neurones récurrents.
| Classe/Fonction | Description |
|---|---|
torch.nn.RNN(input_size, hidden_size, num_layers, nonlinearity, bias, batch_first, dropout, bidirectional) |
Couche RNN simple. |
torch.nn.LSTM(input_size, hidden_size, num_layers, bias, batch_first, dropout, bidirectional, proj_size) |
Couche LSTM (Long Short-Term Memory). |
torch.nn.GRU(input_size, hidden_size, num_layers, bias, batch_first, dropout, bidirectional, proj_size) |
Couche GRU (Gated Recurrent Unit). |
torch.nn.RNNCell(input_size, hidden_size, bias, nonlinearity) |
Cellule RNN (couche unique). |
torch.nn.LSTMCell(input_size, hidden_size, bias) |
Cellule LSTM (couche unique). |
torch.nn.GRUCell(input_size, hidden_size, bias) |
Cellule GRU (couche unique). |
Couches Transformer
| Classe/Fonction | Description |
|---|---|
torch.nn.Transformer(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout, activation, custom_encoder, custom_decoder, layer_norm_eps, normalize_before, need_src_mask, need_tgt_mask, need_memory_mask, batch_first, norm_first, bias) |
Modèle Transformer complet. |
torch.nn.TransformerEncoder(encoder_layer, num_layers, norm) |
Encodeur Transformer. |
torch.nn.TransformerDecoder(decoder_layer, num_layers, norm) |
Décodeur Transformer. |
torch.nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, dropout, activation, layer_norm_eps, batch_first, norm_first, bias) |
Couche d'encodeur Transformer. |
torch.nn.TransformerDecoderLayer(d_model, nhead, dim_feedforward, dropout, activation, layer_norm_eps, batch_first, norm_first, bias) |
Couche de décodeur Transformer. |
torch.nn.MultiheadAttention(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first) |
Mécanisme d'attention multi-têtes. |
Mécanismes d'attention
| Fonction | Description |
|---|---|
torch.nn.functional.scaled_dot_product_attention(query, key, value, attn_mask, dropout_p, is_causal) |
Attention à produit scalaire mis à l'échelle, implémentation d'attention optimisée de PyTorch. |
torch.nn.attention.sdpa_kernel(backends) |
Définit le backend d'attention SDP (Scaled Dot-Product). |
Couches d'embedding (couches creuses)
| Classe/Fonction | Description |
|---|---|
torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse) |
Couche d'embedding, mappe des indices discrets vers des vecteurs denses. |
torch.nn.EmbeddingBag(num_embeddings, embedding_dim, max_norm, norm_type, scale_grad_by_freq, mode, sparse, per_sample_weights, include_last_offset, padding_idx) |
Embedding bag, agrège plusieurs embeddings. |
Couches de dropout
| Classe/Fonction | Description |
|---|---|
torch.nn.Dropout(p, inplace) |
Couche Dropout, met aléatoirement à zéro des éléments d'entrée. |
torch.nn.Dropout1d(p, inplace) |
Dropout unidimensionnel, utilisé pour les entrées unidimensionnelles. |
torch.nn.Dropout2d(p, inplace) |
Dropout bidimensionnel, utilisé pour les cartes de caractéristiques bidimensionnelles. |
torch.nn.Dropout3d(p, inplace) |
Dropout tridimensionnel, utilisé pour les volumes de caractéristiques tridimensionnels. |
torch.nn.AlphaDropout(p, inplace) |
Alpha Dropout, maintient les propriétés d'auto-normalisation. |
torch.nn.FeatureAlphaDropout(p, inplace) |
Feature Alpha Dropout. |
Couches de vision
| Classe/Fonction | Description |
|---|---|
torch.nn.PixelShuffle(upscale_factor) |
Pixel shuffle, convertit les dimensions de canal en dimensions spatiales (suréchantillonnage). |
torch.nn.PixelUnshuffle(downscale_factor) |
Pixel shuffle inverse, convertit les dimensions spatiales en dimensions de canal (sous-échantillonnage). |
torch.nn.Upsample(size, scale_factor, mode, align_corners, recompute_scale_factor) |
Couche de suréchantillonnage. |
torch.nn.UpsamplingNearest2d(size, scale_factor) |
Suréchantillonnage bidimensionnel au plus proche voisin. |
torch.nn.UpsamplingBilinear2d(size, scale_factor, align_corners) |
Suréchantillonnage bidimensionnel bilinéaire. |
torch.nn.ChannelShuffle(groups) |
Channel shuffle, utilisé pour les réseaux ChannelShuffle. |
Fonctions de perte
| Classe/Fonction | Description |
|---|---|
torch.nn.MSELoss(size_average, reduce, reduction) |
Perte d'erreur quadratique moyenne. |
torch.nn.L1Loss(size_average, reduce, reduction) |
Perte L1 (erreur absolue moyenne). |
torch.nn.CrossEntropyLoss(weight, size_average, ignore_index, reduce, reduction, label_smoothing) |
Perte d'entropie croisée, utilisée pour les tâches de classification multiclasse. |
torch.nn.NLLLoss(weight, size_average, ignore_index, reduce, reduction) |
Perte de log-vraisemblance négative. |
torch.nn.BCELoss(weight, size_average, reduce, reduction) |
Perte d'entropie croisée binaire (classification binaire). |
torch.nn.BCEWithLogitsLoss(weight, pos_weight, size_average, reduce, reduction, label_smoothing) |
Perte d'entropie croisée binaire avec Sigmoid, numériquement plus stable. |
torch.nn.KLDivLoss(size_average, reduce, reduction, log_target) |
Perte de divergence KL, utilisée pour l'appariement de distributions. |
torch.nn.HuberLoss(delta, size_average, reduce, reduction) |
Perte de Huber, une combinaison de L1 et L2, plus robuste aux valeurs aberrantes. |
torch.nn.SmoothL1Loss(beta, size_average, reduce, reduction) |
Perte L1 lissée (une variante de la perte de Huber). |
torch.nn.CTCLoss(blank, reduction, zero_infinity) |
Perte de Connectionist Temporal Classification, utilisée pour des tâches de séquence telles que la reconnaissance vocale. |
torch.nn.PoissonNLLLoss(log_input, full, size_average, reduce, reduction) |
Perte de log-vraisemblance négative de Poisson. |
torch.nn.GaussianNLLLoss(full, size_average, reduce, reduction) |
Perte de log-vraisemblance négative gaussienne. |
torch.nn.MarginRankingLoss(margin, size_average, reduce, reduction) |
Perte de classement par marge, utilisée pour l'apprentissage au classement. |
torch.nn.HingeEmbeddingLoss(margin, size_average, reduce, reduction) |
Perte d'intégration Hinge, utilisée pour l'apprentissage métrique. |
torch.nn.MultiLabelMarginLoss(size_average, reduce, reduction) |
Perte de marge multi-étiquettes. |
torch.nn.SoftMarginLoss(size_average, reduce, reduction) |
Perte de marge souple. |
torch.nn.MultiLabelSoftMarginLoss(weight, size_average, reduce, reduction) |
Perte de marge souple multi-étiquettes. |
torch.nn.CosineEmbeddingLoss(margin, size_average, reduce, reduction) |
Perte de plongement cosinus, utilisée pour l'apprentissage de métriques. |
torch.nn.MultiMarginLoss(p, margin, weight, size_average, reduce, reduction) |
Perte de marge multi-classes. |
torch.nn.TripletMarginLoss(margin, p, eps, swap, size_average, reduce, reduction) |
Perte triplet, utilisée pour l'apprentissage de métriques et l'apprentissage contrastif. |
torch.nn.TripletMarginWithDistanceLoss(distance_function, margin, swap, size_average, reduce, reduction) |
Perte triplet avec fonction de distance. |
Fonctions de distance
| Classe/Fonction | Description |
|---|---|
torch.nn.PairwiseDistance(p, eps, keepdim) |
Calcul de distance par paires. |
torch.nn.CosineSimilarity(dim, eps) |
Calcul de similarité cosinus. |
Couches parallèles (DataParallel)
| Classe/Fonction | Description |
|---|---|
torch.nn.DataParallel(module, device_ids, output_device, dim) |
Parallélisme de données, exécute le modèle en parallèle sur plusieurs GPU. |
torch.nn.parallel.DistributedDataParallel(module, device_ids, broadcast_buffers, bucket_cap_mb, find_unused_parameters, gradient_as_bucket_view, static_graph) |
Parallélisme de données distribué, utilisé pour l'entraînement distribué multi-nœuds. |
Fonctions utilitaires (nn.functional)
| Fonction | Description |
|---|---|
torch.nn.functional.relu(input, inplace) |
Applique la fonction d'activation ReLU. |
torch.nn.functional.sigmoid(input) |
Applique la fonction d'activation Sigmoid. |
torch.nn.functional.tanh(input) |
Applique la fonction d'activation Tanh. |
torch.nn.functional.softmax(input, dim, dtype) |
Applique la fonction d'activation Softmax. |
torch.nn.functional.log_softmax(input, dim, dtype) |
Applique la fonction d'activation Log Softmax. |
torch.nn.functional.gelu(input) |
Applique la fonction d'activation GELU. |
torch.nn.functional.silu(input) |
Applique la fonction d'activation SiLU (Swish). |
torch.nn.functional.mish(input) |
Applique la fonction d'activation Mish. |
torch.nn.functional.hardswish(input) |
Applique la fonction d'activation Hardswish. |
torch.nn.functional.leaky_relu(input, negative_slope, inplace) |
Applique la fonction d'activation LeakyReLU. |
torch.nn.functional.elu(input, alpha, inplace) |
Applique la fonction d'activation ELU. |
torch.nn.functional.dropout(input, p, training, inplace) |
Applique le Dropout. |
torch.nn.functional.conv1d(input, weight, bias, stride, padding, dilation, groups) |
Opération de convolution unidimensionnelle. |
torch.nn.functional.conv2d(input, weight, bias, stride, padding, dilation, groups) |
Opération de convolution bidimensionnelle |
torch.nn.functional.conv3d(input, weight, bias, stride, padding, dilation, groups) |
Opération de convolution tridimensionnelle. |
torch.nn.functional.max_pool1d(input, kernel_size, stride, padding, dilation, return_indices) |
Sous-échantillonnage maximal unidimensionnel. |
torch.nn.functional.max_pool2d(input, kernel_size, stride, padding, dilation, return_indices, ceil_mode) |
Sous-échantillonnage maximal bidimensionnel. |
torch.nn.functional.avg_pool1d(input, kernel_size, stride, padding, ceil_mode, count_include_pad) |
Sous-échantillonnage moyen unidimensionnel. |
torch.nn.functional.avg_pool2d(input, kernel_size, stride, padding, ceil_mode, count_include_pad) |
Sous-échantillonnage moyen bidimensionnel. |
torch.nn.functional.linear(input, weight, bias) |
Transformation linéaire (multiplication matricielle). |
torch.nn.functional.cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing) |
Calcule la perte d'entropie croisée. |
torch.nn.functional.mse_loss(input, target, size_average, reduce, reduction) |
Calcule la perte d'erreur quadratique moyenne. |
torch.nn.functional.l1_loss(input, target, size_average, reduce, reduction) |
Calcule L1. |
torch.nn.functional.binary_cross_entropy(input, target, weight, size_average, reduce, reduction) |
Calcule l'entropie croisée binaire. |
torch.nn.functional.nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction) |
Calcule la perte de vraisemblance logarithmique négative. |
torch.nn.functional.huber_loss(input, target, delta, size_average, reduce, reduction) |
Calcule la perte de Huber. |
torch.nn.functional.batch_norm(input, running_mean, running_var, weight, bias, training, momentum, eps, track_running_stats) |
Opération de normalisation par lots. |
torch.nn.functional.layer_norm(input, normalized_shape, weight, bias, eps) |
Opération de normalisation de couche. |
torch.nn.functional.group_norm(input, num_groups, weight, bias, eps) |
Opération de normalisation de groupe. |
torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners, recompute_scale_factor) |
Interpolation (suréchantillonnage/sous-échantillonnage). |
torch.nn.functional.grid_sample(input, grid, mode, padding_mode, align_corners) |
Échantillonnage de grille, utilisé pour le recalage d’images et les réseaux de transformation spatiale. |
torch.nn.functional.affine_grid(theta, size, align_corners) |
Génération de grille affine, utilisée pour les réseaux de transformation spatiale. |
torch.nn.functional.pixel_shuffle(input, upscale_factor) |
Réarrangement de pixels. |
torch.nn.functional.pixel_unshuffle(input, downscale_factor) |
Réarrangement inverse de pixels. |
torch.nn.functional.pad(input, pad, mode, value) |
Opération de remplissage. |
torch.nn.functional.one_hot(tensor, num_classes) |
Convertit des entiers en encodage one-hot. |
torch.nn.functional.embedding(input, weight, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse) |
Opération de plongement. |
torch.nn.functional.cosine_similarity(x1, x2, dim, eps) |
Calcul de similarité cosinus. |
torch.nn.functional.pairwise_distance(x1, x2, p, eps, keepdim) |
Calcul de distance par paires. |
Fonctions utilitaires (nn.utils)
| Fonction | Description |
|---|---|
torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type, error_if_nonfinite) |
Écrête la norme du gradient (opération en place). |
torch.nn.utils.clip_grad_norm(parameters, max_norm, norm_type) |
Écrête la norme du gradient (opération non en place). |
torch.nn.utils.clip_grad_value_(parameters, clip_value) |
Écrête la plage de valeurs du gradient. |
torch.nn.utils.get_total_norm(parameters, norm_type) |
Calcule la norme totale du gradient. |
torch.nn.utils.weight_norm(module, name, dim) |
Applique la normalisation des poids aux paramètres du module. |
torch.nn.utils.remove_weight_norm(module, name) |
Supprime la normalisation des poids. |
torch.nn.utils.spectral_norm(module, name, n_power_iterations, eps, bias) |
Applique la normalisation spectrale aux paramètres du module. |
torch.nn.utils.remove_spectral_norm(module, name) |
Supprime la normalisation spectrale. |
torch.nn.utils.fuse_conv_bn_eval(conv, bn) |
Fusionne les couches convolutionnelles et les couches de normalisation par lots (mode inférence). |
torch.nn.utils.fuse_linear_bn_eval(linear, bn) |
Fusionne les couches linéaires et les couches de normalisation par lots (mode inférence). |
torch.nn.utils.skip_init(module_class, *args, **kwargs) |
Ignore l'initialisation des paramètres. |
torch.nn.utils.parameters_to_vector(parameters) |
Aplatit une liste de paramètres en un vecteur. |
torch.nn.utils.vector_to_parameters(vector, parameters) |
Remodèle un vecteur en une liste de paramètres. |
Initialisation des paramètres (nn.init)
| Fonction | Description |
|---|---|
torch.nn.init.zeros_(tensor) |
Initialise un tenseur avec des zéros. |
torch.nn.init.ones_(tensor) |
Initialise un tenseur avec des uns. |
torch.nn.init.uniform_(tensor, a, b) |
Initialisation par distribution uniforme. |
torch.nn.init.normal_(tensor, mean, std) |
Initialisation par distribution normale. |
torch.nn.init.constant_(tensor, val) |
Initialisation par valeur constante. |
torch.nn.init.eye_(tensor) |
Initialisation par matrice identité (applicable uniquement aux matrices carrées 2D). |
torch.nn.init.dirac_(tensor) |
Initialisation par delta de Dirac (préserve le nombre de canaux d'entrée). |
torch.nn.init.xavier_uniform_(tensor, gain) |
Initialisation par distribution uniforme de Xavier. |
torch.nn.init.xavier_normal_(tensor, gain) |
Initialisation par distribution normale de Xavier. |
torch.nn.init.kaiming_uniform_(tensor, a, mode, nonlinearity) |
Initialisation par distribution uniforme de Kaiming, adaptée aux activations ReLU. |
torch.nn.init.kaiming_normal_(tensor, a, mode, nonlinearity) |
Initialisation par distribution normale de Kaiming, adaptée aux activations ReLU. |
torch.nn.init.trunc_normal_(tensor, mean, std, a, b) |
Initialisation par distribution normale tronquée. |
torch.nn.init.orthogonal_(tensor, gain) |
Initialisation orthogonale. |
torch.nn.init.sparse_(tensor, sparsity, std) |
Initialisation creuse (majoritairement nulle). |
torch.nn.init.calculate_gain(nonlinearity, param) |
Calcule la valeur du gain d'initialisation. |
Fonctions utilitaires RNN
| Fonction | Description |
|---|---|
torch.nn.utils.rnn.PackedSequence |
Empaqueter des séquences pour gérer des séquences de longueur variable. |
torch.nn.utils.rnn.pack_padded_sequence(input, lengths, batch_first, enforce_sorted) |
Empaqueter des séquences rembourrées. |
torch.nn.utils.rnn.pad_packed_sequence(input, batch_first, padding_value, total_length) |
Dépaqueter des séquences. |
torch.nn.utils.rnn.pad_sequence(sequences, batch_first, padding_value) |
Rembourrer les séquences à la même longueur. |
torch.nn.utils.rnn.pack_sequence(sequences, enforce_sorted) |
Empaqueter directement une liste de séquences. |
Fonctions d'élagage
| Fonction | Description |
|---|---|
torch.nn.utils.prune.random_unstructured(module, name, amount) |
Élagage non structuré aléatoire. |
torch.nn.utils.prune.l1_unstructured(module, name, amount) |
Élagage non structuré L1. |
torch.nn.utils.prune.global_unstructured(parameters, pruning_method, amount) |
Élagage non structuré global. |
torch.nn.utils.prune.remove(module, name) |
Supprimer l'élagage. |
torch.nn.utils.prune.is_pruned(module) |
Vérifier si un module a été élagué. |
Couche Flatten
| Classe/Fonction | Description |
|---|---|
torch.nn.Flatten(start_dim, end_dim) |
Aplatir un tenseur, en aplatissant un tenseur multidimensionnel en deux dimensions. |
torch.nn.Unflatten(dim, unflattened_size) |
Unflatten, redimensionner un tenseur unidimensionnel en multidimensionnel. |
Exemple
Exemple
import torch
import torch.nn as nn
# Définir un réseau de neurones simple
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(20, 1)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# Créer un modèle et une entrée
model = SimpleNet()
input = torch.randn(5, 10)
output = model(input)
print(output)
import torch.nn as nn
# Définir un réseau de neurones simple
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(20, 1)
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
# Créer un modèle et une entrée
model = SimpleNet()
input = torch.randn(5, 10)
output = model(input)
print(output)
Exemple : Classification d'images avec CNN
import torch
import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
# Couche convolutionnelle
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
# Couche de pooling
self.pool = nn.MaxPool2d(2, 2)
# Normalisation par lots
self.bn1 = nn.BatchNorm2d(16)
self.bn2 = nn.BatchNorm2d(32)
self.bn3 = nn.BatchNorm2d(64)
# Fonction d'activation
self.relu = nn.ReLU()
# Couche entièrement connectée
self.fc1 = nn.Linear(64 * 4 * 4, 256)
self.fc2 = nn.Linear(256, 10)
# Dropout
self.dropout = nn.Dropout(0.5)
def forward(self, x):
# Conv -> BN -> ReLU -> Pool
x = self.pool(self.relu(self.bn1(self.conv1(x))))
x = self.pool(self.relu(self.bn2(self.conv2(x))))
x = self.pool(self.relu(self.bn3(self.conv3(x))))
# Flatten
x = x.view(x.size(0), -1)
# FC -> ReLU -> Dropout -> FC
x = self.dropout(self.relu(self.fc1(x)))
x = self.fc2(x)
return x
# Créer le modèle
model = CNN()
print(model)
# Tester la propagation avant
input_tensor = torch.randn(1, 3, 32, 32)
output = model(input_tensor)
print("Forme de sortie :", output.shape)
import torch.nn as nn
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
# Couche convolutionnelle
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)
self.conv3 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
# Couche de pooling
self.pool = nn.MaxPool2d(2, 2)
# Normalisation par lots
self.bn1 = nn.BatchNorm2d(16)
self.bn2 = nn.BatchNorm2d(32)
self.bn3 = nn.BatchNorm2d(64)
# Fonction d'activation
self.relu = nn.ReLU()
# Couche entièrement connectée
self.fc1 = nn.Linear(64 * 4 * 4, 256)
self.fc2 = nn.Linear(256, 10)
# Dropout
self.dropout = nn.Dropout(0.5)
def forward(self, x):
# Conv -> BN -> ReLU -> Pool
x = self.pool(self.relu(self.bn1(self.conv1(x))))
x = self.pool(self.relu(self.bn2(self.conv2(x))))
x = self.pool(self.relu(self.bn3(self.conv3(x))))
# Flatten
x = x.view(x.size(0), -1)
# FC -> ReLU -> Dropout -> FC
x = self.dropout(self.relu(self.fc1(x)))
x = self.fc2(x)
return x
# Créer le modèle
model = CNN()
print(model)
# Tester la propagation avant
input_tensor = torch.randn(1, 3, 32, 32)
output = model(input_tensor)
print("Forme de sortie :", output.shape)
Exemple : Classification de texte avec LSTM
import torch
import torch.nn as nn
class LSTMClassifier(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers, output_dim):
super(LSTMClassifier, self).__init__()
# Couche d'embedding
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
# Couche LSTM
self.lstm = nn.LSTM(
embedding_dim,
hidden_dim,
num_layers=num_layers,
batch_first=True,
bidirectional=True,
dropout=0.5
)
# Couche entièrement connectée
self.fc = nn.Linear(hidden_dim * 2, output_dim)
# Dropout
self.dropout = nn.Dropout(0.5)
def forward(self, text, text_lengths):
# Plongement
embedded = self.embedding(text)
# Empaqueter les séquences pour gérer les entrées de longueur variable
packed = nn.utils.rnn.pack_padded_sequence(
embedded, text_lengths.cpu(), batch_first=True, enforce_sorted=False
)
# LSTM
packed_output, (hidden, cell) = self.lstm(packed)
# Dépaqueter
output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output, batch_first=True)
# Fusionner les états cachés finaux bidirectionnels
hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)
# Dropout et couche entièrement connectée
hidden = self.dropout(hidden)
output = self.fc(hidden)
return output
# Paramètres
vocab_size = 10000
embedding_dim = 128
hidden_dim = 256
num_layers = 2
output_dim = 5 # 5 classes
# Créer le modèle
model = LSTMClassifier(vocab_size, embedding_dim, hidden_dim, num_layers, output_dim)
print(model)
import torch.nn as nn
class LSTMClassifier(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers, output_dim):
super(LSTMClassifier, self).__init__()
# Couche d'embedding
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
# Couche LSTM
self.lstm = nn.LSTM(
embedding_dim,
hidden_dim,
num_layers=num_layers,
batch_first=True,
bidirectional=True,
dropout=0.5
)
# Couche entièrement connectée
self.fc = nn.Linear(hidden_dim * 2, output_dim)
# Dropout
self.dropout = nn.Dropout(0.5)
def forward(self, text, text_lengths):
# Plongement
embedded = self.embedding(text)
# Empaqueter les séquences pour gérer les entrées de longueur variable
packed = nn.utils.rnn.pack_padded_sequence(
embedded, text_lengths.cpu(), batch_first=True, enforce_sorted=False
)
# LSTM
packed_output, (hidden, cell) = self.lstm(packed)
# Dépaqueter
output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output, batch_first=True)
# Fusionner les états cachés finaux bidirectionnels
hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim=1)
# Dropout et couche entièrement connectée
hidden = self.dropout(hidden)
output = self.fc(hidden)
return output
# Paramètres
vocab_size = 10000
embedding_dim = 128
hidden_dim = 256
num_layers = 2
output_dim = 5 # 5 classes
# Créer le modèle
model = LSTMClassifier(vocab_size, embedding_dim, hidden_dim, num_layers, output_dim)
print(model)
Exemple : Utilisation d'un encodeur Transformer
import torch
import torch.nn as nn
class TransformerClassifier(nn.Module):
def __init__(self, input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout):
super(TransformerClassifier, self).__init__()
# Couche d'embedding
self.embedding = nn.Linear(input_dim, d_model)
# Encodage positionnel
self.positional_encoding = nn.Parameter(torch.randn(1, 1000, d_model) * 0.1)
# Couche d'encodeur Transformer
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
dropout=dropout,
batch_first=True
)
# Encodeur Transformer
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Tête de classification
self.fc = nn.Linear(d_model, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# Ajouter un encodage positionnel
seq_len = x.size(1)
x = self.embedding(x) + self.positional_encoding[:, :seq_len, :]
# Encodage Transformer
x = self.transformer_encoder(x)
# Utiliser la sortie à la première position pour la classification (similaire au token CLS)
x = x[:, 0, :]
x = self.dropout(x)
x = self.fc(x)
return x
# Paramètres
input_dim = 512
d_model = 512
nhead = 8
num_layers = 6
dim_feedforward = 2048
output_dim = 10
dropout = 0.1
# Créer le modèle
model = TransformerClassifier(input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout)
print(model)
# Test
x = torch.randn(32, 100, input_dim) # batch_size=32, seq_len=100
output = model(x)
print("Forme de sortie :", output.shape) # (32, 10)
import torch.nn as nn
class TransformerClassifier(nn.Module):
def __init__(self, input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout):
super(TransformerClassifier, self).__init__()
# Couche d'embedding
self.embedding = nn.Linear(input_dim, d_model)
# Encodage positionnel
self.positional_encoding = nn.Parameter(torch.randn(1, 1000, d_model) * 0.1)
# Couche d'encodeur Transformer
encoder_layer = nn.TransformerEncoderLayer(
d_model=d_model,
nhead=nhead,
dim_feedforward=dim_feedforward,
dropout=dropout,
batch_first=True
)
# Encodeur Transformer
self.transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Tête de classification
self.fc = nn.Linear(d_model, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
# Ajouter un encodage positionnel
seq_len = x.size(1)
x = self.embedding(x) + self.positional_encoding[:, :seq_len, :]
# Encodage Transformer
x = self.transformer_encoder(x)
# Utiliser la sortie à la première position pour la classification (similaire au token CLS)
x = x[:, 0, :]
x = self.dropout(x)
x = self.fc(x)
return x
# Paramètres
input_dim = 512
d_model = 512
nhead = 8
num_layers = 6
dim_feedforward = 2048
output_dim = 10
dropout = 0.1
# Créer le modèle
model = TransformerClassifier(input_dim, d_model, nhead, num_layers, dim_feedforward, output_dim, dropout)
print(model)
# Test
x = torch.randn(32, 100, input_dim) # batch_size=32, seq_len=100
output = model(x)
print("Forme de sortie :", output.shape) # (32, 10)
Si vous avez besoin d'informations plus détaillées, vous pouvez vous référer àla documentation officielle PyTorch。
Autres extensions