পাঠ ১৯ · ৪০-এর মধ্যে · মডিউল ৩

Receptive Field বোঝা

Receptive fields — what each neuron sees
৬ মিনিট পড়া মাঝারি · Intermediate PyTorch hands-on

এই পাঠে যা শিখবেন

  • Receptive field-এর সংজ্ঞা — input-এ একটি neuron-এর "view"
  • RF সূত্র — kernel, stride, layer-এর সাথে কীভাবে বাড়ে
  • Effective receptive field — Gaussian-শাপ ও কম্পেক্ট
  • Dilated convolution — RF বাড়ান কিন্তু parameter একই
  • PyTorch দিয়ে RF calculate করা

১ · Receptive Field — মূল ধারণা

একটি deep CNN-এর শেষ feature map-এ একটি pixel আসলে input image-এর কোন region থেকে তৈরি? এই region-ই receptive field।

Receptive Field

একটি output unit-এর receptive field = input pixel-গুলোর সেই region — যাদের value পরিবর্তন করলে সেই output unit-এর value পরিবর্তন হয়।

RF যত বড়, neuron তত বড় context "দেখে"। ছোট RF — local feature (edge)। বড় RF — global feature (object)।

ভাবুন আপনি একজন journalist। শুরুতে আপনার ছোট beat — শুধু এক পাড়ার খবর (local RF)। অভিজ্ঞতা ও সংযোগ বাড়ার সাথে — পুরো শহর, পুরো দেশের খবরের সংশ্লেষ করতে পারেন (global RF)। CNN-ও তাই — layer যত গভীর, RF তত বিস্তৃত।

২ · RF সূত্র — recursive

Layer $\ell$-এর receptive field $r_\ell$:

$$r_\ell = r_{\ell-1} + (k_\ell - 1) \cdot \prod_{i=1}^{\ell-1} s_i$$

যেখানে $k_\ell$ — layer $\ell$-এর kernel size, $s_i$ — পূর্ববর্তী layer-গুলোর stride। Initial: $r_0 = 1$।

একটি ছোট উদাহরণ: তিনটি $3 \times 3$ conv (stride 1):

  • $r_0 = 1$
  • $r_1 = 1 + (3-1) \cdot 1 = 3$
  • $r_2 = 3 + (3-1) \cdot 1 = 5$
  • $r_3 = 5 + (3-1) \cdot 1 = 7$

তিনটি $3 \times 3$ stack = একটি $7 \times 7$-এর সমান RF। (একটি $5 \times 5$ stack = $5$, পরিচিত VGG result)।

৩ · Stride-এর dramatic effect

