MCPcopy Create free account
hub / github.com/PolyU-ChenLab/UniPixel / MemoryEncoder

Class MemoryEncoder

sam2/modeling/memory_encoder.py:138–185  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

136
137
138class MemoryEncoder(nn.Module):
139
140 def __init__(
141 self,
142 out_dim,
143 mask_downsampler,
144 fuser,
145 position_encoding,
146 in_dim=256, # in_dim of pix_feats
147 ):
148 super().__init__()
149
150 self.mask_downsampler = mask_downsampler
151
152 self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
153 self.fuser = fuser
154 self.position_encoding = position_encoding
155 self.out_proj = nn.Identity()
156 if out_dim != in_dim:
157 self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
158
159 # save out_dim to avoid accessing model weights (breaks zero3)
160 self.out_dim = out_dim
161
162 def forward(
163 self,
164 pix_feat: torch.Tensor,
165 masks: torch.Tensor,
166 skip_mask_sigmoid: bool = False,
167 ) -> Tuple[torch.Tensor, torch.Tensor]:
168 # Process masks
169 # sigmoid, so that less domain shift from gt masks which are bool
170 if not skip_mask_sigmoid:
171 masks = F.sigmoid(masks)
172 masks = self.mask_downsampler(masks)
173
174 # Fuse pix_feats and downsampled masks
175 # in case the visual features are on CPU, cast them to CUDA
176 pix_feat = pix_feat.to(masks.device)
177
178 x = self.pix_feat_proj(pix_feat)
179 x = x + masks
180 x = self.fuser(x)
181 x = self.out_proj(x)
182
183 pos = self.position_encoding(x).to(x.dtype)
184
185 return {"vision_features": x, "vision_pos_enc": [pos]}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected