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

Class CrossAttnEncoder1DBlock

src/models/text_decoder.py:249–331  ·  view source on GitHub ↗

Single transformer encoder block (MHSA + MLP).

Source from the content-addressed store, hash-verified

247
248
249class CrossAttnEncoder1DBlock(nn.Module):
250 """Single transformer encoder block (MHSA + MLP)."""
251 mlp_dim: Optional[int] = None # Defaults to 4x input dim
252 num_heads: int = 12
253 dropout: float = 0.0
254 drop_path: float = 0.0
255 depth: int = 12
256 casual_mask: bool = False
257 use_flash_attn: bool = False
258 dtype: Optional[Dtype] = jnp.float32
259 param_dtype: Dtype = jnp.float32
260 mesh: Any = None
261
262 @nn.compact
263 def __call__(self, x, u, attn_mask=None, deterministic=True):
264 width = x.shape[-1]
265 init_std = {
266 'proj': (width ** -0.5) * ((2 * self.depth) ** -0.5),
267 'attn': width ** -0.5,
268 'fc': (2 * width) ** -0.5
269 }
270 out = {}
271 x = x.astype(self.dtype)
272 x = nn.with_logical_constraint(x, ("activation_batch", "activation_length", "activation_embed"))
273 y = nn.LayerNorm(
274 dtype=self.dtype,
275 param_dtype=self.param_dtype,
276 scale_init=nn.with_logical_partitioning(nn.initializers.ones_init(), ("norm",)),
277 bias_init=nn.with_logical_partitioning(nn.initializers.zeros_init(), (None,)),
278 )(x)
279 y = nn.with_logical_constraint(y, ("activation_batch", "activation_length", "activation_embed"))
280
281 u = u.astype(self.dtype)
282 u = nn.with_logical_constraint(u, ("activation_batch", "activation_length", "activation_embed"))
283 v = nn.LayerNorm(
284 dtype=self.dtype,
285 param_dtype=self.param_dtype,
286 scale_init=nn.with_logical_partitioning(nn.initializers.ones_init(), ("norm",)),
287 bias_init=nn.with_logical_partitioning(nn.initializers.zeros_init(), (None,)),
288 )(u)
289 v = nn.with_logical_constraint(v, ("activation_batch", "activation_length", "activation_embed"))
290
291 y = out["sa"] = MultiHeadDotProductAttention(
292 num_heads=self.num_heads,
293 attn_kernel_init=nn.initializers.normal(stddev=init_std['attn']),
294 proj_kernel_init=nn.initializers.normal(stddev=init_std['proj']),
295 bias_init=nn.initializers.zeros,
296 dtype=self.dtype,
297 param_dtype=self.param_dtype,
298 deterministic=deterministic,
299 use_flash_attn=self.use_flash_attn,
300 scan_attn=self.scan_attn,
301 scan_attn_chunck=self.mlp_chunck,
302 mesh=self.mesh,
303 )(y, v, mask=attn_mask if self.casual_mask else None)
304 y = nn.Dropout(rate=self.dropout)(y, deterministic)
305 # y = DropPath(dropout_prob=self.drop_path)(y, deterministic)
306 x = out["+sa"] = x + y

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected