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

Class CrossAttnEncoder1DBlock

src/models/text_decoder_v2.py:208–282  ·  view source on GitHub ↗

A Transformer block with cross-attention followed by an MLP. This block takes two inputs: `x` (typically text embeddings) which acts as the query, and `u` (typically image embeddings) which acts as the key and value for the cross-attention layer. Attributes: mlp_dim: The hi

Source from the content-addressed store, hash-verified

206
207
208class CrossAttnEncoder1DBlock(nn.Module):
209 """A Transformer block with cross-attention followed by an MLP.
210
211 This block takes two inputs: `x` (typically text embeddings) which acts
212 as the query, and `u` (typically image embeddings) which acts as the
213 key and value for the cross-attention layer.
214
215 Attributes:
216 mlp_dim: The hidden dimension of the MLP block.
217 num_heads: The number of attention heads.
218 dropout: Dropout rate for attention and MLP outputs.
219 drop_path: Stochastic depth drop rate.
220 depth: The total number of layers in the parent encoder, used for weight init scaling.
221 use_flash_attn: Whether to use TPU Flash Attention.
222 dtype: The computation data type.
223 param_dtype: The parameter data type.
224 mesh: The JAX device mesh for model parallelism.
225 """
226 mlp_dim: Optional[int] = None
227 num_heads: int = 12
228 dropout: float = 0.0
229 drop_path: float = 0.0
230 depth: int = 12
231 use_flash_attn: bool = False
232 dtype: Optional[Dtype] = jnp.float32
233 param_dtype: Dtype = jnp.float32
234 mesh: Optional[Any] = None
235
236 @nn.compact
237 def __call__(self, x: Array, u: Array, deterministic: bool = True) -> Tuple[Array, dict]:
238 width = x.shape[-1]
239 # Scaled weight initialization based on model depth
240 init_std = {
241 'proj': (width ** -0.5) * ((2 * self.depth) ** -0.5),
242 'attn': width ** -0.5,
243 'fc': (2 * width) ** -0.5
244 }
245 out = {}
246
247 # Cross-Attention part
248 y = nn.LayerNorm(dtype=self.dtype, param_dtype=self.param_dtype, name="ln_x")(x)
249 v = nn.LayerNorm(dtype=self.dtype, param_dtype=self.param_dtype, name="ln_u")(u)
250
251 y = out["cross_attn"] = MultiHeadDotProductAttention(
252 num_heads=self.num_heads,
253 attn_kernel_init=nn.initializers.normal(stddev=init_std['attn']),
254 proj_kernel_init=nn.initializers.normal(stddev=init_std['proj']),
255 bias_init=nn.initializers.zeros,
256 dtype=self.dtype,
257 param_dtype=self.param_dtype,
258 deterministic=deterministic,
259 use_flash_attn=self.use_flash_attn,
260 mesh=self.mesh,
261 )(inputs_q=y, inputs_kv=v)
262
263 y = nn.Dropout(rate=self.dropout)(y, deterministic)
264 y = DropPath(dropout_prob=self.drop_path)(y, deterministic)
265 x = x + y

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected