yeonjung77 commited on
Commit
1ebce2f
·
verified ·
1 Parent(s): b6bb637

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +178 -0
model.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ P3 모델 -- Fashionpedia 2-Stage Model (Fashion Image Segmentation · Attribute Tagging)
3
+
4
+ [Stage 1] build_maskrcnn() -- Mask R-CNN ResNet50-FPN v2 (COCO pretrained)
5
+ · box/mask predictor 를 Fashionpedia 47-class(46 카테고리 + background) 로 교체
6
+ · 입력: List[Tensor[3,H,W]] / 출력: train→loss dict, eval→예측 List[Dict]
7
+
8
+ [Stage 2] AttributeClassifier -- ResNet-50 기반 multi-label 속성 분류
9
+ · 입력: Tensor[B,3,224,224] (배경 제거된 crop)
10
+ · 출력: logits [B,294] (sigmoid 는 BCEWithLogitsLoss 내부에서)
11
+
12
+ [헬퍼] build_model(stage, **kwargs) -- 'maskrcnn' / 'attribute' 분기
13
+
14
+ [중요] Stage 1 label 은 dataset 에서 category_id+1 로 들어온다 (0=background).
15
+ 따라서 num_classes=47, 추론 결과를 보여줄 땐 label-1 로 되돌린다.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import List
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ import torchvision
26
+ from torchvision.models.detection import (
27
+ maskrcnn_resnet50_fpn_v2,
28
+ MaskRCNN_ResNet50_FPN_V2_Weights,
29
+ )
30
+ from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
31
+ from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
32
+
33
+
34
+ # ============================================================================
35
+ # Stage 1: Mask R-CNN
36
+ # ============================================================================
37
+
38
+ def build_maskrcnn(num_classes: int = 47, pretrained: bool = True) -> nn.Module:
39
+ """Mask R-CNN ResNet50-FPN v2 를 Fashionpedia 용으로 만든다.
40
+
41
+ COCO 로 사전학습된 모델을 불러온 뒤, 마지막 분류/마스크 head 만 우리 클래스 수
42
+ (47 = 46 카테고리 + background)에 맞게 갈아끼운다. backbone(특징 추출부)은
43
+ COCO 가중치를 그대로 살려 전이학습한다.
44
+
45
+ Args:
46
+ num_classes (int): 클래스 수 (background 포함). Fashionpedia 는 47.
47
+ pretrained (bool): COCO 사전학습 가중치 사용 여부.
48
+
49
+ Returns:
50
+ nn.Module: head 가 교체된 Mask R-CNN.
51
+ · train(): model(images, targets) → loss dict
52
+ · eval(): model(images) → [{boxes,labels,scores,masks}, ...]
53
+ """
54
+ weights = MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1 if pretrained else None
55
+ model = maskrcnn_resnet50_fpn_v2(weights=weights)
56
+
57
+ # 1) 박스 분류 head 교체 (cls_score / bbox_pred 를 num_classes 로)
58
+ in_features = model.roi_heads.box_predictor.cls_score.in_features
59
+ model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
60
+
61
+ # 2) 마스크 예측 head 교체
62
+ in_channels_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
63
+ hidden_dim = 256
64
+ model.roi_heads.mask_predictor = MaskRCNNPredictor(in_channels_mask, hidden_dim, num_classes)
65
+
66
+ return model
67
+
68
+
69
+ # ============================================================================
70
+ # Stage 2: Attribute Classifier
71
+ # ============================================================================
72
+
73
+ class AttributeClassifier(nn.Module):
74
+ """ResNet-50 기반 multi-label 속성 분류기 (Stage 2).
75
+
76
+ 배경이 제거된 인스턴스 crop 을 받아 294개 속성에 대한 logit 을 출력한다.
77
+ backbone(특징 추출부)은 ImageNet 사전학습 가중치를 쓰고, 그 위에 새 분류 head 를 얹는다.
78
+
79
+ 구조:
80
+ backbone : ResNet-50 (GAP/fc 제거) → feature map [B, 2048, 7, 7]
81
+ head : GAP → Dropout → Linear(2048→512) → ReLU → Dropout → Linear(512→294)
82
+
83
+ Args:
84
+ backbone (str): 'resnet50' (그 외 이름은 timm 으로 생성 시도).
85
+ num_attrs (int): 속성 수 (294).
86
+ pretrained (bool): ImageNet 사전학습 사용 여부.
87
+ dropout (float): 드롭아웃 비율.
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ backbone: str = "resnet50",
93
+ num_attrs: int = 294,
94
+ pretrained: bool = True,
95
+ dropout: float = 0.3,
96
+ ) -> None:
97
+ super().__init__()
98
+ self.num_attrs = num_attrs
99
+
100
+ if backbone == "resnet50":
101
+ from torchvision.models import resnet50, ResNet50_Weights
102
+ weights = ResNet50_Weights.IMAGENET1K_V2 if pretrained else None
103
+ net = resnet50(weights=weights)
104
+ self.feature_dim = net.fc.in_features # 2048
105
+ # 마지막 avgpool(GAP) + fc 를 떼어내 feature map 추출부만 남긴다
106
+ self.backbone = nn.Sequential(*list(net.children())[:-2])
107
+ else:
108
+ import timm
109
+ # global_pool='' → GAP 미적용 feature map, num_classes=0 → fc 제거
110
+ self.backbone = timm.create_model(
111
+ backbone, pretrained=pretrained, num_classes=0, global_pool=""
112
+ )
113
+ self.feature_dim = self.backbone.num_features
114
+
115
+ # 분류 head (GAP 포함). sigmoid 는 적용하지 않음 (BCEWithLogitsLoss).
116
+ self.head = nn.Sequential(
117
+ nn.AdaptiveAvgPool2d((1, 1)),
118
+ nn.Flatten(1),
119
+ nn.Dropout(dropout),
120
+ nn.Linear(self.feature_dim, 512),
121
+ nn.ReLU(inplace=True),
122
+ nn.Dropout(dropout),
123
+ nn.Linear(512, num_attrs),
124
+ )
125
+
126
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
127
+ """순전파.
128
+
129
+ Args:
130
+ x (torch.Tensor): [B, 3, 224, 224]
131
+
132
+ Returns:
133
+ torch.Tensor: logits [B, num_attrs] (sigmoid 전)
134
+ """
135
+ features = self.backbone(x) # [B, 2048, 7, 7]
136
+ logits = self.head(features) # [B, num_attrs]
137
+ return logits
138
+
139
+ def get_param_groups(
140
+ self, backbone_lr: float = 1e-5, head_lr: float = 1e-4
141
+ ) -> List[dict]:
142
+ """backbone 과 head 에 서로 다른 학습률을 주는 파라미터 그룹.
143
+
144
+ 사전학습된 backbone 은 살짝만(작은 lr), 새로 얹은 head 는 빠르게(큰 lr) 학습한다.
145
+
146
+ Args:
147
+ backbone_lr (float): backbone 학습률.
148
+ head_lr (float): head 학습률.
149
+
150
+ Returns:
151
+ List[dict]: optimizer 에 그대로 넘길 파라미터 그룹.
152
+ """
153
+ return [
154
+ {"params": self.backbone.parameters(), "lr": backbone_lr},
155
+ {"params": self.head.parameters(), "lr": head_lr},
156
+ ]
157
+
158
+
159
+ # ============================================================================
160
+ # 빌더 헬퍼
161
+ # ============================================================================
162
+
163
+ def build_model(stage: str, **kwargs) -> nn.Module:
164
+ """stage 이름으로 알맞은 모델을 만든다.
165
+
166
+ Args:
167
+ stage (str): 'maskrcnn'(Stage 1) 또는 'attribute'(Stage 2).
168
+ **kwargs: 각 빌더로 그대로 전달 (num_classes/pretrained 또는
169
+ backbone/num_attrs/pretrained/dropout 등).
170
+
171
+ Returns:
172
+ nn.Module: 생성된 모델.
173
+ """
174
+ if stage == "maskrcnn":
175
+ return build_maskrcnn(**kwargs)
176
+ if stage == "attribute":
177
+ return AttributeClassifier(**kwargs)
178
+ raise ValueError(f"알 수 없는 stage: {stage!r} (가능: 'maskrcnn', 'attribute')")