← Return to Portfolio

By Rommel Sharma · LinkedIn

1. Introduction & Project Objective

Wildlife monitoring relies heavily on camera traps to track endangered animal populations. Historically, researchers had to manually inspect thousands of photos to match individual animals based on their unique coat pattern markings. This project establishes an automated, deep learning pipeline designed to solve the Jaguar Re-Identification (Re-ID) problem by transforming visual pattern matching into a high-dimensional metric learning task.

Instead of matching an image to a fixed set of labels, the system learns to convert raw camera trap images into compact mathematical numerical vectors (embeddings). When two photos feature the same jaguar, their resulting vectors sit close together in vector space; if the photos feature different jaguars, their vectors sit far apart.

2. The Problem Context & Challenge

Standard classification networks (which assign images to rigid categories like "Jaguar A" or "Jaguar B") fail in ecological research settings because the population is dynamic. New animals are constantly discovered in the wild. If a new jaguar is found, a traditional classification model requires altering its architecture and retraining from scratch.

Furthermore, real-world data presents massive complexity:

3. Technical Solution Architecture

The final solution balances a strong baseline feature extractor with advanced optimization criteria to build robust, highly generalizable embeddings.

A. Foundation Backbone & Spatial Pooling

The architecture uses a pre-trained **MegaDescriptor-L** backbone (built on top of Meta's DINOv2 Vision Transformer architecture). This foundation model provides exceptional spatial representations optimized specifically for biological contours and textures. To compress the transformer's spatial feature outputs into a final 512-dimensional vector without discarding critical pattern data, **Generalized Mean (GeM) Pooling** is implemented. GeM pooling uses a learnable parameter to adjust how aggressively it highlights prominent features compared to standard average pooling.

B. Dual-Objective Loss Functions

To maximize the separation between different individual jaguars, the network optimizes two distinct loss targets simultaneously during training:

C. Fine-Tuning Stability with LLRD

Large vision transformers are highly prone to "catastrophic forgetting" or severe overfitting when fine-tuned on small datasets. To protect the foundational knowledge captured by the backbone, **Layer-wise Learning Rate Decay (LLRD)** is used.

Example Instead of applying a uniform learning rate across the entire network, the lower layers closest to the raw image data use a highly conservative learning rate (decaying by a factor of 0.8 per layer backwards), while the brand-new classification head uses a learning rate ten times larger. This keeps foundational edge-and-shape detectors intact while allowing the top layers to adapt to jaguar spot layouts.

4. Engineering Insights & Lessons Learned

Building the solution highlighted that model performance often stems from catching silent infrastructure and execution failures rather than tweaking arbitrary hyperparameters. Key design evolutions included:

A. Fixing Broken State Management

Early iterations suffered from a hidden bug where training runs would occasionally timeout or crash on shared cluster infrastructure. While a simple checkpoint was reloaded, the internal state tracker of the *Early Stopping* mechanism was discarded upon restart. This caused the model to inadvertently save suboptimal weights. The solution was refactored to treat early stopping metrics as a stateful dictionary saved directly inside the model artifact file, ensuring consistent evaluations across pipeline preemptions.

B. Resolving Checkpoint Shape Mismatches

When swapping between different model variations, variations in the dense classification head layer weights caused initialization shape errors. Building an explicit custom layer mapping utility ensured that only the backbone transformer weights were reloaded cleanly during cross-validation folds, safely ignoring target layer dimension differences.

C. Overcoming Disk Input/Output Constraints

Kaggle environment runtimes impose strict write limits on root filesystems. Generating Test-Time Augmentations (TTA) dynamically across large image sets created significant processing bottlenecks. To overcome this, an execution pipeline was engineered to process embeddings in strict 100-image chunks, saving intermediate representations as compressed NumPy files (`.npz`) directly to a writable staging directory (`/kaggle/working/cache/`) while treating foundational inputs as read-only.

5. Advanced Inference and Retrieval Logic

Evaluating model performance uses the **identity-balanced mean Average Precision (mAP)** metric, which balances out accuracy tracking across individuals with wildly uneven image distributions. At inference time, accuracy is pushed further via automated post-processing:

6. Broader Horizons: Cross-Domain Adaptations

Because this pipeline models identity differences at a foundational pixel texture level rather than relying on a rigid label list, the entire underlying architecture can be redeployed across several industrial and ecological use cases with minimal configuration tweaks:

A. Parallel Ecological Monitoring

The system can instantly transfer to identify other complex fine-grained species. For example, tracking individual leopards or cheetahs via rosette density, identifying zebras via stripe patterns, or monitoring marine life like whales and manta rays using fluke shapes and spot placements.

B. Smart Agriculture & Livestock Tracking

Example Large-scale cattle farms currently rely on invasive physical ear tags or branding to track individual cows. By swapping the training inputs, this exact architecture can identify individual cattle or horses via unique facial structures and natural hair patterns from standard overhead cameras mounted at watering troughs, enabling contactless health tracking.

C. Industrial Asset Management & Supply Chain Search

In manufacturing pipelines, components frequently lack clear serial numbers but carry distinctive structural surface imperfections or wood-grain configurations. This metric learning pipeline can serve as a highly accurate visual search engine to track parts, detect duplicates, or verify product authenticity across logistics networks by matching microscopic item textures.

← Return to Portfolio

Let's Connect

I am always open to discussing new challenges in the AI and Machine Learning space. Whether you are exploring wildlife conservation through the use of technology or how these patterns can be adapted for your specific domain, have questions about the architectural choices detailed above, or are looking to collaborate on impactful technology projects that help the society, I would love to hear from you.

Connect on LinkedIn