Transformer Model Encoder for sequence to sequence translation.
| 507 | |
| 508 | |
| 509 | class Encoder(nn.Module): |
| 510 | """Transformer Model Encoder for sequence to sequence translation.""" |
| 511 | depth: int |
| 512 | mlp_dim: Optional[int] = None # Defaults to 4x input dim |
| 513 | num_heads: int = 12 |
| 514 | dropout: float = 0.0 |
| 515 | drop_path: float = 0.0 |
| 516 | remat_policy: str = "none" |
| 517 | casual_mask: bool = False |
| 518 | scan_mlp: bool = False |
| 519 | scan_attn: bool = False |
| 520 | mlp_chunck: int = 128 |
| 521 | use_flash_attn: bool = False |
| 522 | dtype: Optional[Dtype] = jnp.float32 |
| 523 | param_dtype: Dtype = jnp.float32 |
| 524 | mesh: Any = None |
| 525 | fusion_style: str = "cross_attn" |
| 526 | li: int = 0 |
| 527 | lt: int = 0 |
| 528 | use_dense_general: bool = False |
| 529 | |
| 530 | @nn.compact |
| 531 | def __call__(self, x, deterministic=True): |
| 532 | out = {} |
| 533 | dpr = [ |
| 534 | float(x) for x in np.linspace( |
| 535 | 0, |
| 536 | self.drop_path, |
| 537 | self.depth)] # drop path decay |
| 538 | # Input Encoder |
| 539 | if self.remat_policy != "none": |
| 540 | if self.remat_policy == "minimal": |
| 541 | policy = jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims |
| 542 | elif self.remat_policy == "minimal_offloaded": |
| 543 | policy = jax.checkpoint_policies.offload_dot_with_no_batch_dims(offload_src="device", |
| 544 | offload_dst="pinned_host") |
| 545 | elif self.remat_policy == "minimal_flash": |
| 546 | policy = jax.checkpoint_policies.save_from_both_policies( |
| 547 | jax.checkpoint_policies.checkpoint_dots_with_no_batch_dims, |
| 548 | jax.checkpoint_policies.save_only_these_names( |
| 549 | "context", |
| 550 | ), |
| 551 | ) |
| 552 | else: |
| 553 | assert self.remat_policy == "full", "Remat policy needs to be on list of remat policies" |
| 554 | policy = None |
| 555 | |
| 556 | BlockLayer = remat( # pylint: disable=invalid-name |
| 557 | Encoder1DBlock, prevent_cse=True, policy=policy, static_argnums=(1,) |
| 558 | ) # "deterministic" is a static argu |
| 559 | else: |
| 560 | BlockLayer = Encoder1DBlock |
| 561 | |
| 562 | for lyr in range(self.depth): |
| 563 | x, out[f"block{lyr:02d}"] = BlockLayer( |
| 564 | name=f"encoderblock_{lyr}", |
| 565 | mlp_dim=self.mlp_dim, |
| 566 | num_heads=self.num_heads, |