Spaces:
Sleeping
Sleeping
Commit ·
7b4e05b
1
Parent(s): f2a7558
Sync src/ with attention decoder support
Browse files- src/evaluation/__pycache__/evaluate.cpython-312.pyc +0 -0
- src/evaluation/evaluate.py +23 -32
- src/features/__pycache__/extractor.cpython-312.pyc +0 -0
- src/features/extractor.py +39 -4
- src/inference/__pycache__/predict.cpython-312.pyc +0 -0
- src/inference/predict.py +14 -6
- src/models/__pycache__/base.cpython-312.pyc +0 -0
- src/models/__pycache__/caption_model.cpython-312.pyc +0 -0
- src/models/__pycache__/decoder.cpython-312.pyc +0 -0
- src/models/__pycache__/encoder.cpython-312.pyc +0 -0
- src/models/__pycache__/registry.cpython-312.pyc +0 -0
- src/models/base.py +19 -1
- src/models/caption_model.py +17 -0
- src/models/decoder.py +258 -7
- src/models/encoder.py +55 -2
- src/models/registry.py +5 -3
- src/training/__pycache__/trainer.cpython-312.pyc +0 -0
- src/training/trainer.py +9 -2
- src/utils/__pycache__/config.cpython-312.pyc +0 -0
- src/utils/config.py +2 -0
src/evaluation/__pycache__/evaluate.cpython-312.pyc
CHANGED
|
Binary files a/src/evaluation/__pycache__/evaluate.cpython-312.pyc and b/src/evaluation/__pycache__/evaluate.cpython-312.pyc differ
|
|
|
src/evaluation/evaluate.py
CHANGED
|
@@ -1,87 +1,78 @@
|
|
| 1 |
"""Evaluate a trained model on the test set: BLEU/ROUGE/METEOR + qualitative examples.
|
| 2 |
-
|
| 3 |
Usage:
|
| 4 |
-
python -m src.evaluation.evaluate --config configs/base_resnet_lstm.yaml
|
| 5 |
-
|
| 6 |
Reads:
|
| 7 |
<paths.processed_dir>/test.csv
|
| 8 |
<paths.models_dir>/<run_name>/best_model.pt
|
| 9 |
<paths.processed_dir>/vocab.json
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
<paths.models_dir>/<run_name>/
|
| 13 |
-
<paths.models_dir>/<run_name>/eval_qualitative.md
|
| 14 |
"""
|
| 15 |
from __future__ import annotations
|
| 16 |
-
|
| 17 |
import argparse
|
| 18 |
import json
|
| 19 |
from pathlib import Path
|
| 20 |
-
|
| 21 |
import pandas as pd
|
| 22 |
from tqdm import tqdm
|
| 23 |
-
|
| 24 |
from src.evaluation.metrics import compute_all_metrics
|
| 25 |
from src.inference.predict import Predictor
|
| 26 |
from src.utils.config import load_config
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
processed_dir = Path(config["paths"]["processed_dir"])
|
| 31 |
run_dir = Path(config["paths"]["models_dir"]) / config["run_name"]
|
| 32 |
-
|
| 33 |
predictor = Predictor(
|
| 34 |
checkpoint_path=run_dir / "best_model.pt",
|
| 35 |
vocab_path=processed_dir / "vocab.json",
|
| 36 |
device=device,
|
| 37 |
)
|
| 38 |
-
|
|
|
|
| 39 |
test_df = pd.read_csv(processed_dir / "test.csv")
|
| 40 |
grouped = test_df.groupby("image")["caption"].apply(list).reset_index()
|
| 41 |
-
print(f"Evaluating on {len(grouped)} unique test images ({
|
| 42 |
-
|
| 43 |
images_dir = Path(config["paths"]["raw_images_dir"])
|
| 44 |
hypotheses: list[str] = []
|
| 45 |
references: list[list[str]] = []
|
| 46 |
per_image_results = []
|
| 47 |
-
|
| 48 |
for _, row in tqdm(grouped.iterrows(), total=len(grouped), desc="Generating captions"):
|
| 49 |
image_filename = row["image"]
|
| 50 |
refs = row["caption"]
|
| 51 |
-
|
| 52 |
caption = predictor.predict(images_dir / image_filename)
|
| 53 |
hypotheses.append(caption)
|
| 54 |
references.append(refs)
|
| 55 |
per_image_results.append(
|
| 56 |
{"image": image_filename, "generated": caption, "references": refs}
|
| 57 |
)
|
| 58 |
-
|
| 59 |
metrics = compute_all_metrics(hypotheses, references)
|
| 60 |
-
|
| 61 |
-
print("\n=== Evaluation Metrics ===")
|
| 62 |
for name, value in metrics.items():
|
| 63 |
print(f"{name}: {value:.4f}")
|
| 64 |
-
|
| 65 |
-
metrics_path = run_dir / "eval_metrics.json"
|
| 66 |
with open(metrics_path, "w") as f:
|
| 67 |
-
json.dump(metrics, f, indent=2)
|
| 68 |
print(f"\nSaved metrics to {metrics_path}")
|
| 69 |
-
|
| 70 |
-
# qualitative report: first N examples, image -> generated -> references
|
| 71 |
-
qual_path = run_dir / "eval_qualitative.md"
|
| 72 |
with open(qual_path, "w") as f:
|
| 73 |
-
f.write(f"# Qualitative Evaluation -- {config['run_name']}\n\n")
|
| 74 |
f.write("| Image | Generated | References |\n|---|---|---|\n")
|
| 75 |
for item in per_image_results[:n_qualitative]:
|
| 76 |
refs_joined = "<br>".join(item["references"])
|
| 77 |
f.write(f"| {item['image']} | {item['generated']} | {refs_joined} |\n")
|
| 78 |
print(f"Saved qualitative examples to {qual_path}")
|
| 79 |
-
|
| 80 |
-
|
| 81 |
if __name__ == "__main__":
|
| 82 |
parser = argparse.ArgumentParser()
|
| 83 |
parser.add_argument("--config", required=True)
|
| 84 |
parser.add_argument("--device", default="cuda")
|
|
|
|
|
|
|
| 85 |
args = parser.parse_args()
|
| 86 |
config = load_config(args.config)
|
| 87 |
-
evaluate(config, device=args.device)
|
|
|
|
| 1 |
"""Evaluate a trained model on the test set: BLEU/ROUGE/METEOR + qualitative examples.
|
|
|
|
| 2 |
Usage:
|
| 3 |
+
python -m src.evaluation.evaluate --config configs/base_resnet_lstm.yaml --decoding greedy
|
| 4 |
+
python -m src.evaluation.evaluate --config configs/base_resnet_lstm.yaml --decoding beam --beam-width 3
|
| 5 |
Reads:
|
| 6 |
<paths.processed_dir>/test.csv
|
| 7 |
<paths.models_dir>/<run_name>/best_model.pt
|
| 8 |
<paths.processed_dir>/vocab.json
|
| 9 |
+
Writes (filenames include the decoding mode so greedy/beam results don't overwrite each other):
|
| 10 |
+
<paths.models_dir>/<run_name>/eval_metrics_<decoding>.json
|
| 11 |
+
<paths.models_dir>/<run_name>/eval_qualitative_<decoding>.md
|
|
|
|
| 12 |
"""
|
| 13 |
from __future__ import annotations
|
|
|
|
| 14 |
import argparse
|
| 15 |
import json
|
| 16 |
from pathlib import Path
|
|
|
|
| 17 |
import pandas as pd
|
| 18 |
from tqdm import tqdm
|
|
|
|
| 19 |
from src.evaluation.metrics import compute_all_metrics
|
| 20 |
from src.inference.predict import Predictor
|
| 21 |
from src.utils.config import load_config
|
| 22 |
+
def evaluate(
|
| 23 |
+
config: dict,
|
| 24 |
+
device: str = "cuda",
|
| 25 |
+
decoding: str = "greedy",
|
| 26 |
+
beam_width: int = 3,
|
| 27 |
+
n_qualitative: int = 12,
|
| 28 |
+
) -> None:
|
| 29 |
processed_dir = Path(config["paths"]["processed_dir"])
|
| 30 |
run_dir = Path(config["paths"]["models_dir"]) / config["run_name"]
|
|
|
|
| 31 |
predictor = Predictor(
|
| 32 |
checkpoint_path=run_dir / "best_model.pt",
|
| 33 |
vocab_path=processed_dir / "vocab.json",
|
| 34 |
device=device,
|
| 35 |
)
|
| 36 |
+
predictor.decoding = decoding
|
| 37 |
+
predictor.beam_width = beam_width
|
| 38 |
test_df = pd.read_csv(processed_dir / "test.csv")
|
| 39 |
grouped = test_df.groupby("image")["caption"].apply(list).reset_index()
|
| 40 |
+
print(f"Evaluating on {len(grouped)} unique test images (decoding={decoding}, beam_width={beam_width})")
|
|
|
|
| 41 |
images_dir = Path(config["paths"]["raw_images_dir"])
|
| 42 |
hypotheses: list[str] = []
|
| 43 |
references: list[list[str]] = []
|
| 44 |
per_image_results = []
|
|
|
|
| 45 |
for _, row in tqdm(grouped.iterrows(), total=len(grouped), desc="Generating captions"):
|
| 46 |
image_filename = row["image"]
|
| 47 |
refs = row["caption"]
|
|
|
|
| 48 |
caption = predictor.predict(images_dir / image_filename)
|
| 49 |
hypotheses.append(caption)
|
| 50 |
references.append(refs)
|
| 51 |
per_image_results.append(
|
| 52 |
{"image": image_filename, "generated": caption, "references": refs}
|
| 53 |
)
|
|
|
|
| 54 |
metrics = compute_all_metrics(hypotheses, references)
|
| 55 |
+
print(f"\n=== Evaluation Metrics (decoding={decoding}) ===")
|
|
|
|
| 56 |
for name, value in metrics.items():
|
| 57 |
print(f"{name}: {value:.4f}")
|
| 58 |
+
metrics_path = run_dir / f"eval_metrics_{decoding}.json"
|
|
|
|
| 59 |
with open(metrics_path, "w") as f:
|
| 60 |
+
json.dump({"decoding": decoding, "beam_width": beam_width, **metrics}, f, indent=2)
|
| 61 |
print(f"\nSaved metrics to {metrics_path}")
|
| 62 |
+
qual_path = run_dir / f"eval_qualitative_{decoding}.md"
|
|
|
|
|
|
|
| 63 |
with open(qual_path, "w") as f:
|
| 64 |
+
f.write(f"# Qualitative Evaluation -- {config['run_name']} ({decoding} decoding)\n\n")
|
| 65 |
f.write("| Image | Generated | References |\n|---|---|---|\n")
|
| 66 |
for item in per_image_results[:n_qualitative]:
|
| 67 |
refs_joined = "<br>".join(item["references"])
|
| 68 |
f.write(f"| {item['image']} | {item['generated']} | {refs_joined} |\n")
|
| 69 |
print(f"Saved qualitative examples to {qual_path}")
|
|
|
|
|
|
|
| 70 |
if __name__ == "__main__":
|
| 71 |
parser = argparse.ArgumentParser()
|
| 72 |
parser.add_argument("--config", required=True)
|
| 73 |
parser.add_argument("--device", default="cuda")
|
| 74 |
+
parser.add_argument("--decoding", default="greedy", choices=["greedy", "beam"])
|
| 75 |
+
parser.add_argument("--beam-width", type=int, default=3)
|
| 76 |
args = parser.parse_args()
|
| 77 |
config = load_config(args.config)
|
| 78 |
+
evaluate(config, device=args.device, decoding=args.decoding, beam_width=args.beam_width)
|
src/features/__pycache__/extractor.cpython-312.pyc
CHANGED
|
Binary files a/src/features/__pycache__/extractor.cpython-312.pyc and b/src/features/__pycache__/extractor.cpython-312.pyc differ
|
|
|
src/features/extractor.py
CHANGED
|
@@ -13,13 +13,16 @@ import torchvision.models as models
|
|
| 13 |
|
| 14 |
|
| 15 |
class ResNet50FeatureExtractor:
|
| 16 |
-
"""Wraps a frozen, pretrained ResNet50 with its classification head removed.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
def __init__(self, device: str = "cpu"):
|
| 19 |
self.device = device
|
| 20 |
weights = models.ResNet50_Weights.IMAGENET1K_V2
|
| 21 |
resnet = models.resnet50(weights=weights)
|
| 22 |
-
# drop the final fc layer -> output is the (2048,) pooled feature
|
| 23 |
self.model = nn.Sequential(*list(resnet.children())[:-1]).to(device)
|
| 24 |
self.model.eval()
|
| 25 |
for param in self.model.parameters():
|
|
@@ -29,5 +32,37 @@ class ResNet50FeatureExtractor:
|
|
| 29 |
def extract(self, image_tensor: torch.Tensor) -> torch.Tensor:
|
| 30 |
"""image_tensor: (batch, 3, 224, 224) -> returns (batch, 2048)."""
|
| 31 |
image_tensor = image_tensor.to(self.device)
|
| 32 |
-
features = self.model(image_tensor)
|
| 33 |
-
return features.squeeze(-1).squeeze(-1).cpu()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
class ResNet50FeatureExtractor:
|
| 16 |
+
"""Wraps a frozen, pretrained ResNet50 with its classification head removed.
|
| 17 |
+
|
| 18 |
+
Produces a single pooled (2048,) feature vector per image -- used by the
|
| 19 |
+
baseline/regularized DecoderLSTM, which relies on one global image vector.
|
| 20 |
+
"""
|
| 21 |
|
| 22 |
def __init__(self, device: str = "cpu"):
|
| 23 |
self.device = device
|
| 24 |
weights = models.ResNet50_Weights.IMAGENET1K_V2
|
| 25 |
resnet = models.resnet50(weights=weights)
|
|
|
|
| 26 |
self.model = nn.Sequential(*list(resnet.children())[:-1]).to(device)
|
| 27 |
self.model.eval()
|
| 28 |
for param in self.model.parameters():
|
|
|
|
| 32 |
def extract(self, image_tensor: torch.Tensor) -> torch.Tensor:
|
| 33 |
"""image_tensor: (batch, 3, 224, 224) -> returns (batch, 2048)."""
|
| 34 |
image_tensor = image_tensor.to(self.device)
|
| 35 |
+
features = self.model(image_tensor)
|
| 36 |
+
return features.squeeze(-1).squeeze(-1).cpu()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ResNet50SpatialFeatureExtractor:
|
| 40 |
+
"""Wraps a frozen, pretrained ResNet50 with BOTH the classification head
|
| 41 |
+
AND the final average-pooling layer removed.
|
| 42 |
+
|
| 43 |
+
Produces a spatial GRID of features (7x7 regions, 2048-d each) instead of
|
| 44 |
+
one pooled global vector -- required for attention-based decoders, which
|
| 45 |
+
need to attend to different image regions at each generation step.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self, device: str = "cpu"):
|
| 49 |
+
self.device = device
|
| 50 |
+
weights = models.ResNet50_Weights.IMAGENET1K_V2
|
| 51 |
+
resnet = models.resnet50(weights=weights)
|
| 52 |
+
self.model = nn.Sequential(*list(resnet.children())[:-2]).to(device)
|
| 53 |
+
self.model.eval()
|
| 54 |
+
for param in self.model.parameters():
|
| 55 |
+
param.requires_grad = False
|
| 56 |
+
|
| 57 |
+
@torch.no_grad()
|
| 58 |
+
def extract(self, image_tensor: torch.Tensor) -> torch.Tensor:
|
| 59 |
+
"""image_tensor: (batch, 3, 224, 224) -> returns (batch, 49, 2048).
|
| 60 |
+
|
| 61 |
+
49 = 7x7 spatial grid positions, each a 2048-d feature vector.
|
| 62 |
+
"""
|
| 63 |
+
image_tensor = image_tensor.to(self.device)
|
| 64 |
+
features = self.model(image_tensor)
|
| 65 |
+
batch, channels, h, w = features.shape
|
| 66 |
+
features = features.view(batch, channels, h * w)
|
| 67 |
+
features = features.permute(0, 2, 1)
|
| 68 |
+
return features.cpu()
|
src/inference/__pycache__/predict.cpython-312.pyc
CHANGED
|
Binary files a/src/inference/__pycache__/predict.cpython-312.pyc and b/src/inference/__pycache__/predict.cpython-312.pyc differ
|
|
|
src/inference/predict.py
CHANGED
|
@@ -15,14 +15,14 @@ from PIL import Image
|
|
| 15 |
|
| 16 |
from src.data.preprocessing import get_image_transform
|
| 17 |
from src.data.vocabulary import Vocabulary
|
| 18 |
-
from src.features.extractor import ResNet50FeatureExtractor
|
| 19 |
from src.models.caption_model import CaptionModel
|
| 20 |
|
| 21 |
FEATURE_EXTRACTOR_REGISTRY = {
|
| 22 |
"resnet50": ResNet50FeatureExtractor,
|
|
|
|
| 23 |
}
|
| 24 |
|
| 25 |
-
|
| 26 |
class Predictor:
|
| 27 |
def __init__(self, checkpoint_path: str | Path, vocab_path: str | Path, device: str = "cpu"):
|
| 28 |
self.device = device
|
|
@@ -41,13 +41,19 @@ class Predictor:
|
|
| 41 |
self.feature_extractor = FEATURE_EXTRACTOR_REGISTRY[encoder_type](device=device)
|
| 42 |
self.transform = get_image_transform(train=False)
|
| 43 |
self.max_len = self.config["vocab"]["max_len"]
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
if isinstance(image, (str, Path)):
|
| 47 |
image = Image.open(image).convert("RGB")
|
| 48 |
|
| 49 |
-
image_tensor = self.transform(image).unsqueeze(0)
|
| 50 |
-
image_feature = self.feature_extractor.extract(image_tensor)
|
| 51 |
image_feature = image_feature.to(self.device)
|
| 52 |
|
| 53 |
generated_ids = self.model.generate(
|
|
@@ -55,6 +61,8 @@ class Predictor:
|
|
| 55 |
start_idx=self.vocab.start_idx,
|
| 56 |
end_idx=self.vocab.end_idx,
|
| 57 |
max_len=self.max_len,
|
|
|
|
|
|
|
| 58 |
)
|
| 59 |
words = self.vocab.decode(generated_ids, strip_special=True)
|
| 60 |
return " ".join(words)
|
|
|
|
| 15 |
|
| 16 |
from src.data.preprocessing import get_image_transform
|
| 17 |
from src.data.vocabulary import Vocabulary
|
| 18 |
+
from src.features.extractor import ResNet50FeatureExtractor, ResNet50SpatialFeatureExtractor
|
| 19 |
from src.models.caption_model import CaptionModel
|
| 20 |
|
| 21 |
FEATURE_EXTRACTOR_REGISTRY = {
|
| 22 |
"resnet50": ResNet50FeatureExtractor,
|
| 23 |
+
"resnet50_spatial": ResNet50SpatialFeatureExtractor,
|
| 24 |
}
|
| 25 |
|
|
|
|
| 26 |
class Predictor:
|
| 27 |
def __init__(self, checkpoint_path: str | Path, vocab_path: str | Path, device: str = "cpu"):
|
| 28 |
self.device = device
|
|
|
|
| 41 |
self.feature_extractor = FEATURE_EXTRACTOR_REGISTRY[encoder_type](device=device)
|
| 42 |
self.transform = get_image_transform(train=False)
|
| 43 |
self.max_len = self.config["vocab"]["max_len"]
|
| 44 |
+
self.decoding = self.config.get("inference", {}).get("decoding", "greedy")
|
| 45 |
+
self.beam_width = self.config.get("inference", {}).get("beam_width", 3)
|
| 46 |
+
|
| 47 |
+
def predict(self, image: str | Path | Image.Image, decoding: str | None = None) -> str:
|
| 48 |
+
"""Generate a caption for a single image (path or already-loaded PIL Image).
|
| 49 |
+
|
| 50 |
+
`decoding` overrides the config's default ("greedy" or "beam") for this call.
|
| 51 |
+
"""
|
| 52 |
if isinstance(image, (str, Path)):
|
| 53 |
image = Image.open(image).convert("RGB")
|
| 54 |
|
| 55 |
+
image_tensor = self.transform(image).unsqueeze(0)
|
| 56 |
+
image_feature = self.feature_extractor.extract(image_tensor)
|
| 57 |
image_feature = image_feature.to(self.device)
|
| 58 |
|
| 59 |
generated_ids = self.model.generate(
|
|
|
|
| 61 |
start_idx=self.vocab.start_idx,
|
| 62 |
end_idx=self.vocab.end_idx,
|
| 63 |
max_len=self.max_len,
|
| 64 |
+
decoding=decoding or self.decoding,
|
| 65 |
+
beam_width=self.beam_width,
|
| 66 |
)
|
| 67 |
words = self.vocab.decode(generated_ids, strip_special=True)
|
| 68 |
return " ".join(words)
|
src/models/__pycache__/base.cpython-312.pyc
CHANGED
|
Binary files a/src/models/__pycache__/base.cpython-312.pyc and b/src/models/__pycache__/base.cpython-312.pyc differ
|
|
|
src/models/__pycache__/caption_model.cpython-312.pyc
CHANGED
|
Binary files a/src/models/__pycache__/caption_model.cpython-312.pyc and b/src/models/__pycache__/caption_model.cpython-312.pyc differ
|
|
|
src/models/__pycache__/decoder.cpython-312.pyc
CHANGED
|
Binary files a/src/models/__pycache__/decoder.cpython-312.pyc and b/src/models/__pycache__/decoder.cpython-312.pyc differ
|
|
|
src/models/__pycache__/encoder.cpython-312.pyc
CHANGED
|
Binary files a/src/models/__pycache__/encoder.cpython-312.pyc and b/src/models/__pycache__/encoder.cpython-312.pyc differ
|
|
|
src/models/__pycache__/registry.cpython-312.pyc
CHANGED
|
Binary files a/src/models/__pycache__/registry.cpython-312.pyc and b/src/models/__pycache__/registry.cpython-312.pyc differ
|
|
|
src/models/base.py
CHANGED
|
@@ -33,6 +33,7 @@ class BaseDecoder(nn.Module, ABC):
|
|
| 33 |
"""
|
| 34 |
raise NotImplementedError
|
| 35 |
|
|
|
|
| 36 |
@abstractmethod
|
| 37 |
def generate(
|
| 38 |
self,
|
|
@@ -45,4 +46,21 @@ class BaseDecoder(nn.Module, ABC):
|
|
| 45 |
|
| 46 |
Returns a list of generated token indices, excluding <start> and <end>.
|
| 47 |
"""
|
| 48 |
-
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
"""
|
| 34 |
raise NotImplementedError
|
| 35 |
|
| 36 |
+
#for greedy search
|
| 37 |
@abstractmethod
|
| 38 |
def generate(
|
| 39 |
self,
|
|
|
|
| 46 |
|
| 47 |
Returns a list of generated token indices, excluding <start> and <end>.
|
| 48 |
"""
|
| 49 |
+
raise NotImplementedError
|
| 50 |
+
|
| 51 |
+
#for beam search
|
| 52 |
+
def generate_beam(
|
| 53 |
+
self,
|
| 54 |
+
image_embed: torch.Tensor,
|
| 55 |
+
start_idx: int,
|
| 56 |
+
end_idx: int,
|
| 57 |
+
max_len: int,
|
| 58 |
+
beam_width: int = 3,
|
| 59 |
+
) -> list[int]:
|
| 60 |
+
"""Beam search generation for a SINGLE image (batch=1).
|
| 61 |
+
|
| 62 |
+
Optional: not marked @abstractmethod so existing decoders that only
|
| 63 |
+
implement greedy generate() remain valid; override in subclasses
|
| 64 |
+
that support beam search (see DecoderLSTM).
|
| 65 |
+
"""
|
| 66 |
+
raise NotImplementedError("This decoder does not implement beam search.")
|
src/models/caption_model.py
CHANGED
|
@@ -38,4 +38,21 @@ class CaptionModel(nn.Module):
|
|
| 38 |
) -> list[int]:
|
| 39 |
self.eval()
|
| 40 |
image_embed = self.encoder(image_features)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
return self.decoder.generate(image_embed, start_idx, end_idx, max_len)
|
|
|
|
| 38 |
) -> list[int]:
|
| 39 |
self.eval()
|
| 40 |
image_embed = self.encoder(image_features)
|
| 41 |
+
return self.decoder.generate(image_embed, start_idx, end_idx, max_len)
|
| 42 |
+
|
| 43 |
+
#for beam search
|
| 44 |
+
@torch.no_grad()
|
| 45 |
+
def generate(
|
| 46 |
+
self,
|
| 47 |
+
image_features: torch.Tensor,
|
| 48 |
+
start_idx: int,
|
| 49 |
+
end_idx: int,
|
| 50 |
+
max_len: int,
|
| 51 |
+
decoding: str = "greedy",
|
| 52 |
+
beam_width: int = 3,
|
| 53 |
+
) -> list[int]:
|
| 54 |
+
self.eval()
|
| 55 |
+
image_embed = self.encoder(image_features)
|
| 56 |
+
if decoding == "beam":
|
| 57 |
+
return self.decoder.generate_beam(image_embed, start_idx, end_idx, max_len, beam_width)
|
| 58 |
return self.decoder.generate(image_embed, start_idx, end_idx, max_len)
|
src/models/decoder.py
CHANGED
|
@@ -28,17 +28,27 @@ class DecoderLSTM(BaseDecoder):
|
|
| 28 |
batch_first=True,
|
| 29 |
dropout=dropout if num_layers > 1 else 0.0,
|
| 30 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
self.fc = nn.Linear(hidden_dim, vocab_size)
|
| 32 |
|
| 33 |
def forward(self, image_embed: torch.Tensor, input_seq: torch.Tensor) -> torch.Tensor:
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
lstm_input = torch.cat([image_step, word_embeds], dim=1)
|
| 38 |
-
lstm_out, _ = self.lstm(lstm_input)
|
| 39 |
-
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
@torch.no_grad()
|
| 44 |
def generate(
|
|
@@ -69,4 +79,245 @@ class DecoderLSTM(BaseDecoder):
|
|
| 69 |
generated.append(predicted_idx)
|
| 70 |
current_token = torch.tensor([[predicted_idx]], device=device)
|
| 71 |
|
| 72 |
-
return generated
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
batch_first=True,
|
| 29 |
dropout=dropout if num_layers > 1 else 0.0,
|
| 30 |
)
|
| 31 |
+
# NOTE: nn.LSTM's own `dropout` arg only applies BETWEEN stacked layers,
|
| 32 |
+
# so it has no effect with num_layers=1 (our baseline). This separate
|
| 33 |
+
# output_dropout applies to the LSTM's output before the final
|
| 34 |
+
# projection, giving a real regularization effect even for a
|
| 35 |
+
# single-layer LSTM.
|
| 36 |
+
self.output_dropout = nn.Dropout(dropout)
|
| 37 |
self.fc = nn.Linear(hidden_dim, vocab_size)
|
| 38 |
|
| 39 |
def forward(self, image_embed: torch.Tensor, input_seq: torch.Tensor) -> torch.Tensor:
|
| 40 |
+
# image_embed: (batch, embed_dim)
|
| 41 |
+
# input_seq: (batch, seq_len) token indices (teacher-forced)
|
| 42 |
+
word_embeds = self.embedding(input_seq) # (batch, seq_len, embed_dim)
|
| 43 |
+
image_step = image_embed.unsqueeze(1) # (batch, 1, embed_dim)
|
| 44 |
|
| 45 |
+
lstm_input = torch.cat([image_step, word_embeds], dim=1) # (batch, seq_len+1, embed_dim)
|
| 46 |
+
lstm_out, _ = self.lstm(lstm_input) # (batch, seq_len+1, hidden_dim)
|
| 47 |
+
lstm_out = self.output_dropout(lstm_out)
|
| 48 |
+
logits = self.fc(lstm_out) # (batch, seq_len+1, vocab_size)
|
| 49 |
|
| 50 |
+
# drop the output at the image step (index 0) -- it has no word target
|
| 51 |
+
return logits[:, 1:, :] # (batch, seq_len, vocab_size)
|
| 52 |
|
| 53 |
@torch.no_grad()
|
| 54 |
def generate(
|
|
|
|
| 79 |
generated.append(predicted_idx)
|
| 80 |
current_token = torch.tensor([[predicted_idx]], device=device)
|
| 81 |
|
| 82 |
+
return generated
|
| 83 |
+
|
| 84 |
+
@torch.no_grad()
|
| 85 |
+
def generate_beam(
|
| 86 |
+
self,
|
| 87 |
+
image_embed: torch.Tensor,
|
| 88 |
+
start_idx: int,
|
| 89 |
+
end_idx: int,
|
| 90 |
+
max_len: int,
|
| 91 |
+
beam_width: int = 3,
|
| 92 |
+
) -> list[int]:
|
| 93 |
+
"""Beam search decoding for a SINGLE image (batch=1).
|
| 94 |
+
|
| 95 |
+
Keeps the top `beam_width` candidate sequences at each step instead of
|
| 96 |
+
committing to a single best word (as generate()/greedy does), which
|
| 97 |
+
can recover from a locally-suboptimal early word choice. No retraining
|
| 98 |
+
required -- this only changes inference-time decoding.
|
| 99 |
+
"""
|
| 100 |
+
assert image_embed.size(0) == 1, "generate_beam() supports batch_size=1"
|
| 101 |
+
device = image_embed.device
|
| 102 |
+
|
| 103 |
+
image_step = image_embed.unsqueeze(1) # (1, 1, embed_dim)
|
| 104 |
+
_, init_hidden = self.lstm(image_step)
|
| 105 |
+
|
| 106 |
+
# each beam: (token_ids, cumulative_log_prob, hidden_state, finished)
|
| 107 |
+
beams = [([start_idx], 0.0, init_hidden, False)]
|
| 108 |
+
|
| 109 |
+
for _ in range(max_len):
|
| 110 |
+
all_candidates = []
|
| 111 |
+
for tokens, log_prob, hidden, finished in beams:
|
| 112 |
+
if finished:
|
| 113 |
+
all_candidates.append((tokens, log_prob, hidden, finished))
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
last_token = torch.tensor([[tokens[-1]]], device=device)
|
| 117 |
+
word_embed = self.embedding(last_token)
|
| 118 |
+
lstm_out, new_hidden = self.lstm(word_embed, hidden)
|
| 119 |
+
logits = self.fc(lstm_out.squeeze(1))
|
| 120 |
+
log_probs = torch.log_softmax(logits, dim=-1).squeeze(0)
|
| 121 |
+
|
| 122 |
+
top_log_probs, top_indices = log_probs.topk(beam_width)
|
| 123 |
+
for lp, idx in zip(top_log_probs.tolist(), top_indices.tolist()):
|
| 124 |
+
new_tokens = tokens + [idx]
|
| 125 |
+
new_finished = idx == end_idx
|
| 126 |
+
all_candidates.append((new_tokens, log_prob + lp, new_hidden, new_finished))
|
| 127 |
+
|
| 128 |
+
all_candidates.sort(key=lambda c: c[1], reverse=True)
|
| 129 |
+
beams = all_candidates[:beam_width]
|
| 130 |
+
|
| 131 |
+
if all(finished for _, _, _, finished in beams):
|
| 132 |
+
break
|
| 133 |
+
|
| 134 |
+
best_tokens, _, _, _ = max(beams, key=lambda c: c[1])
|
| 135 |
+
result = best_tokens[1:]
|
| 136 |
+
if result and result[-1] == end_idx:
|
| 137 |
+
result = result[:-1]
|
| 138 |
+
return result
|
| 139 |
+
|
| 140 |
+
class BahdanauAttention(nn.Module):
|
| 141 |
+
"""Additive (Bahdanau-style) attention over spatial image regions.
|
| 142 |
+
|
| 143 |
+
At each decoder step, computes a weighted combination of the encoder's
|
| 144 |
+
spatial feature grid, where the weights depend on the current decoder
|
| 145 |
+
hidden state -- this is what lets the decoder "look at" different image
|
| 146 |
+
regions for different words, instead of relying on one static vector.
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
def __init__(self, embed_dim: int, hidden_dim: int, attention_dim: int):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.encoder_att = nn.Linear(embed_dim, attention_dim)
|
| 152 |
+
self.decoder_att = nn.Linear(hidden_dim, attention_dim)
|
| 153 |
+
self.full_att = nn.Linear(attention_dim, 1)
|
| 154 |
+
self.relu = nn.ReLU()
|
| 155 |
+
self.softmax = nn.Softmax(dim=1)
|
| 156 |
+
|
| 157 |
+
def forward(self, encoder_out: torch.Tensor, decoder_hidden: torch.Tensor):
|
| 158 |
+
att1 = self.encoder_att(encoder_out)
|
| 159 |
+
att2 = self.decoder_att(decoder_hidden).unsqueeze(1)
|
| 160 |
+
att = self.full_att(self.relu(att1 + att2)).squeeze(2)
|
| 161 |
+
alpha = self.softmax(att)
|
| 162 |
+
context = (encoder_out * alpha.unsqueeze(2)).sum(dim=1)
|
| 163 |
+
return context, alpha
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class DecoderAttentionLSTM(BaseDecoder):
|
| 167 |
+
"""LSTM decoder with Bahdanau-style attention over spatial image features.
|
| 168 |
+
|
| 169 |
+
Unlike DecoderLSTM (which injects one static image vector as the first
|
| 170 |
+
LSTM step), this decoder recomputes a fresh, weighted combination of
|
| 171 |
+
image regions at EVERY generation step, using an LSTMCell in an explicit
|
| 172 |
+
loop (required since each step's attention depends on that step's hidden
|
| 173 |
+
state -- unlike DecoderLSTM, the whole sequence can't be processed in one
|
| 174 |
+
nn.LSTM call).
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
vocab_size: int,
|
| 180 |
+
embed_dim: int = 256,
|
| 181 |
+
hidden_dim: int = 512,
|
| 182 |
+
attention_dim: int = 256,
|
| 183 |
+
dropout: float = 0.5,
|
| 184 |
+
**kwargs,
|
| 185 |
+
):
|
| 186 |
+
super().__init__()
|
| 187 |
+
self.embed_dim = embed_dim
|
| 188 |
+
self.hidden_dim = hidden_dim
|
| 189 |
+
|
| 190 |
+
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
|
| 191 |
+
self.attention = BahdanauAttention(embed_dim, hidden_dim, attention_dim)
|
| 192 |
+
self.lstm_cell = nn.LSTMCell(embed_dim + embed_dim, hidden_dim)
|
| 193 |
+
self.init_h = nn.Linear(embed_dim, hidden_dim)
|
| 194 |
+
self.init_c = nn.Linear(embed_dim, hidden_dim)
|
| 195 |
+
self.f_beta = nn.Linear(hidden_dim, embed_dim)
|
| 196 |
+
self.sigmoid = nn.Sigmoid()
|
| 197 |
+
self.dropout = nn.Dropout(dropout)
|
| 198 |
+
self.fc = nn.Linear(hidden_dim, vocab_size)
|
| 199 |
+
|
| 200 |
+
def _init_hidden_state(self, encoder_out: torch.Tensor):
|
| 201 |
+
mean_encoder_out = encoder_out.mean(dim=1)
|
| 202 |
+
h = self.init_h(mean_encoder_out)
|
| 203 |
+
c = self.init_c(mean_encoder_out)
|
| 204 |
+
return h, c
|
| 205 |
+
|
| 206 |
+
def forward(self, image_embed: torch.Tensor, input_seq: torch.Tensor) -> torch.Tensor:
|
| 207 |
+
batch_size = image_embed.size(0)
|
| 208 |
+
seq_len = input_seq.size(1)
|
| 209 |
+
vocab_size = self.fc.out_features
|
| 210 |
+
device = image_embed.device
|
| 211 |
+
|
| 212 |
+
embeddings = self.embedding(input_seq)
|
| 213 |
+
h, c = self._init_hidden_state(image_embed)
|
| 214 |
+
|
| 215 |
+
outputs = torch.zeros(batch_size, seq_len, vocab_size, device=device)
|
| 216 |
+
|
| 217 |
+
for t in range(seq_len):
|
| 218 |
+
context, _ = self.attention(image_embed, h)
|
| 219 |
+
gate = self.sigmoid(self.f_beta(h))
|
| 220 |
+
context = gate * context
|
| 221 |
+
|
| 222 |
+
lstm_input = torch.cat([embeddings[:, t, :], context], dim=1)
|
| 223 |
+
h, c = self.lstm_cell(lstm_input, (h, c))
|
| 224 |
+
|
| 225 |
+
preds = self.fc(self.dropout(h))
|
| 226 |
+
outputs[:, t, :] = preds
|
| 227 |
+
|
| 228 |
+
return outputs
|
| 229 |
+
|
| 230 |
+
@torch.no_grad()
|
| 231 |
+
def generate(
|
| 232 |
+
self,
|
| 233 |
+
image_embed: torch.Tensor,
|
| 234 |
+
start_idx: int,
|
| 235 |
+
end_idx: int,
|
| 236 |
+
max_len: int,
|
| 237 |
+
) -> list[int]:
|
| 238 |
+
assert image_embed.size(0) == 1, "generate() supports batch_size=1"
|
| 239 |
+
device = image_embed.device
|
| 240 |
+
|
| 241 |
+
h, c = self._init_hidden_state(image_embed)
|
| 242 |
+
current_token = torch.tensor([start_idx], device=device)
|
| 243 |
+
generated: list[int] = []
|
| 244 |
+
|
| 245 |
+
for _ in range(max_len):
|
| 246 |
+
word_embed = self.embedding(current_token)
|
| 247 |
+
context, _ = self.attention(image_embed, h)
|
| 248 |
+
gate = self.sigmoid(self.f_beta(h))
|
| 249 |
+
context = gate * context
|
| 250 |
+
|
| 251 |
+
lstm_input = torch.cat([word_embed, context], dim=1)
|
| 252 |
+
h, c = self.lstm_cell(lstm_input, (h, c))
|
| 253 |
+
logits = self.fc(h)
|
| 254 |
+
predicted_idx = int(logits.argmax(dim=-1).item())
|
| 255 |
+
|
| 256 |
+
if predicted_idx == end_idx:
|
| 257 |
+
break
|
| 258 |
+
|
| 259 |
+
generated.append(predicted_idx)
|
| 260 |
+
current_token = torch.tensor([predicted_idx], device=device)
|
| 261 |
+
|
| 262 |
+
return generated
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@torch.no_grad()
|
| 266 |
+
def generate_beam(
|
| 267 |
+
self,
|
| 268 |
+
image_embed: torch.Tensor,
|
| 269 |
+
start_idx: int,
|
| 270 |
+
end_idx: int,
|
| 271 |
+
max_len: int,
|
| 272 |
+
beam_width: int = 3,
|
| 273 |
+
) -> list[int]:
|
| 274 |
+
"""Beam search decoding for a SINGLE image (batch=1).
|
| 275 |
+
|
| 276 |
+
Same beam-search principle as DecoderLSTM.generate_beam(), adapted for
|
| 277 |
+
the LSTMCell + per-step attention loop: each beam carries its own
|
| 278 |
+
(h, c) hidden state, since attention (and therefore the next word
|
| 279 |
+
distribution) depends on each beam's own hidden state, not a shared one.
|
| 280 |
+
"""
|
| 281 |
+
assert image_embed.size(0) == 1, "generate_beam() supports batch_size=1"
|
| 282 |
+
device = image_embed.device
|
| 283 |
+
|
| 284 |
+
init_h, init_c = self._init_hidden_state(image_embed)
|
| 285 |
+
|
| 286 |
+
# each beam: (token_ids, cumulative_log_prob, h, c, finished)
|
| 287 |
+
beams = [([start_idx], 0.0, init_h, init_c, False)]
|
| 288 |
+
|
| 289 |
+
for _ in range(max_len):
|
| 290 |
+
all_candidates = []
|
| 291 |
+
for tokens, log_prob, h, c, finished in beams:
|
| 292 |
+
if finished:
|
| 293 |
+
all_candidates.append((tokens, log_prob, h, c, finished))
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
last_token = torch.tensor([tokens[-1]], device=device)
|
| 297 |
+
word_embed = self.embedding(last_token)
|
| 298 |
+
context, _ = self.attention(image_embed, h)
|
| 299 |
+
gate = self.sigmoid(self.f_beta(h))
|
| 300 |
+
context = gate * context
|
| 301 |
+
|
| 302 |
+
lstm_input = torch.cat([word_embed, context], dim=1)
|
| 303 |
+
new_h, new_c = self.lstm_cell(lstm_input, (h, c))
|
| 304 |
+
logits = self.fc(new_h)
|
| 305 |
+
log_probs = torch.log_softmax(logits, dim=-1).squeeze(0)
|
| 306 |
+
|
| 307 |
+
top_log_probs, top_indices = log_probs.topk(beam_width)
|
| 308 |
+
for lp, idx in zip(top_log_probs.tolist(), top_indices.tolist()):
|
| 309 |
+
new_tokens = tokens + [idx]
|
| 310 |
+
new_finished = idx == end_idx
|
| 311 |
+
all_candidates.append((new_tokens, log_prob + lp, new_h, new_c, new_finished))
|
| 312 |
+
|
| 313 |
+
all_candidates.sort(key=lambda cand: cand[1], reverse=True)
|
| 314 |
+
beams = all_candidates[:beam_width]
|
| 315 |
+
|
| 316 |
+
if all(finished for _, _, _, _, finished in beams):
|
| 317 |
+
break
|
| 318 |
+
|
| 319 |
+
best_tokens, _, _, _, _ = max(beams, key=lambda cand: cand[1])
|
| 320 |
+
result = best_tokens[1:]
|
| 321 |
+
if result and result[-1] == end_idx:
|
| 322 |
+
result = result[:-1]
|
| 323 |
+
return result
|
src/models/encoder.py
CHANGED
|
@@ -1,30 +1,83 @@
|
|
|
|
|
| 1 |
"""Encoder implementations.
|
| 2 |
|
| 3 |
Note: ResNet50 itself is NOT run here during training -- features are
|
|
|
|
| 4 |
precomputed/cached by scripts/extract_features.py (see src/features/extractor.py).
|
|
|
|
| 5 |
This module only holds the small trainable projection layer that maps cached
|
|
|
|
| 6 |
CNN features (e.g. 2048-d) down to the shared embedding space (e.g. 256-d).
|
|
|
|
| 7 |
"""
|
|
|
|
| 8 |
from __future__ import annotations
|
| 9 |
|
| 10 |
import torch
|
|
|
|
| 11 |
import torch.nn as nn
|
| 12 |
|
| 13 |
from src.models.base import BaseEncoder
|
| 14 |
|
| 15 |
-
|
| 16 |
class ResNet50Encoder(BaseEncoder):
|
|
|
|
| 17 |
"""Linear projection of cached, frozen ResNet50 features -> embed_dim."""
|
| 18 |
|
| 19 |
def __init__(self, feature_dim: int = 2048, embed_dim: int = 256, freeze: bool = True, **kwargs):
|
|
|
|
| 20 |
super().__init__()
|
|
|
|
| 21 |
self.freeze = freeze
|
|
|
|
| 22 |
self.linear = nn.Linear(feature_dim, embed_dim)
|
|
|
|
| 23 |
self.relu = nn.ReLU()
|
|
|
|
| 24 |
self.dropout = nn.Dropout(0.5)
|
| 25 |
|
| 26 |
def forward(self, image_features: torch.Tensor) -> torch.Tensor:
|
|
|
|
| 27 |
x = self.linear(image_features)
|
|
|
|
| 28 |
x = self.relu(x)
|
|
|
|
| 29 |
x = self.dropout(x)
|
| 30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
"""Encoder implementations.
|
| 3 |
|
| 4 |
Note: ResNet50 itself is NOT run here during training -- features are
|
| 5 |
+
|
| 6 |
precomputed/cached by scripts/extract_features.py (see src/features/extractor.py).
|
| 7 |
+
|
| 8 |
This module only holds the small trainable projection layer that maps cached
|
| 9 |
+
|
| 10 |
CNN features (e.g. 2048-d) down to the shared embedding space (e.g. 256-d).
|
| 11 |
+
|
| 12 |
"""
|
| 13 |
+
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
import torch
|
| 17 |
+
|
| 18 |
import torch.nn as nn
|
| 19 |
|
| 20 |
from src.models.base import BaseEncoder
|
| 21 |
|
|
|
|
| 22 |
class ResNet50Encoder(BaseEncoder):
|
| 23 |
+
|
| 24 |
"""Linear projection of cached, frozen ResNet50 features -> embed_dim."""
|
| 25 |
|
| 26 |
def __init__(self, feature_dim: int = 2048, embed_dim: int = 256, freeze: bool = True, **kwargs):
|
| 27 |
+
|
| 28 |
super().__init__()
|
| 29 |
+
|
| 30 |
self.freeze = freeze
|
| 31 |
+
|
| 32 |
self.linear = nn.Linear(feature_dim, embed_dim)
|
| 33 |
+
|
| 34 |
self.relu = nn.ReLU()
|
| 35 |
+
|
| 36 |
self.dropout = nn.Dropout(0.5)
|
| 37 |
|
| 38 |
def forward(self, image_features: torch.Tensor) -> torch.Tensor:
|
| 39 |
+
|
| 40 |
x = self.linear(image_features)
|
| 41 |
+
|
| 42 |
x = self.relu(x)
|
| 43 |
+
|
| 44 |
x = self.dropout(x)
|
| 45 |
+
|
| 46 |
+
return x
|
| 47 |
+
|
| 48 |
+
class ResNet50AttentionEncoder(BaseEncoder):
|
| 49 |
+
|
| 50 |
+
"""Projects a SPATIAL GRID of cached, frozen ResNet50 features -> embed_dim.
|
| 51 |
+
|
| 52 |
+
Unlike ResNet50Encoder (which projects one pooled global vector), this
|
| 53 |
+
|
| 54 |
+
projects each of the 49 spatial grid positions independently, preserving
|
| 55 |
+
|
| 56 |
+
per-region information for an attention-based decoder to attend over.
|
| 57 |
+
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, feature_dim: int = 2048, embed_dim: int = 256, freeze: bool = True, **kwargs):
|
| 61 |
+
|
| 62 |
+
super().__init__()
|
| 63 |
+
|
| 64 |
+
self.freeze = freeze
|
| 65 |
+
|
| 66 |
+
self.linear = nn.Linear(feature_dim, embed_dim)
|
| 67 |
+
|
| 68 |
+
self.relu = nn.ReLU()
|
| 69 |
+
|
| 70 |
+
self.dropout = nn.Dropout(0.5)
|
| 71 |
+
|
| 72 |
+
def forward(self, image_features: torch.Tensor) -> torch.Tensor:
|
| 73 |
+
|
| 74 |
+
# image_features: (batch, num_pixels, feature_dim) -- num_pixels=49 for a 7x7 grid
|
| 75 |
+
|
| 76 |
+
x = self.linear(image_features)
|
| 77 |
+
|
| 78 |
+
x = self.relu(x)
|
| 79 |
+
|
| 80 |
+
x = self.dropout(x)
|
| 81 |
+
|
| 82 |
+
return x
|
| 83 |
+
|
src/models/registry.py
CHANGED
|
@@ -9,15 +9,17 @@ No other file needs to change.
|
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
from src.models.base import BaseDecoder, BaseEncoder
|
| 12 |
-
from src.models.decoder import DecoderLSTM
|
| 13 |
-
from src.models.encoder import ResNet50Encoder
|
| 14 |
|
| 15 |
ENCODER_REGISTRY: dict[str, type[BaseEncoder]] = {
|
| 16 |
"resnet50": ResNet50Encoder,
|
|
|
|
| 17 |
}
|
| 18 |
|
| 19 |
DECODER_REGISTRY: dict[str, type[BaseDecoder]] = {
|
| 20 |
"lstm": DecoderLSTM,
|
|
|
|
| 21 |
}
|
| 22 |
|
| 23 |
|
|
@@ -34,4 +36,4 @@ def build_decoder(config: dict, vocab_size: int) -> BaseDecoder:
|
|
| 34 |
dec_type = dec_config.pop("type")
|
| 35 |
if dec_type not in DECODER_REGISTRY:
|
| 36 |
raise ValueError(f"Unknown decoder type '{dec_type}'. Available: {list(DECODER_REGISTRY)}")
|
| 37 |
-
return DECODER_REGISTRY[dec_type](vocab_size=vocab_size, **dec_config)
|
|
|
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
from src.models.base import BaseDecoder, BaseEncoder
|
| 12 |
+
from src.models.decoder import DecoderAttentionLSTM, DecoderLSTM
|
| 13 |
+
from src.models.encoder import ResNet50AttentionEncoder, ResNet50Encoder
|
| 14 |
|
| 15 |
ENCODER_REGISTRY: dict[str, type[BaseEncoder]] = {
|
| 16 |
"resnet50": ResNet50Encoder,
|
| 17 |
+
"resnet50_spatial": ResNet50AttentionEncoder,
|
| 18 |
}
|
| 19 |
|
| 20 |
DECODER_REGISTRY: dict[str, type[BaseDecoder]] = {
|
| 21 |
"lstm": DecoderLSTM,
|
| 22 |
+
"attention_lstm": DecoderAttentionLSTM,
|
| 23 |
}
|
| 24 |
|
| 25 |
|
|
|
|
| 36 |
dec_type = dec_config.pop("type")
|
| 37 |
if dec_type not in DECODER_REGISTRY:
|
| 38 |
raise ValueError(f"Unknown decoder type '{dec_type}'. Available: {list(DECODER_REGISTRY)}")
|
| 39 |
+
return DECODER_REGISTRY[dec_type](vocab_size=vocab_size, **dec_config)
|
src/training/__pycache__/trainer.cpython-312.pyc
CHANGED
|
Binary files a/src/training/__pycache__/trainer.cpython-312.pyc and b/src/training/__pycache__/trainer.cpython-312.pyc differ
|
|
|
src/training/trainer.py
CHANGED
|
@@ -29,8 +29,12 @@ class Trainer:
|
|
| 29 |
self.device = device
|
| 30 |
|
| 31 |
train_cfg = config["training"]
|
| 32 |
-
self.criterion = nn.CrossEntropyLoss(ignore_index=0)
|
| 33 |
-
self.optimizer = torch.optim.Adam(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
|
| 35 |
self.optimizer,
|
| 36 |
mode="min",
|
|
@@ -72,6 +76,9 @@ class Trainer:
|
|
| 72 |
|
| 73 |
if train:
|
| 74 |
loss.backward()
|
|
|
|
|
|
|
|
|
|
| 75 |
self.optimizer.step()
|
| 76 |
|
| 77 |
total_loss += loss.item()
|
|
|
|
| 29 |
self.device = device
|
| 30 |
|
| 31 |
train_cfg = config["training"]
|
| 32 |
+
self.criterion = nn.CrossEntropyLoss(ignore_index=0) # ignore <pad>
|
| 33 |
+
self.optimizer = torch.optim.Adam(
|
| 34 |
+
self.model.parameters(),
|
| 35 |
+
lr=train_cfg["lr"],
|
| 36 |
+
weight_decay=train_cfg.get("weight_decay", 0.0),
|
| 37 |
+
)
|
| 38 |
self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
|
| 39 |
self.optimizer,
|
| 40 |
mode="min",
|
|
|
|
| 76 |
|
| 77 |
if train:
|
| 78 |
loss.backward()
|
| 79 |
+
grad_clip = self.config["training"].get("grad_clip_norm", 0.0)
|
| 80 |
+
if grad_clip > 0:
|
| 81 |
+
torch.nn.utils.clip_grad_norm_(self.model.parameters(), grad_clip)
|
| 82 |
self.optimizer.step()
|
| 83 |
|
| 84 |
total_loss += loss.item()
|
src/utils/__pycache__/config.cpython-312.pyc
CHANGED
|
Binary files a/src/utils/__pycache__/config.cpython-312.pyc and b/src/utils/__pycache__/config.cpython-312.pyc differ
|
|
|
src/utils/config.py
CHANGED
|
@@ -48,6 +48,8 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
| 48 |
"epochs": 30,
|
| 49 |
"lr": 1e-3,
|
| 50 |
"optimizer": "adam",
|
|
|
|
|
|
|
| 51 |
"lr_scheduler_patience": 2,
|
| 52 |
"lr_scheduler_factor": 0.5,
|
| 53 |
"early_stop_patience": 5,
|
|
|
|
| 48 |
"epochs": 30,
|
| 49 |
"lr": 1e-3,
|
| 50 |
"optimizer": "adam",
|
| 51 |
+
"weight_decay": 0.0,
|
| 52 |
+
"grad_clip_norm": 0.0,
|
| 53 |
"lr_scheduler_patience": 2,
|
| 54 |
"lr_scheduler_factor": 0.5,
|
| 55 |
"early_stop_patience": 5,
|