একটি $3 \times 3$ conv stride 2 + একটি $3 \times 3$ conv stride 1:

  • $r_0 = 1$
  • $r_1 = 1 + (3-1) \cdot 1 = 3$ (stride 1 in formula's product = 1, since $i < 1$)
  • $r_2 = 3 + (3-1) \cdot 2 = 7$ (পূর্ববর্তী stride 2)

Stride RF-কে multiplicatively scale করে — তাই pooling/stride deep network-এ critical।

৪ · ResNet-50-এর RF

  • Stem: 7×7 conv stride 2 + 3×3 maxpool stride 2 → RF ~ 35
  • Stage 1: 3 blocks (3×3 conv) → RF ~ 67
  • Stage 2: stride 2 + 4 blocks → RF ~ 195
  • Stage 3: stride 2 + 6 blocks → RF ~ 427
  • Stage 4: stride 2 + 3 blocks → RF ~ 483

ResNet-50-এর শেষ layer-এর RF $\approx 483$ — input $224 \times 224$-এর চেয়ে বড়! কিন্তু effective RF অনেক কম।

৫ · Effective Receptive Field — Luo et al. (২০১৬)

Theoretical RF-এ সব pixel সমান contribution ধরা হয়। বাস্তবে — center pixel-গুলোর contribution সবচেয়ে বেশি, কোণার pixel কম। Gradient flow Gaussian-শাপ।

  • Theoretical RF $483$ — effective হয়তো $80-100$।
  • Center heavy — কোণার pixel-এ output insensitive।
  • সমাধান — dilation, larger kernel, attention।
Effective Receptive Field (ERF)

ERF = $\sqrt{N} \cdot \sigma$ scale ($N$ = stacked layers)। Theoretical এর $\sqrt{N}$ root বৃদ্ধি, linear না।

Receptive Field — depth-এর সাথে কীভাবে বাড়ে 3×3 conv stack — RF: 1 → 3 → 5 → 7 L0 (input) RF = 1 L1 (3×3 conv) RF = 3 L2 (+ 3×3) RF = 5 L3 (+ 3×3) RF = 7 Effective RF (Gaussian) — center heavy Theoretical RF বড় — কিন্তু center pixel dominate
Receptive field — প্রতিটি conv layer-এ ($k-1$) করে বাড়ে। Effective RF Gaussian, center-heavy।

৬ · Dilated convolution — RF বাড়ান cheap

Dilation rate $d$ — kernel-এর pixel-গুলোর মধ্যে $d-1$ টি গর্ত। Effective kernel size: $k + (k-1)(d-1)$।

  • $3 \times 3$, dilation $2$ → effective $5 \times 5$, parameter ৯টি।
  • $3 \times 3$, dilation $4$ → effective $9 \times 9$।
  • DeepLab segmentation — dilated conv stack — RF বড়, resolution preserved।
Python · PyTorch
import torch.nn as nn

# Standard 3x3
conv1 = nn.Conv2d(64, 64, 3, padding=1)
# Dilated 3x3 (effective 5x5)
conv2 = nn.Conv2d(64, 64, 3, padding=2, dilation=2)
# Dilated 3x3 (effective 7x7)
conv3 = nn.Conv2d(64, 64, 3, padding=3, dilation=3)

print("Standard:  ", sum(p.numel() for p in conv1.parameters()))
print("Dilated 2x:", sum(p.numel() for p in conv2.parameters()))
print("Dilated 3x:", sum(p.numel() for p in conv3.parameters()))
# একই parameter — RF অনেক বড়

    

৭ · RF calculator — হাতে-কলমে

Python · NumPy
# RF, effective stride, padding tracker
def rf_track(layers):
    """layers = [(kernel, stride, dilation), ...]"""
    r, j = 1, 1  # r = RF, j = jump (effective stride)
    for k, s, d in layers:
        k_eff = k + (k - 1) * (d - 1)
        r = r + (k_eff - 1) * j
        j = j * s
    return r, j

# VGG-16-এর প্রথম block: 2 x (3x3 stride 1) + (2x2 pool stride 2)
vgg_block = [
    (3, 1, 1),  # conv
    (3, 1, 1),  # conv
    (2, 2, 1),  # maxpool
]
rf, jump = rf_track(vgg_block)
print(f"VGG block 1 — RF: {rf}, effective stride: {jump}")
# Block 2 add করলে RF আরও বাড়ে

full_vgg = vgg_block + [
    (3, 1, 1), (3, 1, 1), (2, 2, 1),
    (3, 1, 1), (3, 1, 1), (3, 1, 1), (2, 2, 1),
]
rf, jump = rf_track(full_vgg)
print(f"VGG-13 partial — RF: {rf}, jump: {jump}")

    

৮ · Practical implications

  • Object detection: RF ≥ object size, না হলে object-কে "complete" দেখা যাবে না।
  • Segmentation: per-pixel prediction — context (RF) যথেষ্ট।
  • Small object: low-level feature map (small RF) থেকে detect — FPN idea।
  • Texture: small RF যথেষ্ট।
  • Scene understanding: বড় RF দরকার।
"Bigger RF = better" সবসময় না। অপ্রয়োজনে বড় RF — irrelevant context, distraction। Architecture design-এ task-aware RF।

৯ · ViT-এর global RF

  • Vision Transformer — first layer থেকেই global attention — full image RF।
  • CNN-এ deep layer-এও local-ish; ViT-এ shallow layer-ও global।
  • Trade-off — ViT data hungry (inductive bias কম)।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ "Theoretical RF বড়, effective RF ছোট" — Luo et al. (২০১৬)। কেন এই gap? ছোট object detect করতে কীভাবে কাজে লাগে?

Effective RF — empirical phenomenon, theoretical analysis-এর সাথে discrepancy। Object detection এর জন্য critical।

Theoretical vs effective:

  • Theoretical — সব input pixel equal influence assume।
  • Effective — gradient-flow weighted contribution।
  • Center pixel — multiple paths, edges — fewer।
  • Gaussian-shaped attention।

Why Gaussian shape?

  • Random weight initialization।
  • Center পাথ — convolution-এ direct contribution।
  • Edge — fewer convolutional paths।
  • Central limit theorem-এর effect।

Mathematical intuition:

  • $N$-layer stack → effective RF ~ $\sqrt{N} \cdot \sigma$।
  • Linear layer growth — sub-linear ERF।
  • "Most learning happens in central region"।

Implications for detection:

  • Small object → small RF needed → shallow features।
  • Large object → big RF → deep features।
  • Multi-scale architecture necessary।

FPN (Feature Pyramid Network):

  • Lin et al. (২০১৭) — Detection-এ multi-scale।
  • Top-down pathway — high-level feature low-resolution।
  • Lateral connection — fine resolution merge।
  • Each pyramid level — different effective RF।

FPN architecture:

P5 (deep, low-res, large RF)
  ↓ upsample
P4 (mid, mid-res, mid RF) ← lateral
  ↓ upsample
P3 (shallow, high-res, small RF) ← lateral
  ↓ upsample
P2 (shallowest, highest res)

Detection at each scale:

  • P2/P3 — small object।
  • P4/P5 — large object।
  • Per-scale anchor optimal।

Modern advances:

  • BiFPN (EfficientDet): bidirectional fusion।
  • NAS-FPN: architecture search।
  • PANet: bottom-up augmentation।

Receptive field design rules:

  • Object size ≤ effective RF।
  • Multi-scale features for varied object sizes।
  • Atrous/dilation for compact RF expansion।
  • Attention for adaptive RF।

Bangladesh use cases:

  • License plate detection — wide aspect, multiple scales।
  • Crop disease detection — leaf spots small।
  • Crowd counting — distant heads small।
  • Multi-scale FPN আদর্শ।

Visualization tools:

  • Activation maximization — RF visualize।
  • Gradient-based — effective RF measure।
  • CAM — class-relevant region।

মূল উপলব্ধি: Theoretical RF — paper number। Effective RF — practical reality। Gap exists, design must account। FPN — multi-scale solution। Detection-এ universal। Bangladesh detection task — FPN backbone + task-specific augmentation। Effective RF awareness — better architecture decision।

প্র ০২ Dilated convolution semantic segmentation-এ revolution আনল (DeepLab)। কেন standard pool RF বাড়ালে segmentation-এ কাজ করে না?

Semantic segmentation — পুরো image-এ per-pixel class prediction। Resolution এবং context — দু'টোই দরকার।

Standard CNN problem:

  • Pool layer — RF বাড়ায় কিন্তু resolution কমায়।
  • $224 \times 224$ → $7 \times 7$ feature map।
  • Per-pixel prediction এর জন্য — কীভাবে $7 \times 7$ থেকে $224 \times 224$ output?
  • Upsampling spatial detail recover-এ কঠিন।

FCN approach (২০১৫):

  • Long-Shelhamer-Darrell — Fully Convolutional Network।
  • Pool-based downsample + transposed conv upsample।
  • Skip connections — fine details preserve।
  • Initial breakthrough কিন্তু blurry boundary।

DeepLab (২০১৪+):

  • Chen et al. — Atrous (dilated) convolution।
  • Pool-এর জায়গায় dilated conv।
  • Resolution preserve + RF বাড়ে।
  • Segmentation accuracy major jump।

Atrous Spatial Pyramid Pooling (ASPP):

  • Multiple dilation rate parallel — 1, 6, 12, 18।
  • Different scale context capture।
  • Concatenate → fused feature।
  • Multi-scale segmentation।

Implementation:

class ASPP(nn.Module):
    def __init__(self, in_ch, out_ch=256):
        super().__init__()
        self.branches = nn.ModuleList([
            nn.Conv2d(in_ch, out_ch, 1),
            nn.Conv2d(in_ch, out_ch, 3, padding=6, dilation=6),
            nn.Conv2d(in_ch, out_ch, 3, padding=12, dilation=12),
            nn.Conv2d(in_ch, out_ch, 3, padding=18, dilation=18),
        ])
        self.fuse = nn.Conv2d(out_ch * 4, out_ch, 1)
    def forward(self, x):
        feats = [b(x) for b in self.branches]
        return self.fuse(torch.cat(feats, 1))

Why dilation works:

  • RF expand without resolution loss।
  • Parameter cost minimal।
  • Multi-scale natural।
  • Boundary preservation better।

Limitations of dilation:

  • Gridding artifact — sparse sampling।
  • Memory cost — feature map বড় থাকে।
  • Computation cost — high resolution-এ দীর্ঘ।
  • Hybrid Atrous (HDC) — gridding mitigate।

Modern alternatives:

  • U-Net: encoder-decoder + skip — medical imaging gold।
  • SegFormer: Vision Transformer + lightweight head।
  • Mask2Former: attention-based universal segmentation।

U-Net specifics:

  • Encoder downsample — context।
  • Decoder upsample — resolution।
  • Skip connections — fine details।
  • Medical imaging-এ standard।

Bangladesh segmentation use:

  • Medical: tumor segmentation, organ delineation।
  • Agriculture: crop boundary, disease area।
  • Satellite: land use, building detection।
  • Document: Bangla text region detection।

Evaluation metrics:

  • IoU (Intersection over Union)।
  • Dice coefficient।
  • Per-class accuracy (class imbalance)।
  • Boundary F-measure।

মূল উপলব্ধি: Segmentation-এ resolution + context dual demand। Pool resolution হত্যা করে — dilation alternative। DeepLab series বিপ্লব — atrous + ASPP। U-Net medical-এ gold। Modern transformer-based architecture rising। Bangladesh segmentation — domain-specific architecture choice + augmentation key।

প্র ০৩ Vision Transformer-এর first layer থেকেই global RF — CNN-এর চেয়ে কেন এটা বিপ্লব? Trade-off কী?

ViT (Dosovitskiy ২০২০) — pure transformer image classification। CNN-এর সাথে fundamental architectural difference।

CNN RF growth — slow:

  • Each conv layer linear RF increase।
  • 50-layer ResNet — RF ~500 (theoretical), effective ~100।
  • Hierarchical — local → global gradual।

ViT RF — instant global:

  • Patch attention — every patch sees every patch।
  • Layer 1 থেকেই full image RF।
  • No locality bias।

Architecture:

  • Image → 16×16 patches।
  • $224 \times 224 \to 14 \times 14 = 196$ patches।
  • Each patch → embedding vector।
  • Transformer block stack।

Why "revolutionary":

  • Single architecture for vision + language।
  • Scale-friendly — bigger model, more data, better।
  • Inductive bias minimal — flexibility।
  • SOTA results on multiple benchmarks।

Trade-off — data hunger:

  • CNN — image-friendly inductive bias।
  • ViT — bias none, must learn from data।
  • JFT-300M (Google internal) — ViT shines।
  • ImageNet-1M — CNN comparable।

Empirical observations:

  • Small data — CNN better।
  • Large data — ViT scales better।
  • Hybrid — CNN stem + ViT body — সবসময় ভাল।

Compute trade-off:

  • Attention quadratic in patches।
  • Long-range powerful কিন্তু expensive।
  • Memory significant।

Modern ViT improvements:

  • Swin Transformer: local windows + shifted।
  • DeiT: distillation efficient training।
  • BeIT: BERT-style pre-training।
  • DINO: self-supervised।

Hybrid architectures:

  • ConvNeXt — modernized CNN matching ViT।
  • CoAtNet — Conv + Attention।
  • EfficientNet ViT hybrid।

Modern best practice:

  • ImageNet-1M pretrain — Swin/ConvNeXt comparable।
  • Self-supervised (DINO) — ViT excellent।
  • Multi-modal (CLIP) — ViT preferred।

Bangladesh deployment:

  • Limited data — CNN preferred।
  • Pre-trained ViT fine-tune — works।
  • Edge device — CNN smaller।
  • Cloud inference — ViT acceptable।

Future direction:

  • Multi-modal foundation models।
  • Vision + language unified।
  • Few-shot learning।
  • Generative + discriminative।

মূল উপলব্ধি: ViT — global RF instant from layer 1। CNN-এর hierarchical গঠন বদলে — direct attention। Data hungry কিন্তু scale powerful। Modern computer vision dual ecosystem — CNN, ViT, hybrid। Bangladesh-এ — task + data-এর উপর depend। Foundation model era — multi-modal, scaling, self-supervision।

প্র ০৪ Bangladesh-এর rice paddy থেকে drone image — pest detection বানাচ্ছেন। Pest ছোট (10-20 pixel)। RF কীভাবে design করবেন?

Small object detection — computer vision-এর কঠিনতম problem। Drone agriculture-এ practical importance।

Problem analysis:

  • Drone image: 4K (3840×2160) typical।
  • Pest: 10-20 pixel (rice plant brown spot, leaf hopper)।
  • Aspect: typically square।
  • Density: clustered or sparse।

RF requirement:

  • Pest size 20px — RF ≥ 30-50px (some context)।
  • Standard ResNet — RF ~480 — overkill, miss small।
  • Need: shallow + multi-scale।

Architecture choice:

  • FPN backbone: ResNet50 + FPN।
  • P2 (1/4) — small pest detection।
  • P3-P5 — context for verification।
  • RetinaNet style detector।

Patch-based training:

  • 4K image → 512×512 patches।
  • Overlap 64 pixel — boundary objects।
  • Train on patch — efficient।
  • Inference — sliding window।

Anchor design:

  • Small anchor: 8, 16, 32 pixel।
  • Aspect ratio: 1:1, 1:2, 2:1।
  • Per-level anchor — small for P2, large for P5।

Loss specifics:

  • Focal loss — class imbalance (background 99%)।
  • GIoU — better small object localization।
  • Hard example mining।

Augmentation:

transforms = A.Compose([
    A.RandomScale(scale_limit=0.3, p=0.5),
    A.RandomRotate90(p=0.5),
    A.HorizontalFlip(p=0.5),
    A.Mosaic(p=0.5),  # combine 4 images
    A.MixUp(p=0.3),
    A.RandomBrightnessContrast(0.2, 0.2),
    A.HueSaturationValue(20, 30, 20),
    A.GaussianBlur(blur_limit=3, p=0.3),
])

Mosaic augmentation:

  • YOLOv4 introduced।
  • 4 images combine — diverse context।
  • Small object effective training।
  • Critical for small pest।

Data labeling:

  • Expert agronomist labeling।
  • Bounding box tight।
  • Multi-class: brown plant hopper, stem borer, etc.।
  • Iterative active learning।

Bangladesh-specific challenges:

  • Monsoon — drone image quality vary।
  • Crop variety — Boro, Aman, Aush different appearance।
  • Pest seasonality — annual pattern।
  • Limited labeled data।

Pre-training strategy:

  • ImageNet pre-trained backbone।
  • Crop disease open dataset (PlantVillage)।
  • Self-supervised on unlabeled drone images।
  • Fine-tune on labeled subset।

Inference deployment:

  • Drone onboard — Jetson Nano/Xavier।
  • Quantized YOLOv5 small।
  • Real-time 30 FPS।
  • Cloud sync — flight data।

Field considerations:

  • Drone altitude consistent — 5-10m।
  • GPS coordinate per detection।
  • Spray application targeted।
  • Farmer mobile app — Bangla UI।

Validation strategy:

  • Field-wise hold-out।
  • Season-wise split।
  • Variety-wise generalization test।
  • Expert validation।

Economic value:

  • Early detection — yield save।
  • Targeted spray — pesticide reduce।
  • Cost saving farmer।
  • Environmental benefit।

মূল উপলব্ধি: Small object detection — RF careful balance। Multi-scale FPN + small anchors essential। Mosaic augmentation small object boost। Bangladesh agriculture — drone + AI promising। Practical pipeline — patch training + onboard inference + Bangla farmer interface। Receptive field theory practice transformation।

অনুশীলন

  1. RF calculation: ৩টি $3 \times 3$ conv (stride 1) + একটি $2 \times 2$ pool (stride 2) — সমষ্টিগত RF কত?

    $r_0=1$, $r_1=3$, $r_2=5$, $r_3=7$ (jump=1 throughout)। Pool: $r_4 = 7 + (2-1) \cdot 1 = 8$, jump = $2$।

  2. Dilation: $3 \times 3$ conv, dilation $4$ — effective kernel size কত?

    $k_{\text{eff}} = k + (k-1)(d-1) = 3 + 2 \cdot 3 = 9$. Effective $9 \times 9$, parameter ৯টি।

  3. Code: দু'টি conv block — একটি standard, একটি dilated — তৈরি ও parameter মিলিয়ে দেখুন।
    std    = nn.Conv2d(64, 64, 3, padding=1)
    dilated = nn.Conv2d(64, 64, 3, padding=4, dilation=4)
    
    print("Standard params:", sum(p.numel() for p in std.parameters()))
    print("Dilated params: ", sum(p.numel() for p in dilated.parameters()))
    # একই — RF dramatically different

আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ

কোড রানার কাজ না করলে? ব্রাউজারে কাজ না করলে Google Colab ব্যবহার করুন — Google-এর ফ্রি অনলাইন Python পরিবেশ, শুধু Gmail অ্যাকাউন্ট লাগে।
পূর্ববর্তী পাঠ
পাঠ ১৮ · Pooling