model.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import torch
  2. from typing import List, Union
  3. from SwissArmyTransformer.generation.autoregressive_sampling import update_mems, get_masks_and_position_ids_default
  4. from SwissArmyTransformer.mpu import vocab_parallel_cross_entropy
  5. def batch_filling_sequence(
  6. model,
  7. seqs,
  8. context_lengths,
  9. strategy,
  10. max_memory_length=100000,
  11. get_masks_and_position_ids=get_masks_and_position_ids_default,
  12. mems=None,
  13. **kw_args
  14. ):
  15. '''
  16. seq: [2, 3, 5, ..., -1(to be generated), -1, ...]
  17. mems: [num_layers, batch_size, len_mems(index), mem_hidden_size]
  18. cache, should be first mems.shape[1] parts of context_tokens.
  19. mems are the first-level citizens here, but we don't assume what is memorized.
  20. input mems are used when multi-phase generation.
  21. '''
  22. assert len(seqs.shape) == 2
  23. # building the initial tokens, attention_mask, and position_ids
  24. batch_size, context_length = seqs.shape
  25. seqs, attention_mask, position_ids = get_masks_and_position_ids(seqs)
  26. tokens = seqs[..., :context_length]
  27. if attention_mask.dtype != torch.bool:
  28. attention_mask = attention_mask.type_as(next(model.parameters())) # if fp16
  29. # initialize generation
  30. counter = context_length - 1 # Last fixed index is ``counter''
  31. index = 0 if mems is None else mems.shape[2] # Next forward starting index, also the length of cache.
  32. num_beams = 1
  33. # step-by-step generation
  34. while counter < seqs.shape[1] - 1:
  35. # Now, we want to generate seq[counter + 1],
  36. # token[:, index: counter+1] needs forwarding.
  37. # forward
  38. tokens = tokens.reshape(batch_size * num_beams, -1)
  39. mems = mems.reshape(mems.shape[0], batch_size * num_beams, mems.shape[-2], mems.shape[-1]) if mems is not None else None
  40. logits, *output_per_layers = model(
  41. tokens[:, index:],
  42. position_ids[..., index: counter+1],
  43. attention_mask[..., index: counter+1, :counter+1], # TODO memlen
  44. mems=mems,
  45. **kw_args
  46. )
  47. mem_kv = [o['mem_kv'] for o in output_per_layers]
  48. mems = update_mems(mem_kv, mems, max_memory_length=max_memory_length)
  49. if counter == context_length - 1:
  50. logits = logits[torch.arange(batch_size), context_lengths - 1]
  51. else:
  52. logits = logits[:, -1]
  53. counter += 1
  54. index = counter
  55. # if torch.distributed.get_rank() == 0:
  56. # print(f"counter: {counter}: logits: {logits.float().abs().mean()}")
  57. # sampling
  58. logits = logits.reshape(batch_size, num_beams, -1)
  59. tokens = tokens.reshape(batch_size, num_beams, -1)
  60. mems = mems.reshape(mems.shape[0], batch_size, num_beams, mems.shape[-2], mems.shape[-1])
  61. tokens, mems = strategy.forward(logits, tokens, mems)
  62. if len(tokens.shape) == 3 and num_beams == 1:
  63. num_beams = tokens.shape[1]
  64. position_ids = position_ids.unsqueeze(1).expand(batch_size, num_beams, -1).reshape(batch_size * num_beams, -1)
  65. attention_mask_shape = attention_mask.shape[-3:]
  66. attention_mask = attention_mask.unsqueeze(1).expand(batch_size, num_beams, -1, -1, -1).reshape(
  67. batch_size * num_beams, *attention_mask_shape)
  68. if strategy.is_done:
  69. break
  70. return strategy.finalize(tokens, mems)
  71. class ModelForEvaluation(torch.nn.Module):
  72. def __init__(self, model):
  73. super().__init__()
  74. self.model = model
  75. self.device = next(self.model.parameters()).device
  76. @staticmethod
  77. def process_data(batch, device):
  78. return (
  79. batch["tokens"].to(device=device).long(),
  80. batch["position_ids"].to(device=device).long(),
  81. batch["attention_mask"].to(device=device).bool().unsqueeze(1),
  82. )
  83. def cond_log_prob(self, batch) -> List[List[float]]:
  84. """
  85. @return: Conditional log probability of each option
  86. """
  87. tokens, position_ids, attention_mask = self.process_data(batch, self.device)
  88. choices_batch, choice_target_ids_batch = batch["choices"], batch["choice_target_ids"]
  89. is_single_token = batch["is_single_token"]
  90. self.model.eval()
  91. with torch.no_grad():
  92. logits, *output_per_layers = self.model(tokens, position_ids, attention_mask, log_attention_weights=None)
  93. logits_batch = torch.nn.functional.log_softmax(logits, dim=-1)
  94. # output: [b, sq, vocab]
  95. log_probs = []
  96. if is_single_token: # Single token
  97. for logits, choices, choice_target_ids in zip(logits_batch, choices_batch, choice_target_ids_batch):
  98. log_probs.append(logits[choice_target_ids[0], choices].tolist())
  99. else: # Multi token
  100. for output, choices, choice_target_ids in zip(logits_batch, choices_batch, choice_target_ids_batch):
  101. log_probs_single = []
  102. for choice, choice_target_id in zip(choices, choice_target_ids):
  103. tmp = output[choice_target_id, choice]
  104. log_probs_single.append(tmp.sum().tolist())
  105. log_probs.append(log_probs_single)
  106. return log_probs
  107. def generate_text(self, sample, strategy, return_all_beams=False) -> Union[
  108. List[List[int]], List[List[List[int]]]]:
  109. """
  110. @return: A list of text model generated, sorted by score in descending order
  111. """
  112. seqs = sample["tokens"].to(device=self.device).long()
  113. context_lengths = sample["context_length"].long()
  114. def get_masks_and_position_ids(seq):
  115. batch_size = seq.shape[0]
  116. max_gen_length = sample['target_position_ids'].shape[-1]
  117. tokens = torch.nn.functional.pad(seq, (0, max_gen_length), mode='constant', value=-1)
  118. position_ids = torch.cat((sample['position_ids'], sample['target_position_ids']), dim=-1)
  119. position_ids = position_ids.to(device=self.device).long()
  120. attention_mask = sample["attention_mask"].to(device=self.device)
  121. context_mask = attention_mask[torch.arange(batch_size), context_lengths - 1].unsqueeze(1).repeat(1,
  122. max_gen_length,
  123. 1)
  124. causal_mask = torch.tril(context_mask.new_ones((batch_size, max_gen_length, max_gen_length))) < 0.5
  125. generation_mask = torch.cat(
  126. (context_mask, causal_mask), dim=-1)
  127. attention_mask = torch.nn.functional.pad(attention_mask, (0, max_gen_length), mode='constant', value=1)
  128. attention_mask = torch.cat((attention_mask, generation_mask), dim=1)
  129. attention_mask = attention_mask.bool().unsqueeze(1)
  130. return tokens, attention_mask, position_ids
  131. self.model.eval()
  132. with torch.no_grad():
  133. output = batch_filling_sequence(
  134. self.model,
  135. seqs,
  136. context_lengths,
  137. get_masks_and_position_ids=get_masks_and_position_ids,
  138. strategy=strategy,
  139. )[0]
  140. if isinstance(output, torch.Tensor): # different strategies
  141. output = output.tolist()
  142. output_targets = []
  143. context_length = seqs.shape[1]
  144. for lines in output:
  145. lines = lines.tolist() if isinstance(lines, torch.Tensor) else lines
  146. output_target = []
  147. if not isinstance(lines, list):
  148. lines = [lines]
  149. for line in lines:
  150. unfinished = line.index(-1) if -1 in line else len(line)
  151. if line[unfinished - 1] in strategy.end_tokens:
  152. unfinished -= 1
  153. line = line[context_length:unfinished]
  154. output_target.append(line)
  155. if not return_all_beams:
  156. output_targets.append(output_target[0])
  157. else:
  158. output_targets.append(output_target)
  159. return output_targets
  160. def calculate_loss(self, batch) -> List[float]:
  161. tokens, position_ids, attention_mask = self.process_data(batch, self.device)
  162. targets, loss_masks = (
  163. batch["targets"].to(device=self.device).long(),
  164. batch["loss_masks"].to(device=self.device).long(),
  165. )
  166. original_parallel_output = self.model.transformer.parallel_output
  167. self.model.transformer.parallel_output = True
  168. self.model.eval()
  169. with torch.no_grad():
  170. logits, *output_per_layers = self.model(tokens, position_ids, attention_mask, log_attention_weights=None)
  171. losses = vocab_parallel_cross_entropy(logits.contiguous().float(), targets)
  172. loss = torch.sum(losses * loss_masks, dim=-1)
  173. self.model.transformer.parallel_output = original_parallel_output
  174. return loss.tolist()