|
| 1 | +from typing import Optional |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | +from hivemind import DHT |
| 6 | +from hivemind.utils.logging import get_logger |
| 7 | +from transformers.modeling_outputs import MoeModelOutputWithPast |
| 8 | +from transformers.models.mixtral import ( |
| 9 | + MixtralForCausalLM, |
| 10 | + MixtralForSequenceClassification, |
| 11 | + MixtralModel, |
| 12 | + MixtralPreTrainedModel, |
| 13 | +) |
| 14 | + |
| 15 | +from petals.client.from_pretrained import FromPretrainedMixin |
| 16 | +from petals.client.lm_head import LMHead |
| 17 | +from petals.client.ptune import PTuneMixin |
| 18 | +from petals.client.remote_generation import RemoteGenerationMixin, RemotePastKeyValues |
| 19 | +from petals.client.remote_sequential import RemoteSequential |
| 20 | +from petals.models.mixtral.config import DistributedMixtralConfig |
| 21 | +from petals.utils.auto_config import DefaultRevisionMixin |
| 22 | + |
| 23 | +logger = get_logger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class DistributedMixtralModel(DefaultRevisionMixin, FromPretrainedMixin, PTuneMixin, MixtralModel): |
| 27 | + """MixtralModel, but all transformer layers are hosted by the swarm""" |
| 28 | + |
| 29 | + _keys_to_ignore_on_load_missing = PTuneMixin._keys_to_ignore_on_load_missing |
| 30 | + _keys_to_ignore_on_load_unexpected = [r"^model\.layers\."] |
| 31 | + |
| 32 | + config_class = DistributedMixtralConfig |
| 33 | + |
| 34 | + def __init__(self, config: DistributedMixtralConfig, *, dht: Optional[DHT] = None): |
| 35 | + n_layer, config.num_hidden_layers = config.num_hidden_layers, 0 # Prevent initialization |
| 36 | + super().__init__(config) |
| 37 | + assert len(self.layers) == 0 |
| 38 | + config.num_hidden_layers = n_layer |
| 39 | + |
| 40 | + self.layers = RemoteSequential(config, dht=dht) |
| 41 | + |
| 42 | + self.requires_grad_(False) # Forbid accumulate grads for embeddings and layernorm |
| 43 | + self.init_prompts(config) |
| 44 | + |
| 45 | + def forward( |
| 46 | + self, |
| 47 | + input_ids: Optional[torch.LongTensor] = None, |
| 48 | + past_key_values: Optional[RemotePastKeyValues] = None, |
| 49 | + attention_mask: Optional[torch.Tensor] = None, |
| 50 | + position_ids: Optional[torch.LongTensor] = None, |
| 51 | + head_mask: Optional[torch.LongTensor] = None, |
| 52 | + inputs_embeds: Optional[torch.LongTensor] = None, |
| 53 | + use_cache: Optional[bool] = None, |
| 54 | + output_attentions: Optional[bool] = None, |
| 55 | + output_hidden_states: Optional[bool] = None, |
| 56 | + output_router_logits: Optional[bool] = None, |
| 57 | + return_dict: Optional[bool] = None, |
| 58 | + ): |
| 59 | + if input_ids is not None and inputs_embeds is not None: |
| 60 | + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") |
| 61 | + elif input_ids is not None: |
| 62 | + input_shape = input_ids.size() |
| 63 | + input_ids = input_ids.view(-1, input_shape[-1]) |
| 64 | + elif inputs_embeds is not None: |
| 65 | + input_shape = inputs_embeds.size()[:-1] |
| 66 | + else: |
| 67 | + raise ValueError("You have to specify either input_ids or inputs_embeds") |
| 68 | + |
| 69 | + # The causal mask will be added on the server-side |
| 70 | + assert ( |
| 71 | + attention_mask is None or (attention_mask == 1).all() |
| 72 | + ), f"Custom attention masks are not supported, {attention_mask=}" |
| 73 | + assert ( |
| 74 | + position_ids is None or (position_ids[:, 1:] - position_ids[:, :-1] == 1).all() |
| 75 | + ), f"Non-consecutive position_ids are not supported, {position_ids=}" |
| 76 | + assert head_mask is None, f"Custom head masks are not supported, {head_mask=}" |
| 77 | + assert use_cache is None or use_cache, f"{use_cache=} is not supported" |
| 78 | + assert not output_attentions, f"{output_attentions=} is not supported" |
| 79 | + assert not output_hidden_states, f"{output_hidden_states=} is not supported" |
| 80 | + assert return_dict is None or return_dict, f"{return_dict=} is not supported" |
| 81 | + assert not output_router_logits, f"{output_router_logits=} is not supported" |
| 82 | + |
| 83 | + if inputs_embeds is None: |
| 84 | + inputs_embeds = self.embed_tokens(input_ids) |
| 85 | + |
| 86 | + use_prompts = self.config.tuning_mode and "ptune" in self.config.tuning_mode and self.h.position == 0 |
| 87 | + if use_prompts: |
| 88 | + batch_size = inputs_embeds.shape[0] |
| 89 | + prompts, intermediate_prompts = self.get_prompt(batch_size) |
| 90 | + inputs_embeds = torch.cat([prompts, inputs_embeds], dim=1) |
| 91 | + else: |
| 92 | + prompts = intermediate_prompts = None |
| 93 | + |
| 94 | + hidden_states = inputs_embeds |
| 95 | + output_shape = input_shape + (hidden_states.size(-1),) |
| 96 | + |
| 97 | + if past_key_values is None: |
| 98 | + past_key_values = RemotePastKeyValues() |
| 99 | + past_key_values.update_seen(hidden_states.size(1)) |
| 100 | + |
| 101 | + hidden_states = self.layers( |
| 102 | + hidden_states, |
| 103 | + prompts=intermediate_prompts, |
| 104 | + hypo_ids=past_key_values.hypo_ids if past_key_values is not None else None, |
| 105 | + ) |
| 106 | + |
| 107 | + # Remove prefix |
| 108 | + if use_prompts: |
| 109 | + hidden_states = hidden_states[:, self.pre_seq_len :] |
| 110 | + |
| 111 | + # Add last hidden state |
| 112 | + hidden_states = self.norm(hidden_states) |
| 113 | + hidden_states = hidden_states.view(output_shape) |
| 114 | + return MoeModelOutputWithPast( |
| 115 | + last_hidden_state=hidden_states, |
| 116 | + past_key_values=past_key_values, |
| 117 | + hidden_states=None, |
| 118 | + attentions=None, |
| 119 | + ) |
| 120 | + |
| 121 | + @property |
| 122 | + def word_embeddings(self) -> nn.Embedding: # For compatibility with RemoteGenerationMixin |
| 123 | + return self.embed_tokens |
| 124 | + |
| 125 | + @property |
| 126 | + def h(self) -> RemoteSequential: # For compatibility with RemoteGenerationMixin |
| 127 | + return self.layers |
| 128 | + |
| 129 | + |
| 130 | +class DistributedMixtralForCausalLM( |
| 131 | + DefaultRevisionMixin, FromPretrainedMixin, RemoteGenerationMixin, MixtralForCausalLM |
| 132 | +): |
| 133 | + _keys_to_ignore_on_load_missing = DistributedMixtralModel._keys_to_ignore_on_load_missing |
| 134 | + _keys_to_ignore_on_load_unexpected = DistributedMixtralModel._keys_to_ignore_on_load_unexpected |
| 135 | + |
| 136 | + config_class = DistributedMixtralConfig |
| 137 | + |
| 138 | + def __init__(self, config: DistributedMixtralConfig): |
| 139 | + MixtralPreTrainedModel.__init__(self, config) |
| 140 | + self.model = DistributedMixtralModel(config) |
| 141 | + self.lm_head = LMHead(config) |
| 142 | + |
| 143 | + # Initialize weights and apply final processing |
| 144 | + self.post_init() |
| 145 | + |
| 146 | + def get_output_embeddings(self): |
| 147 | + return self.lm_head |
| 148 | + |
| 149 | + @property |
| 150 | + def transformer(self) -> DistributedMixtralModel: # For compatibility with RemoteGenerationMixin |
| 151 | + return self.model |
| 152 | + |
| 153 | + |
| 154 | +class DistributedMixtralForSequenceClassification( |
| 155 | + DefaultRevisionMixin, FromPretrainedMixin, MixtralForSequenceClassification |
| 156 | +): |
| 157 | + def __init__(self, config: DistributedMixtralConfig): |
| 158 | + MixtralPreTrainedModel.__init__(self, config) |
| 159 | + self.num_labels = config.num_labels |
| 160 | + |
| 161 | + self.model = DistributedMixtralModel(config) |
| 162 | + self.score = nn.Linear(config.hidden_size, config.num_labels, bias=False) |
| 163 | + |
| 164 | + # Initialize weights and apply final processing |
| 165 | + self.post_init() |
| 166 | + |
| 167 | + @property |
| 168 | + def transformer(self) -> DistributedMixtralModel: # For compatibility with RemoteGenerationMixin |
| 169 | + return self.model |
0 commit comments