ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Advanced CNNs for Computer Vision Applications
Chapter 1: Revisiting CNN Foundations and Modern Architectures
Brief Review of CNN Building Blocks
Evolution of CNN Architectures: AlexNet to ResNet
Understanding Residual Connections and Skip Architectures
Inception Modules and Network-in-Network Concepts
DenseNet: Architecture and Connectivity Patterns
EfficientNet: Compound Scaling for Models
Architectural Design Choices and Trade-offs
Implementing Modern Architectures Practice
Chapter 2: Advanced Training and Optimization Techniques
Advanced Optimization Algorithms
Learning Rate Schedules and Cyclical Learning Rates
Regularization Revisited: Advanced Techniques
Batch Normalization Internals and Alternatives
Weight Initialization Strategies for Deep Networks
Gradient Clipping and Gradient Flow Mitigation
Mixed Precision Training Fundamentals
Debugging and Monitoring Deep CNN Training
Hands-on Practical: Implementing Advanced Training Loops
Chapter 3: Object Detection Algorithms
Two-Stage Detectors: R-CNN Family
Region Proposal Networks Explained
Single-Stage Detectors: YOLO Family
Single-Stage Detectors: SSD and RetinaNet
Anchor Boxes: Design and Refinement
Non-Maximum Suppression Variants
Evaluation Metrics for Object Detection
Implementing an Object Detector Practice
Chapter 4: Image Segmentation Techniques
Semantic Segmentation vs. Instance Segmentation
Fully Convolutional Networks for Segmentation
Encoder-Decoder Architectures: U-Net and SegNet
Dilated (Atrous) Convolutions for Segmentation
DeepLab Family: Atrous Spatial Pyramid Pooling
Instance Segmentation Approaches (Mask R-CNN)
Evaluation Metrics for Segmentation
Hands-on Practical: Building a Semantic Segmentation Model
Chapter 5: Attention Mechanisms and Transformers in Vision
Self-Attention Mechanisms in CNNs
Non-local Neural Networks
Introduction to Vision Transformers
ViT Architecture: Patches, Embeddings, Transformer Encoder
Hybrid CNN-Transformer Models
Comparing CNNs and Transformers for Vision Tasks
Implementing Attention Blocks in CNNs Practice
Chapter 6: Advanced Transfer Learning and Domain Adaptation
Revisiting Transfer Learning Strategies
Fine-tuning vs. Feature Extraction: Advanced Considerations
Adapting Models to Different Data Distributions
Domain Generalization Concepts
Few-Shot Learning with CNNs
Self-Supervised Learning Pre-training for Vision
Hands-on Practical: Fine-tuning Models on Specialized Datasets
Chapter 7: Generative Adversarial Networks for Image Synthesis
GAN Fundamentals Revisited
Challenges in Training GANs
Deep Convolutional GANs (DCGANs)
Conditional GANs for Controlled Generation
StyleGAN Architecture and Style-Based Generation
Evaluation Metrics for GANs
Implementing a DCGAN for Image Generation Practice
Chapter 8: Model Compression and Efficient Deep Learning
Motivation for Efficient Models
Network Pruning Techniques
Knowledge Distillation Methods
Quantization: Reducing Model Precision
Designing Efficient Architectures
Neural Architecture Search Overview
Hands-on Practical: Applying Pruning and Quantization

Non-local Neural Networks

Standard convolutional layers operate locally, processing information within a confined neighborhood defined by the kernel size. While stacking these layers increases the effective receptive field, efficiently capturing dependencies between spatially distant features (long-range dependencies) remains challenging. For instance, understanding the relationship between a person holding an object and the object itself, even if they appear far apart in the image, requires modeling interactions outside immediate adjacency.

Non-local Neural Networks directly address this limitation by computing the response at a position as a weighted sum of features at all positions in the input feature map. This allows the network to capture global context and model relationships between any two locations, regardless of their spatial distance. Think of it as a generalization of self-attention mechanisms applied to spatial or spatio-temporal data.

The Non-local Operation

The core idea is elegantly captured in a general formula for a non-local operation. Given an input feature map x\mathbf{x}x (which could be an image, or feature maps from intermediate layers of a CNN), the output feature map y\mathbf{y}y at a position iii is computed as:

yi=1C(x)∑∀jf(xi,xj)g(xj)\mathbf{y}_i = \frac{1}{\mathcal{C}(\mathbf{x})} \sum_{\forall j} f(\mathbf{x}_i, \mathbf{x}_j) g(\mathbf{x}_j)yi​=C(x)1​∀j∑​f(xi​,xj​)g(xj​)

Let's break down the components:

  • iii: The index of the output position whose response is being calculated.
  • jjj: An index that iterates over all possible positions in the input feature map.
  • xi\mathbf{x}_ixi​: The feature vector at position iii in the input.
  • xj\mathbf{x}_jxj​: The feature vector at position jjj in the input.
  • f(xi,xj)f(\mathbf{x}_i, \mathbf{x}_j)f(xi​,xj​): A pairwise function that computes a scalar representing the relationship (e.g., affinity or similarity) between position iii and position jjj.
  • g(xj)g(\mathbf{x}_j)g(xj​): A function that computes a representation or transformation of the input feature vector at position jjj. This is often a linear embedding.
  • C(x)\mathcal{C}(\mathbf{x})C(x): A normalization factor, calculated as ∑∀jf(xi,xj)\sum_{\forall j} f(\mathbf{x}_i, \mathbf{x}_j)∑∀j​f(xi​,xj​), ensuring the weights sum appropriately (often to 1, similar to a softmax).

Essentially, the response at position iii (yi\mathbf{y}_iyi​) is a weighted average of the transformed features (g(xj)g(\mathbf{x}_j)g(xj​)) from all positions jjj. The weights are determined by the similarity or relationship (fff) between position iii and each position jjj.

Instantiations of the Pairwise and Transformation Functions

The generic non-local operation formula allows for different specific implementations based on the choice of functions fff and ggg.

Transformation Function ggg: A common choice for ggg is a simple linear embedding learned via a 1×11 \times 11×1 convolution: g(xj)=Wgxjg(\mathbf{x}_j) = W_g \mathbf{x}_jg(xj​)=Wg​xj​ Here, WgW_gWg​ represents the weights of the 1×11 \times 11×1 convolutional layer.

Pairwise Function fff: Several options exist for the pairwise function fff, measuring the relationship between iii and jjj:

  1. Embedded Gaussian: This is perhaps the most common choice and directly relates to self-attention. First, linear embeddings θ\thetaθ and ϕ\phiϕ (again, typically 1×11 \times 11×1 convolutions with weight matrices WθW_{\theta}Wθ​ and WϕW_{\phi}Wϕ​) are applied to the input features. The function is then: f(xi,xj)=eθ(xi)Tϕ(xj)=e(Wθxi)T(Wϕxj)f(\mathbf{x}_i, \mathbf{x}_j) = e^{\theta(\mathbf{x}_i)^T \phi(\mathbf{x}_j)} = e^{(W_{\theta}\mathbf{x}_i)^T (W_{\phi}\mathbf{x}_j)}f(xi​,xj​)=eθ(xi​)Tϕ(xj​)=e(Wθ​xi​)T(Wϕ​xj​) The normalization factor C(x)\mathcal{C}(\mathbf{x})C(x) in this case makes the weighting f(xi,xj)C(x)\frac{f(\mathbf{x}_i, \mathbf{x}_j)}{\mathcal{C}(\mathbf{x})}C(x)f(xi​,xj​)​ equivalent to a softmax function applied over all positions jjj.

  2. Dot Product: A simpler version of the Embedded Gaussian, omitting the exponential: f(xi,xj)=θ(xi)Tϕ(xj)f(\mathbf{x}_i, \mathbf{x}_j) = \theta(\mathbf{x}_i)^T \phi(\mathbf{x}_j)f(xi​,xj​)=θ(xi​)Tϕ(xj​) Here, the normalization C(x)\mathcal{C}(\mathbf{x})C(x) might be the number of positions NNN.

  3. Concatenation: The embedded features are concatenated, passed through a linear layer (with weight vector wfw_fwf​), and activated (e.g., with ReLU): f(xi,xj)=ReLU(wfT[θ(xi),ϕ(xj)])f(\mathbf{x}_i, \mathbf{x}_j) = \text{ReLU}(w_f^T [\theta(\mathbf{x}_i), \phi(\mathbf{x}_j)])f(xi​,xj​)=ReLU(wfT​[θ(xi​),ϕ(xj​)]) This allows for potentially more complex relationship modeling.

The Embedded Gaussian approach is widely used due to its connection to attention mechanisms and empirical success.

Implementing Non-local Blocks

Non-local operations are typically integrated into existing deep learning architectures as "Non-local Blocks". These blocks often employ a residual connection to facilitate training, similar to ResNet blocks.

The structure of a common Non-local Block (using the Embedded Gaussian version) is as follows:

  1. Input: Feature map x\mathbf{x}x (e.g., dimensions H×W×CH \times W \times CH×W×C).
  2. Embeddings: Compute θ(x)\theta(\mathbf{x})θ(x), ϕ(x)\phi(\mathbf{x})ϕ(x), and g(x)g(\mathbf{x})g(x) using separate 1×11 \times 11×1 convolutions. θ\thetaθ and ϕ\phiϕ typically reduce the channel dimension (e.g., to C/2C/2C/2) to save computation, while ggg might maintain or reduce it. Let the outputs be Θ\mathbf{\Theta}Θ, Φ\mathbf{\Phi}Φ, G\mathbf{G}G.
  3. Affinity Calculation: Reshape Θ\mathbf{\Theta}Θ and Φ\mathbf{\Phi}Φ to matrices where one dimension represents the spatial locations (H×WH \times WH×W) and the other represents the channels (C/2C/2C/2). Calculate the dot product ΘTΦ\mathbf{\Theta}^T \mathbf{\Phi}ΘTΦ (after appropriate transpositions). This gives a matrix of size (HW)×(HW)(HW) \times (HW)(HW)×(HW) representing affinities between all pairs of locations.
  4. Normalization: Apply softmax row-wise (or column-wise, depending on matrix setup) to the affinity matrix to get normalized weights A\mathbf{A}A.
  5. Weighted Sum: Reshape G\mathbf{G}G similarly to Θ\mathbf{\Theta}Θ and Φ\mathbf{\Phi}Φ (dimension HW×C′HW \times C'HW×C′). Compute the weighted sum by matrix multiplying the normalized affinities A\mathbf{A}A with G\mathbf{G}G. Let the result be Y′\mathbf{Y}'Y′.
  6. Reshape and Project: Reshape Y′\mathbf{Y}'Y′ back to the spatial dimensions H×W×C′H \times W \times C'H×W×C′. Apply a final 1×11 \times 11×1 convolution (with weights WzW_zWz​) to project it back to the original channel dimension CCC. Let this be Y\mathbf{Y}Y. The weights WzW_zWz​ are often initialized to zero, so the block initially behaves like an identity function.
  7. Residual Connection: Add the output Y\mathbf{Y}Y back to the original input x\mathbf{x}x: z=Y+x\mathbf{z} = \mathbf{Y} + \mathbf{x}z=Y+x.

This structure allows the network to learn long-range dependencies while retaining the original information flow through the residual connection.

Data flow within a Non-local Block using Embedded Gaussian affinity and a residual connection. The θ\thetaθ, ϕ\phiϕ, and ggg transformations are typically implemented using 1×11 \times 11×1 convolutions.

Connection to Self-Attention

If you are familiar with the Transformer architecture, you'll recognize the Embedded Gaussian non-local operation as being equivalent to the scaled dot-product self-attention mechanism.

  • θ(xi)\theta(\mathbf{x}_i)θ(xi​) corresponds to the "Query".
  • ϕ(xj)\phi(\mathbf{x}_j)ϕ(xj​) corresponds to the "Key".
  • g(xj)g(\mathbf{x}_j)g(xj​) corresponds to the "Value".

The non-local block computes the attention weights between each query position iii and all positions jjj, then uses these weights to form a weighted sum of the values. Non-local networks essentially introduced self-attention to the computer vision domain, applying it directly to feature maps rather than sequences of word embeddings.

Applications and Approaches

Non-local blocks have proven effective in tasks where long-range interactions are significant:

  • Video Analysis: Capturing temporal dependencies between frames for action recognition.
  • Object Detection & Segmentation: Modeling context, such as relationships between objects or between object parts and the whole object. Mask R-CNN, for example, benefits from incorporating contextual information.
  • Image Generation: Improving the global coherence and structure of generated images.

However, a significant drawback is computational cost. Calculating the pairwise affinities involves comparing every position with every other position. If the input feature map has N=H×WN = H \times WN=H×W spatial locations, the complexity is O(N2)O(N^2)O(N2), which can be demanding for high-resolution feature maps.

Mitigation Strategies: To manage this cost, implementations often:

  • Reduce channel dimensions via the 1×11 \times 11×1 convolutions in θ\thetaθ, ϕ\phiϕ, and ggg.
  • Apply spatial subsampling (e.g., max-pooling) to the (ϕ\phiϕ) and value (ggg) inputs before the pairwise computations. This reduces the number of positions jjj involved in the sum.
  • Insert Non-local blocks only in deeper layers of the network where feature maps are smaller, or sparingly throughout the architecture.

Non-local networks provide a powerful and general mechanism for incorporating non-local interactions within deep learning models for vision. They represent an important step towards models that can reason about global image structure and context, complementing the local feature extraction capabilities of standard convolutions and leading to architectures like Vision Transformers.

  • Non-local Neural Networks, Xiaolong Wang, Ross Girshick, Abhinav Gupta, Kaiming He, 2018 Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR) (IEEE Computer Society) DOI: 10.1109/CVPR.2018.00813 - Introduces the Non-local Neural Network architecture, its general formulation, and specific instantiations, serving as the primary source for the section content.
  • Attention Is All You Need, Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin, 2017 Advances in Neural Information Processing Systems (NeurIPS), Vol. 30 DOI: 10.48550/arXiv.1706.03762 - Presents the Transformer architecture and the self-attention mechanism, which the non-local operation generalizes and is closely related to.
  • An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale, Alexey Dosovitskiy, Lucas Beyer, Alexander Kolesnikov, Dirk Weissenborn, Xiaohua Zhai, Thomas Unterthiner, Mostafa Dehghani, Matthias Minderer, Georg Heigold, Sylvain Gelly, Jakob Uszkoreit, and Neil Houlsby, 2021 International Conference on Learning Representations (ICLR) DOI: 10.48550/arXiv.2010.11929 - Introduces the Vision Transformer (ViT) model, demonstrating how to apply the Transformer architecture and self-attention effectively to image classification, building upon global context modeling.

© 2026 ApX Machine Learning