MCPcopy Create free account
hub / github.com/UCSC-VLAA/OpenVision / Encoder1DBlock

Class Encoder1DBlock

src/models/vit.py:245–334  ·  view source on GitHub ↗

Single transformer encoder block (MHSA + MLP).

Source from the content-addressed store, hash-verified

243
244
245class Encoder1DBlock(nn.Module):
246 """Single transformer encoder block (MHSA + MLP)."""
247 mlp_dim: Optional[int] = None # Defaults to 4x input dim
248 num_heads: int = 12
249 dropout: float = 0.0
250 drop_path: float = 0.0
251 init_values: float = None
252 use_flash_attn: bool = False
253 dtype: Optional[Dtype] = jnp.float32
254 param_dtype: Dtype = jnp.float32
255 mesh: Any = None
256 use_dense_general: bool = False
257 scan_mlp: bool = False
258 scan_attn: bool = False
259 mlp_chunck: int = 128
260
261 @nn.compact
262 def __call__(self, x, deterministic=True):
263 out = {}
264 x = x.astype(self.dtype)
265 x = nn.with_logical_constraint(x, ("activation_batch", "activation_length", "activation_embed"))
266
267 y = nn.LayerNorm(
268 dtype=self.dtype,
269 param_dtype=self.param_dtype,
270 scale_init=nn.with_logical_partitioning(nn.initializers.ones_init(), ("norm",)),
271 bias_init=nn.with_logical_partitioning(nn.initializers.zeros_init(), (None,)),
272 )(x)
273 y = nn.with_logical_constraint(y, ("activation_batch", "activation_length", "activation_embed"))
274
275 ## hack init func
276 y = out["sa"] = common.MultiHeadDotProductAttention(
277 num_heads=self.num_heads,
278 qkv_kernel_init=nn.initializers.normal(stddev=0.02),
279 out_kernel_init=nn.initializers.normal(stddev=0.02),
280 bias_init=nn.initializers.zeros,
281 deterministic=deterministic,
282 use_flash_attn=self.use_flash_attn,
283 scan_attn=self.scan_attn,
284 scan_attn_chunck=self.mlp_chunck,
285 dtype=self.dtype,
286 param_dtype=self.param_dtype,
287 mesh=self.mesh,
288 use_dense_general=self.use_dense_general
289 )(y, y)
290 y = nn.with_logical_constraint(y, ("activation_batch", "activation_length", "activation_embed"))
291
292 y = nn.Dropout(rate=self.dropout)(y, deterministic)
293 if self.init_values is not None:
294 n, l, d = y.shape
295 y = LayerScale(d, init_values=self.init_values, name='ls1')(y)
296 y = DropPath(dropout_prob=self.drop_path)(y, deterministic)
297 x = out["+sa"] = x + y
298 x = nn.with_logical_constraint(x, ("activation_batch", "activation_length", "activation_embed"))
299
300 y = nn.LayerNorm(dtype=self.dtype,
301 param_dtype=self.param_dtype,
302 scale_init=nn.with_logical_partitioning(nn.initializers.ones_init(), ("norm",)),

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected