CoolFace
Modelpublic

youngPhilosopher/drywall-qa-clipseg

sourceHugging Facemitupdated 6mo agoView on Hugging Face
1likes
Model Card

<p align="center"> <h1 align="center">Prompted Segmentation for Drywall QA</h1> <p align="center"> Text-conditioned binary mask prediction for construction defect detection </p> </p>

Python 3.11 PyTorch HuggingFace CLIPSeg Typst uv MIT

<p align="center"> <a href="#1-methodology">Methodology</a> &bull; <a href="#2-data-preparation">Data Preparation</a> &bull; <a href="#3-results">Results</a> &bull; <a href="#4-failure-cases--potential-solutions">Failure Cases</a> &bull; <a href="#quick-start">Quick Start</a> &bull; Full Report (PDF) </p>


Feed a construction photo and a text prompt. Get a binary segmentation mask back.

Two tasks — crack detection and drywall taping/joint detection — both driven by natural language at inference time. Change the prompt, change what gets segmented. No class heads, no retraining.

Input:  image.jpg  +  "segment wall crack"
Output: image__segment_wall_crack.png   (binary mask, {0, 255})

1. Methodology

Model: CLIPSeg

We fine-tune **CLIPSeg** (Luddecke & Ecker, CVPR 2022) — a text-conditioned segmentation model built on CLIP. The entire CLIP backbone (149.6M params) stays frozen. Only a lightweight 3-block transformer decoder with U-Net skip connections (1.13M params) is trained.

[image]

The model takes an RGB image and a text prompt. The CLIP vision encoder (ViT-B/16) and text encoder independently produce embeddings. The decoder fuses these via cross-attention and generates logits at 352x352, which are thresholded at 0.5 to produce binary masks.

<details> <summary><b>Why CLIPSeg over Grounded SAM, SEEM, X-Decoder?</b></summary>

<br>

CLIPSegGrounded SAMSEEMX-Decoder
Text-to-maskDirectTwo-stage (text → bbox → mask)Multi-modalYes
Small-data fine-tuningProvenModerateDifficultNot ideal
Consumer GPU (Apple M4)YesDecoder onlyNoNo
HuggingFace nativeYesYesGitHub onlyLimited

CLIPSeg is the only architecture that gives direct text-to-mask conditioning without bounding box intermediates, fine-tunes reliably on small datasets, and runs on consumer hardware with mature HuggingFace support.

</details>

Training Configuration

ParameterValue
Base model`CIDAS/clipseg-rd64-refined`
Trainable1,127,009 params (decoder only)
Frozen149,620,737 params (CLIP backbone)
LossBCEDiceLoss — 0.5 BCE + 0.5 Dice
OptimizerAdamW (lr=1e-4, wd=1e-4) + CosineAnnealingLR
Early stoppingpatience 7 on val mIoU
DeviceApple M4 (MPS backend)
Wall time97.2 min (18 epochs, best at epoch 11)

<details> <summary><b>Why BCEDiceLoss instead of standard BCE?</b></summary>

<br>

Standard BCE alone fails on thin structures like cracks — the severe foreground/background imbalance means BCE happily predicts "all background" at low loss. Dice loss directly optimizes overlap, forcing the model to find crack pixels. The 50/50 blend gives gradient stability (BCE) and overlap-awareness (Dice).

</details>

Training Pipeline

[image]

Training converged at epoch 11 (val mIoU 0.1605). The remaining 7 epochs showed no improvement before early stopping triggered at epoch 18.

All hyperparameters: `configs/train_config.yaml`


2. Data Preparation

Sources

Two datasets from Roboflow Universe, downloaded manually in COCO format:

DatasetSourceImagesRaw AnnotationMask Strategy
Tapingdrywall-join-detect1,186Bounding boxes onlyFilled rectangles
Crackscracks-3ii365,369COCO polygonsPixel-accurate binary masks via pycocotools
Note: The cracks dataset had 0 generated Roboflow versions — the owner never created an exportable version, making API download impossible. The raw export was downloaded directly from the website.

Mask Rendering

  • Cracks: COCO polygon annotations rendered to pixel-accurate binary masks using pycocotools.mask. Some annotations had empty segmentation fields (edge case) — handled with try/except fallback to bounding box rendering.
  • Taping: Only bounding box annotations available. Filled rectangles used as mask approximations. This is a known limitation — the rectangles include substantial background, which affects training signal quality.

Prompt Augmentation

5 synonyms per class, randomly sampled each training iteration. This forces the decoder to learn semantic meaning from the text encoder rather than memorize exact strings:

ClassPrompts
Cracks"segment crack" · "segment wall crack" · "segment surface crack" · "segment drywall crack" · "segment fracture"
Taping"segment taping area" · "segment joint tape" · "segment drywall seam" · "segment drywall joint" · "segment tape line"

Pipeline

[image]

Splits

Stratified by class (taping vs cracks), seed 42:

TrainValidationTest
4,588 (70%)982 (15%)985 (15%)

Preprocessing code: `src/data/preprocess.py` · Dataset class: `src/data/dataset.py`


3. Results

Best Predictions

The model's strongest predictions reach IoU 0.78 on both cracks and taping:

[image]

Test-Set Metrics (985 samples)

ClassmIoUDiceSamples
Taping0.19170.2780179
Cracks0.16390.2434806
Overall0.16890.2497985

Taping outperforms cracks because filled-rectangle masks provide a stronger supervision signal (larger contiguous regions) compared to thin crack annotations where minor spatial offsets cause disproportionate IoU drops.

Inference

MetricValue
Avg inference time58.7 ms / image
Model size575.1 MB
Output formatPNG, single-channel {0, 255}, resized to original dimensions
Threshold0.5 (sigmoid → binary)

4. Failure Cases & Potential Solutions

Worst Predictions

The model's worst predictions (IoU near zero) reveal systematic failure patterns:

[image]

What's going wrong in these examples:

  • Cracks (rows 1–3): The model activates over broad wall regions instead of tracing the thin crack lines. Fine cracks disappear at 352x352 resolution, and the frozen CLIP backbone has no features for hairline construction defects. The predictions show the model "knows something is there" but can't localize it precisely.
  • Taping (rows 4–6): The model predicts large rectangular blobs that don't match the actual joint locations. This directly traces back to the filled-rectangle training masks — the model learned to predict rectangles because that's what it was supervised on.

Root Causes

#FactorImpact
1Coarse taping annotationsSource dataset has bounding boxes, not pixel masks. Filled rectangles include background → model over-predicts.
2Thin crack IoU sensitivityA 1px crack shifted 2px = near-zero IoU despite visual similarity. Dominates aggregate.
3352x352 resolution ceilingCLIPSeg's fixed input size discards fine detail from high-res construction photos.
4Frozen backbone domain gapCLIP was trained on internet images, not construction imagery. Cannot adapt feature extraction.
5Small decoder (1.13M params)Limited capacity to learn construction-specific visual patterns.

Proposed Solutions

LimitationSolutionExpected Impact
Coarse taping masksUse SAM/SAM2 to generate pixel-accurate masks from bounding boxes before trainingHigh — directly fixes the supervision signal
Frozen backboneUnfreeze last 2–3 ViT blocks with 10x lower learning rate for domain adaptationHigh — lets the model learn construction-specific features
352x352 resolutionSwitch to SAM2 with text-prompt conditioning or a higher-res architectureHigh — preserves fine crack detail
Small decoderAdd decoder blocks or increase hidden dimension (monitor overfitting)Medium — more capacity, but risk of overfitting on small data
Thin-crack metric sensitivityUse boundary IoU or distance-tolerant evaluation instead of standard IoULow — doesn't improve the model, but gives fairer measurement

Repo Structure

[image]

<details> <summary><b>File-by-file listing</b></summary>

<br>

PathPurpose
`configs/train_config.yaml`All hyperparameters in one file
`src/data/preprocess.py`Annotation inspection, mask rendering, stratified splits
`src/data/dataset.py`PyTorch Dataset + CLIPSegProcessor collation
`src/model/clipseg_wrapper.py`Model loading + backbone freezing
`src/model/losses.py`BCEDiceLoss implementation
`src/train.py`Training loop with early stopping + logging
`src/evaluate.py`Test metrics, mask generation, visual comparisons
`src/predict.py`Single-image CLI inference
`src/best_predictions.py`Per-sample IoU scoring, best/worst prediction figures
`reports/report.typ`Typst source → `report.pdf`

</details>


Quick Start

Prerequisites: Python 3.11+, uv, Homebrew (macOS)

bash
brew install graphviz plantuml typst d2
uv sync

1. Get the data

Download both datasets from Roboflow Universe in COCO format → place under data/raw/:

data/raw/
├── taping/          # drywall-join-detect (COCO export)
│   ├── train/
│   └── valid/
└── cracks/          # cracks-3ii36 (COCO export)
    └── train/

2. Preprocess

bash
uv run python -m src.data.preprocess

3. Train

bash
uv run python -m src.train

4. Evaluate

bash
uv run python -m src.evaluate

5. Predict on a single image

bash
uv run python -m src.predict path/to/image.jpg "segment crack"

6. Build the report

bash
d2 reports/diagrams/pipeline.d2 reports/diagrams/pipeline.png
plantuml -tpng reports/diagrams/training.puml
uv run python reports/diagrams/architecture.py
typst compile reports/report.typ reports/report.pdf

Reproducibility

  • All random state seeded with 42 (data splits, PyTorch, NumPy).
  • Hyperparameters: `configs/train_config.yaml`.
  • Per-epoch training logs: `outputs/logs/`.

<p align="center"> <a href="https://huggingface.co/youngPhilosopher/drywall-qa-clipseg/blob/main/reports/report.pdf"><b>Read the full report (PDF)</b></a> </p>