MCPcopy Create free account
hub / github.com/Ropedia/SpatialBench / PatchEmbed

Class PatchEmbed

benchmark/models/zipmap/zipmap/layers/patch_embed.py:22–82  ·  view source on GitHub ↗

2D image to patch embedding: (B,C,H,W) -> (B,N,D) Args: img_size: Image size. patch_size: Patch token size. in_chans: Number of input image channels. embed_dim: Number of linear projection output channels. norm_layer: Normalization layer.

Source from the content-addressed store, hash-verified

20
21
22class PatchEmbed(nn.Module):
23 """
24 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
25
26 Args:
27 img_size: Image size.
28 patch_size: Patch token size.
29 in_chans: Number of input image channels.
30 embed_dim: Number of linear projection output channels.
31 norm_layer: Normalization layer.
32 """
33
34 def __init__(
35 self,
36 img_size: Union[int, Tuple[int, int]] = 224,
37 patch_size: Union[int, Tuple[int, int]] = 16,
38 in_chans: int = 3,
39 embed_dim: int = 768,
40 norm_layer: Optional[Callable] = None,
41 flatten_embedding: bool = True,
42 ) -> None:
43 super().__init__()
44
45 image_HW = make_2tuple(img_size)
46 patch_HW = make_2tuple(patch_size)
47 patch_grid_size = (image_HW[0] // patch_HW[0], image_HW[1] // patch_HW[1])
48
49 self.img_size = image_HW
50 self.patch_size = patch_HW
51 self.patches_resolution = patch_grid_size
52 self.num_patches = patch_grid_size[0] * patch_grid_size[1]
53
54 self.in_chans = in_chans
55 self.embed_dim = embed_dim
56
57 self.flatten_embedding = flatten_embedding
58
59 self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
60 self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
61
62 def forward(self, x: Tensor) -> Tensor:
63 _, _, H, W = x.shape
64 patch_H, patch_W = self.patch_size
65
66 assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
67 assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
68
69 x = self.proj(x) # B C H W
70 H, W = x.size(2), x.size(3)
71 x = x.flatten(2).transpose(1, 2) # B HW C
72 x = self.norm(x)
73 if not self.flatten_embedding:
74 x = x.reshape(-1, H, W, self.embed_dim) # B H W C
75 return x
76
77 def flops(self) -> float:
78 Ho, Wo = self.patches_resolution
79 flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])

Callers 2

__init__Method · 0.90
__build_patch_embed__Method · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected