MCPcopy Create free account
hub / github.com/DSL-Lab/StreamSplat / Block

Class Block

encoders/dinov2/layers/block.py:49–120  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

47
48
49class Block(nn.Module):
50 def __init__(
51 self,
52 dim: int,
53 num_heads: int,
54 mlp_ratio: float = 4.0,
55 qkv_bias: bool = False,
56 proj_bias: bool = True,
57 ffn_bias: bool = True,
58 drop: float = 0.0,
59 attn_drop: float = 0.0,
60 init_values=None,
61 drop_path: float = 0.0,
62 act_layer: Callable[..., nn.Module] = nn.GELU,
63 norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
64 attn_class: Callable[..., nn.Module] = Attention,
65 ffn_layer: Callable[..., nn.Module] = Mlp,
66 ) -> None:
67 super().__init__()
68 # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
69 self.norm1 = norm_layer(dim)
70 self.attn = attn_class(
71 dim,
72 num_heads=num_heads,
73 qkv_bias=qkv_bias,
74 proj_bias=proj_bias,
75 attn_drop=attn_drop,
76 proj_drop=drop,
77 )
78 self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
79 self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
80
81 self.norm2 = norm_layer(dim)
82 mlp_hidden_dim = int(dim * mlp_ratio)
83 self.mlp = ffn_layer(
84 in_features=dim,
85 hidden_features=mlp_hidden_dim,
86 act_layer=act_layer,
87 drop=drop,
88 bias=ffn_bias,
89 )
90 self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
91 self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
92
93 self.sample_drop_ratio = drop_path
94
95 def forward(self, x: Tensor) -> Tensor:
96 def attn_residual_func(x: Tensor) -> Tensor:
97 return self.ls1(self.attn(self.norm1(x)))
98
99 def ffn_residual_func(x: Tensor) -> Tensor:
100 return self.ls2(self.mlp(self.norm2(x)))
101
102 if self.training and self.sample_drop_ratio > 0.1:
103 # the overhead is compensated only for a drop path rate larger than 0.1
104 x = drop_add_residual_stochastic_depth(
105 x,
106 residual_func=attn_residual_func,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected