Transformer class.
| 577 | |
| 578 | |
| 579 | class GLMTransformer(torch.nn.Module): |
| 580 | """Transformer class.""" |
| 581 | |
| 582 | def __init__(self, config: ChatGLMConfig, device=None): |
| 583 | super(GLMTransformer, self).__init__() |
| 584 | |
| 585 | self.fp32_residual_connection = config.fp32_residual_connection |
| 586 | self.post_layer_norm = config.post_layer_norm |
| 587 | |
| 588 | # Number of layers. |
| 589 | self.num_layers = config.num_layers |
| 590 | |
| 591 | # Transformer layers. |
| 592 | def build_layer(layer_number): |
| 593 | return GLMBlock(config, layer_number, device=device) |
| 594 | |
| 595 | self.layers = torch.nn.ModuleList([build_layer(i + 1) for i in range(self.num_layers)]) |
| 596 | |
| 597 | if self.post_layer_norm: |
| 598 | LayerNormFunc = RMSNorm if config.rmsnorm else LayerNorm |
| 599 | # Final layer norm before output. |
| 600 | self.final_layernorm = LayerNormFunc(config.hidden_size, eps=config.layernorm_epsilon, device=device, |
| 601 | dtype=config.torch_dtype) |
| 602 | |
| 603 | self.gradient_checkpointing = False |
| 604 | |
| 605 | def _get_layer(self, layer_number): |
| 606 | return self.layers[layer_number] |
| 607 | |
| 608 | def forward( |
| 609 | self, hidden_states, attention_mask, rotary_pos_emb, kv_caches=None, |
| 610 | use_cache: Optional[bool] = True, |
| 611 | output_hidden_states: Optional[bool] = False, |
| 612 | ): |
| 613 | if not kv_caches: |
| 614 | kv_caches = [None for _ in range(self.num_layers)] |
| 615 | presents = () if use_cache else None |
| 616 | if self.gradient_checkpointing and self.training: |
| 617 | if use_cache: |
| 618 | logger.warning_once( |
| 619 | "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." |
| 620 | ) |
| 621 | use_cache = False |
| 622 | |
| 623 | all_self_attentions = None |
| 624 | all_hidden_states = () if output_hidden_states else None |
| 625 | for index in range(self.num_layers): |
| 626 | if output_hidden_states: |
| 627 | all_hidden_states = all_hidden_states + (hidden_states,) |
| 628 | |
| 629 | layer = self._get_layer(index) |
| 630 | if self.gradient_checkpointing and self.training: |
| 631 | layer_ret = torch.utils.checkpoint.checkpoint( |
| 632 | layer, |
| 633 | hidden_states, |
| 634 | attention_mask, |
| 635 | rotary_pos_emb, |
| 636 | kv_caches[index], |
nothing calls this directly
no outgoing calls
no test coverage detected