Transformer Model Encoder for sequence to sequence translation.
| 333 | from flax.linen.partitioning import remat |
| 334 | |
| 335 | class CrossAttnEncoder(nn.Module): |
| 336 | """Transformer Model Encoder for sequence to sequence translation.""" |
| 337 | depth: int |
| 338 | mlp_dim: Optional[int] = None # Defaults to 4x input dim |
| 339 | num_heads: int = 12 |
| 340 | dropout: float = 0.0 |
| 341 | # drop_path: float = 0.0 |
| 342 | remat_policy: str = "none" |
| 343 | drop_path: float = 0.0 |
| 344 | casual_mask: bool = False |
| 345 | use_flash_attn: bool = False |
| 346 | dtype: Optional[Dtype] = jnp.float32 |
| 347 | param_dtype: Dtype = jnp.float32 |
| 348 | mesh: Any = None |
| 349 | |
| 350 | @nn.compact |
| 351 | def __call__(self, x, u, deterministic=True): |
| 352 | out = {} |
| 353 | dpr = [ |
| 354 | float(x) for x in np.linspace( |
| 355 | 0, |
| 356 | self.drop_path, |
| 357 | self.depth)] # drop path decay |
| 358 | # Input Encoder |
| 359 | CrossAttnBlockLayer = CrossAttnEncoder1DBlock |
| 360 | if self.remat_policy not in (None, "none"): |
| 361 | logging.info(f"remat policy: {self.remat_policy}") |
| 362 | if self.remat_policy == "minimal": |
| 363 | policy = jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims |
| 364 | else: |
| 365 | policy = None |
| 366 | logging.info(f"activation checkpointing {self.remat_policy}") |
| 367 | CrossAttnBlockLayer = remat( # pylint: disable=invalid-name |
| 368 | CrossAttnEncoder1DBlock, prevent_cse=True, policy=policy, static_argnums=(3,) |
| 369 | ) # "deterministic" is a static argument in CrossAttnEncoder1DBlock |
| 370 | |
| 371 | BlockLayer = Encoder1DBlock |
| 372 | if self.remat_policy not in (None, "none"): |
| 373 | logging.info(f"remat policy: {self.remat_policy}") |
| 374 | if self.remat_policy == "minimal": |
| 375 | policy = jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims |
| 376 | else: |
| 377 | policy = None |
| 378 | logging.info(f"activation checkpointing {self.remat_policy}") |
| 379 | BlockLayer = remat( # pylint: disable=invalid-name |
| 380 | Encoder1DBlock, prevent_cse=True, policy=policy, static_argnums=(1,) |
| 381 | ) # "deterministic" is a static argument in Encoder1DBlock |
| 382 | |
| 383 | for lyr in range(self.depth): |
| 384 | x, out[f"block{lyr:02d}"] = BlockLayer( |
| 385 | name=f"encoderblock_{lyr}", |
| 386 | mlp_dim=self.mlp_dim, |
| 387 | depth=self.depth, |
| 388 | num_heads=self.num_heads, |
| 389 | dropout=self.dropout, |
| 390 | drop_path=dpr[lyr], |
| 391 | casual_mask=self.casual_mask, |
| 392 | use_flash_attn=self.use_flash_attn, |