remote_model.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # this code is in active development, interfaces may change
  2. import os
  3. from typing import List, Optional, Tuple, Union
  4. import hivemind
  5. import torch
  6. import torch.nn as nn
  7. from hivemind import get_logger, use_hivemind_log_handler
  8. from src.bloom.model import (
  9. BloomConfig,
  10. BloomForCausalLM,
  11. BloomForSequenceClassification,
  12. BloomModel,
  13. BloomPreTrainedModel,
  14. LMHead,
  15. )
  16. from src.client.remote_generation import RemoteGenerationMixin
  17. from src.client.remote_sequential import RemoteSequential
  18. from src.utils.generation_algorithms import DecodingAlgorithm
  19. from src.utils.generation_constraints import ABCBloomConstraint
  20. use_hivemind_log_handler("in_root_logger")
  21. logger = get_logger(__file__)
  22. class DistributedBloomConfig(BloomConfig):
  23. """
  24. A bloom config that contains information about DHT peers.
  25. To create a distributed model, one must provide dht_prefix and either initial_peers or dht.
  26. """
  27. initial_peers: Tuple[str, ...] = () # a list of initial peers for hivemind DHT
  28. dht_prefix: str # a prefix for all dht keys that correspond to this model (usually equal to model name)
  29. dht: Optional[hivemind.DHT] = None # a running DHT instance, e.g. when using the same DHT for multiple models
  30. chunk_size_for_efficient_fp16_on_cpu: int = 10000 # a chunk size for a LM head for efficient half-precision on CPU
  31. num_prefix_tokens: int = 0 # a number of tokens for prompt tuning.
  32. class DistributedBloomModel(BloomModel):
  33. """BloomModel, but all transformer layers are hosted by the swarm"""
  34. config_class = DistributedBloomConfig
  35. def __init__(self, config: DistributedBloomConfig):
  36. assert config.dht_prefix, "Could not find dht_prefix in config, please create model with dht_prefix=..."
  37. assert config.initial_peers or config.dht, "Please specify initial_peers=list(...) or dht=hivemind.DHT(...)"
  38. n_layer, config.n_layer = config.n_layer, 0 # temporarily set n_layer to 0 to prevent layer initialization
  39. super().__init__(config)
  40. assert len(self.h) == 0
  41. config.n_layer = n_layer
  42. dht = (
  43. config.dht
  44. if config.dht is not None
  45. else hivemind.DHT(initial_peers=config.initial_peers, client_mode=True, start=True)
  46. )
  47. assert isinstance(dht, hivemind.DHT) and dht.is_alive(), "dht must be a running hivemind.DHT instance"
  48. self.h = RemoteSequential(config, dht, config.dht_prefix)
  49. # Forbid accumulate grads for embeddings and layernorm
  50. self.set_requires_grad(False)
  51. def set_requires_grad(self, value):
  52. for p in self.parameters():
  53. p.requires_grad = value
  54. def forward(self, *args, use_cache=None, **kwargs):
  55. if use_cache:
  56. raise ValueError(
  57. "Distributed forward does not support use_cache; for efficient cache-aware generation, "
  58. "please use model.transformer.inference_session() or model.generate(...)"
  59. )
  60. return super().forward(*args, use_cache=False, **kwargs)
  61. class DistributedBloomPrefix(DistributedBloomModel):
  62. """DistributedBloomModel with prefix tokens for prompt tuning"""
  63. def __init__(self, config):
  64. super().__init__(config)
  65. assert config.num_prefix_tokens > 0, "The number of prefix tokens must be > 0"
  66. self.prefix_length = config.num_prefix_tokens
  67. self.prompt_embeddings = nn.Embedding(self.prefix_length, config.hidden_size)
  68. self.prefix_tokens = torch.arange(self.prefix_length).long()
  69. def get_prompt(self, batch_size):
  70. prefix_tokens = self.prefix_tokens.unsqueeze(0).expand(batch_size, -1)
  71. prefix_tokens = prefix_tokens.to(self.word_embeddings.weight.device)
  72. prompts = self.prompt_embeddings(prefix_tokens)
  73. return prompts
  74. def forward(
  75. self,
  76. input_ids: Optional[torch.LongTensor],
  77. inputs_embeds: Optional[torch.Tensor],
  78. attention_mask: Optional[torch.Tensor],
  79. past_key_values=None,
  80. position_ids=None,
  81. head_mask=None,
  82. use_cache=None,
  83. output_attentions=None,
  84. output_hidden_states=None,
  85. return_dict=None,
  86. ):
  87. assert (
  88. input_ids is None or inputs_embeds is None
  89. ), "You cannot specify both input_ids and inputs_embeds at the same time"
  90. assert input_ids is not None or inputs_embeds is not None, "You must specify either input_ids or inputs_embeds"
  91. if inputs_embeds is None:
  92. inputs_embeds = self.word_embeddings(input_ids)
  93. batch_size = inputs_embeds.shape[0]
  94. if attention_mask is not None:
  95. prefix_attention_mask = torch.ones(batch_size, self.prefix_length, device=attention_mask.device)
  96. attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
  97. prompts = self.get_prompt(batch_size)
  98. inputs_embeds = torch.cat([prompts, inputs_embeds], dim=1)
  99. transformer_outputs = super().forward(
  100. inputs_embeds=inputs_embeds,
  101. attention_mask=attention_mask,
  102. past_key_values=past_key_values,
  103. position_ids=position_ids,
  104. head_mask=head_mask,
  105. use_cache=use_cache,
  106. output_attentions=output_attentions,
  107. output_hidden_states=output_hidden_states,
  108. return_dict=return_dict,
  109. )
  110. # Remove prefix
  111. last_hidden_state = transformer_outputs[0][:, self.prefix_length :]
  112. transformer_outputs["last_hidden_state"] = last_hidden_state
  113. return transformer_outputs
  114. class DistributedBloomForCausalLM(BloomForCausalLM, RemoteGenerationMixin):
  115. """DistributedBloomForCausalLM, but all transformer layers are hosted by the swarm"""
  116. config_class = DistributedBloomConfig
  117. def __init__(self, config: DistributedBloomConfig):
  118. BloomPreTrainedModel.__init__(self, config)
  119. if config.num_prefix_tokens > 0:
  120. self.transformer = DistributedBloomPrefix(config)
  121. else:
  122. self.transformer = DistributedBloomModel(config)
  123. self.lm_head = LMHead(config, self.transformer.word_embeddings)
  124. # Initialize weights and apply final processing
  125. self.post_init()
  126. def get_input_embeddings(self):
  127. return self.transformer.word_embeddings
  128. def get_output_embeddings(self):
  129. if self.config.tie_word_embeddings:
  130. return None
  131. return self.lm_head
  132. def set_input_embeddings(self, new_embeddings: nn.Embedding):
  133. assert isinstance(new_embeddings, nn.Embedding)
  134. self.transformer.word_embeddings = self.lm_head.word_embeddings = new_embeddings
  135. assert self.lm_head.bias is None or len(self.lm_head.bias) == new_embeddings.num_embeddings
  136. def set_output_embeddings(self, new_lm_head: nn.Linear):
  137. with torch.no_grad():
  138. self.lm_head.word_embeddings.weight[...] = new_lm_head.weight
  139. self.lm_head.bias[...] = new_lm_head.bias
  140. def generate(
  141. self,
  142. inputs: Optional[torch.Tensor] = None,
  143. do_sample: Optional[bool] = None,
  144. temperature: float = 1.0,
  145. top_k: Optional[int] = None,
  146. top_p: Optional[float] = None,
  147. eos_token_id: Optional[int] = None,
  148. max_new_tokens: Optional[int] = None,
  149. decoding_algorithm: Optional[DecodingAlgorithm] = None,
  150. provided_constraints: List[ABCBloomConstraint] = [],
  151. **model_kwargs,
  152. ) -> torch.Tensor:
  153. return RemoteGenerationMixin.generate(
  154. self,
  155. inputs=inputs,
  156. do_sample=do_sample,
  157. temperature=temperature,
  158. top_k=top_k,
  159. top_p=top_p,
  160. eos_token_id=eos_token_id,
  161. max_new_tokens=max_new_tokens,
  162. decoding_algorithm=decoding_algorithm,
  163. provided_constraints=provided_constraints,
  164. **model_kwargs,
  165. )
  166. class DistributedBloomForSequenceClassification(BloomForSequenceClassification):
  167. config_class = DistributedBloomConfig
  168. def __init__(self, config: DistributedBloomConfig):
  169. super().__init__(config)
  170. if config.num_prefix_tokens > 0:
  171. self.transformer = DistributedBloomPrefix(config)
  172. else:
  173. self.transformer = DistributedBloomModel(config)
  174. # Initialize weights and apply final processing
  175. self.post_init()