evalscope 0.14.0__py3-none-any.whl → 0.15.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of evalscope might be problematic. Click here for more details.

Files changed (181) hide show
  1. evalscope/arguments.py +2 -1
  2. evalscope/benchmarks/__init__.py +2 -2
  3. evalscope/benchmarks/aigc/__init__.py +0 -0
  4. evalscope/benchmarks/aigc/t2i/__init__.py +0 -0
  5. evalscope/benchmarks/aigc/t2i/base.py +56 -0
  6. evalscope/benchmarks/aigc/t2i/evalmuse_adapter.py +77 -0
  7. evalscope/benchmarks/aigc/t2i/genai_bench_adapter.py +58 -0
  8. evalscope/benchmarks/aigc/t2i/general_t2i_adapter.py +58 -0
  9. evalscope/benchmarks/aigc/t2i/hpdv2_adapter.py +57 -0
  10. evalscope/benchmarks/aigc/t2i/tifa_adapter.py +37 -0
  11. evalscope/benchmarks/aime/aime24_adapter.py +1 -1
  12. evalscope/benchmarks/aime/aime25_adapter.py +4 -4
  13. evalscope/benchmarks/alpaca_eval/alpaca_eval_adapter.py +1 -2
  14. evalscope/benchmarks/arc/arc_adapter.py +1 -1
  15. evalscope/benchmarks/arena_hard/arena_hard_adapter.py +1 -3
  16. evalscope/benchmarks/ceval/ceval_adapter.py +2 -2
  17. evalscope/benchmarks/chinese_simple_qa/csimple_qa_adapter.py +1 -3
  18. evalscope/benchmarks/cmmlu/cmmlu_adapter.py +1 -1
  19. evalscope/benchmarks/competition_math/competition_math_adapter.py +1 -2
  20. evalscope/benchmarks/data_adapter.py +16 -9
  21. evalscope/benchmarks/data_collection/data_collection_adapter.py +6 -4
  22. evalscope/benchmarks/general_mcq/general_mcq_adapter.py +2 -2
  23. evalscope/benchmarks/general_qa/general_qa_adapter.py +3 -3
  24. evalscope/benchmarks/live_code_bench/evaluate_utils.py +16 -21
  25. evalscope/benchmarks/live_code_bench/live_code_bench_adapter.py +4 -1
  26. evalscope/benchmarks/live_code_bench/testing_util.py +6 -3
  27. evalscope/benchmarks/math_500/math_500_adapter.py +1 -1
  28. evalscope/benchmarks/mmlu/mmlu_adapter.py +3 -1
  29. evalscope/benchmarks/simple_qa/simple_qa_adapter.py +1 -2
  30. evalscope/benchmarks/utils.py +7 -16
  31. evalscope/cli/start_app.py +1 -1
  32. evalscope/collections/evaluator.py +16 -4
  33. evalscope/config.py +7 -3
  34. evalscope/constants.py +11 -0
  35. evalscope/evaluator/evaluator.py +9 -3
  36. evalscope/evaluator/reviewer/auto_reviewer.py +1 -1
  37. evalscope/metrics/__init__.py +49 -4
  38. evalscope/metrics/llm_judge.py +1 -1
  39. evalscope/metrics/named_metrics.py +13 -0
  40. evalscope/metrics/t2v_metrics/__init__.py +66 -0
  41. evalscope/metrics/t2v_metrics/clipscore.py +14 -0
  42. evalscope/metrics/t2v_metrics/constants.py +12 -0
  43. evalscope/metrics/t2v_metrics/itmscore.py +14 -0
  44. evalscope/metrics/t2v_metrics/models/__init__.py +0 -0
  45. evalscope/metrics/t2v_metrics/models/clipscore_models/__init__.py +30 -0
  46. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/__init__.py +0 -0
  47. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/base_model.py +6 -0
  48. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/clip_model.py +132 -0
  49. evalscope/metrics/t2v_metrics/models/clipscore_models/build_mps_model/cross_modeling.py +286 -0
  50. evalscope/metrics/t2v_metrics/models/clipscore_models/clip_model.py +114 -0
  51. evalscope/metrics/t2v_metrics/models/clipscore_models/hpsv2_model.py +86 -0
  52. evalscope/metrics/t2v_metrics/models/clipscore_models/mps_model.py +85 -0
  53. evalscope/metrics/t2v_metrics/models/clipscore_models/pickscore_model.py +62 -0
  54. evalscope/metrics/t2v_metrics/models/itmscore_models/__init__.py +26 -0
  55. evalscope/metrics/t2v_metrics/models/itmscore_models/blip2_itm_model.py +84 -0
  56. evalscope/metrics/t2v_metrics/models/itmscore_models/fga_blip2_model.py +97 -0
  57. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/ImageReward.py +171 -0
  58. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/__init__.py +0 -0
  59. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward/blip_pretrain.py +80 -0
  60. evalscope/metrics/t2v_metrics/models/itmscore_models/image_reward_model.py +73 -0
  61. evalscope/metrics/t2v_metrics/models/model.py +45 -0
  62. evalscope/metrics/t2v_metrics/models/utils.py +25 -0
  63. evalscope/metrics/t2v_metrics/models/vqascore_models/__init__.py +22 -0
  64. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/__init__.py +0 -0
  65. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/__init__.py +1 -0
  66. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/language_model/clip_t5.py +300 -0
  67. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_encoder/builder.py +12 -0
  68. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_encoder/clip_encoder.py +82 -0
  69. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5/model/multimodal_projector/builder.py +50 -0
  70. evalscope/metrics/t2v_metrics/models/vqascore_models/clip_t5_model.py +218 -0
  71. evalscope/metrics/t2v_metrics/models/vqascore_models/gpt4v_model.py +150 -0
  72. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/__init__.py +26 -0
  73. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/config.py +465 -0
  74. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/dist_utils.py +141 -0
  75. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/gradcam.py +22 -0
  76. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/logger.py +188 -0
  77. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/optims.py +106 -0
  78. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/registry.py +307 -0
  79. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/utils.py +416 -0
  80. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/__init__.py +8 -0
  81. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/vqa.py +191 -0
  82. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/common/vqa_tools/vqa_eval.py +318 -0
  83. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/default.yaml +10 -0
  84. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_flant5xl.yaml +42 -0
  85. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_opt2.7b.yaml +42 -0
  86. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_caption_opt6.7b.yaml +42 -0
  87. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_coco.yaml +36 -0
  88. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_flant5xl.yaml +43 -0
  89. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_flant5xxl.yaml +43 -0
  90. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_vicuna13b.yaml +43 -0
  91. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml +43 -0
  92. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain.yaml +36 -0
  93. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl.yaml +42 -0
  94. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_iter_80k_total_100k_no_prefix.yaml +42 -0
  95. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_iter_80k_total_100k_prefix.yaml +42 -0
  96. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xl_vitL.yaml +43 -0
  97. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_flant5xxl.yaml +42 -0
  98. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_opt2.7b.yaml +42 -0
  99. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_opt6.7b.yaml +42 -0
  100. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_pretrain_vitL.yaml +37 -0
  101. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_vicuna13b.yaml +43 -0
  102. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/blip2/blip2_vicuna7b.yaml +43 -0
  103. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_config.json +21 -0
  104. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_config_albef.json +22 -0
  105. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/configs/models/med_large_config.json +21 -0
  106. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/__init__.py +208 -0
  107. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/base_model.py +231 -0
  108. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/Qformer.py +1093 -0
  109. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/__init__.py +0 -0
  110. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2.py +211 -0
  111. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_image_text_matching.py +109 -0
  112. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_qformer.py +452 -0
  113. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_t5.py +364 -0
  114. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/blip2_t5_instruct.py +755 -0
  115. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/fga_blip2.py +273 -0
  116. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/modeling_llama.py +880 -0
  117. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip2_models/modeling_t5.py +1844 -0
  118. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/__init__.py +81 -0
  119. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip.py +56 -0
  120. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_caption.py +212 -0
  121. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_classification.py +164 -0
  122. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_feature_extractor.py +202 -0
  123. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_image_text_matching.py +185 -0
  124. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_nlvr.py +178 -0
  125. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_outputs.py +112 -0
  126. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_pretrain.py +371 -0
  127. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/blip_vqa.py +344 -0
  128. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/blip_models/nlvr_encoder.py +858 -0
  129. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/clip_vit.py +271 -0
  130. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/eva_vit.py +503 -0
  131. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/med.py +1270 -0
  132. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/models/vit.py +473 -0
  133. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/__init__.py +31 -0
  134. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/base_processor.py +27 -0
  135. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/blip_processors.py +233 -0
  136. evalscope/metrics/t2v_metrics/models/vqascore_models/lavis/processors/randaugment.py +392 -0
  137. evalscope/metrics/t2v_metrics/models/vqascore_models/mm_utils.py +127 -0
  138. evalscope/metrics/t2v_metrics/models/vqascore_models/vqa_model.py +17 -0
  139. evalscope/metrics/t2v_metrics/score.py +78 -0
  140. evalscope/metrics/t2v_metrics/vqascore.py +14 -0
  141. evalscope/models/__init__.py +50 -14
  142. evalscope/models/adapters/__init__.py +17 -0
  143. evalscope/models/{base_adapter.py → adapters/base_adapter.py} +17 -17
  144. evalscope/models/{chat_adapter.py → adapters/chat_adapter.py} +10 -7
  145. evalscope/models/{choice_adapter.py → adapters/choice_adapter.py} +2 -6
  146. evalscope/models/{custom_adapter.py → adapters/custom_adapter.py} +2 -4
  147. evalscope/models/{server_adapter.py → adapters/server_adapter.py} +1 -3
  148. evalscope/models/adapters/t2i_adapter.py +76 -0
  149. evalscope/models/custom/__init__.py +2 -1
  150. evalscope/models/custom/dummy_model.py +11 -13
  151. evalscope/models/local_model.py +82 -33
  152. evalscope/models/model.py +2 -42
  153. evalscope/models/register.py +26 -0
  154. evalscope/perf/benchmark.py +4 -3
  155. evalscope/perf/main.py +4 -2
  156. evalscope/perf/plugin/datasets/flickr8k.py +2 -1
  157. evalscope/perf/utils/benchmark_util.py +2 -2
  158. evalscope/perf/utils/db_util.py +16 -8
  159. evalscope/report/__init__.py +1 -0
  160. evalscope/report/app.py +117 -67
  161. evalscope/report/app_arguments.py +11 -0
  162. evalscope/report/generator.py +1 -1
  163. evalscope/run.py +3 -3
  164. evalscope/third_party/thinkbench/eval.py +19 -7
  165. evalscope/utils/chat_service.py +2 -2
  166. evalscope/utils/import_utils.py +66 -0
  167. evalscope/utils/utils.py +12 -4
  168. evalscope/version.py +2 -2
  169. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/METADATA +20 -3
  170. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/RECORD +178 -66
  171. tests/aigc/__init__.py +1 -0
  172. tests/aigc/test_t2i.py +87 -0
  173. tests/cli/test_run.py +20 -7
  174. tests/perf/test_perf.py +6 -3
  175. evalscope/metrics/code_metric.py +0 -98
  176. evalscope/metrics/resources/gpt2-zhcn3-v4.bpe +0 -58485
  177. evalscope/metrics/resources/gpt2-zhcn3-v4.json +0 -1
  178. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/LICENSE +0 -0
  179. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/WHEEL +0 -0
  180. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/entry_points.txt +0 -0
  181. {evalscope-0.14.0.dist-info → evalscope-0.15.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,880 @@
1
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
4
+ # and OPT implementations in this library. It has been modified from its
5
+ # original forms to accommodate minor architectural differences compared
6
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
7
+ #
8
+ # Licensed under the Apache License, Version 2.0 (the "License");
9
+ # you may not use this file except in compliance with the License.
10
+ # You may obtain a copy of the License at
11
+ #
12
+ # http://www.apache.org/licenses/LICENSE-2.0
13
+ #
14
+ # Unless required by applicable law or agreed to in writing, software
15
+ # distributed under the License is distributed on an "AS IS" BASIS,
16
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
+ # See the License for the specific language governing permissions and
18
+ # limitations under the License.
19
+ """ PyTorch LLaMA model."""
20
+ import math
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+ from transformers.activations import ACT2FN
26
+ from transformers.modeling_outputs import (BaseModelOutputWithPast, CausalLMOutputWithPast,
27
+ SequenceClassifierOutputWithPast)
28
+ from transformers.modeling_utils import PreTrainedModel
29
+ from transformers.models.llama.configuration_llama import LlamaConfig
30
+ from transformers.utils import (add_start_docstrings, add_start_docstrings_to_model_forward, logging,
31
+ replace_return_docstrings)
32
+ from typing import List, Optional, Tuple, Union
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+ _CONFIG_FOR_DOC = 'LlamaConfig'
37
+
38
+
39
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
40
+ def _make_causal_mask(input_ids_shape: torch.Size,
41
+ dtype: torch.dtype,
42
+ device: torch.device,
43
+ past_key_values_length: int = 0):
44
+ """
45
+ Make causal mask used for bi-directional self-attention.
46
+ """
47
+ bsz, tgt_len = input_ids_shape
48
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
49
+ mask_cond = torch.arange(mask.size(-1), device=device)
50
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
51
+ mask = mask.to(dtype)
52
+
53
+ if past_key_values_length > 0:
54
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
55
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
56
+
57
+
58
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
59
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
60
+ """
61
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
62
+ """
63
+ bsz, src_len = mask.size()
64
+ tgt_len = tgt_len if tgt_len is not None else src_len
65
+
66
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
67
+
68
+ inverted_mask = 1.0 - expanded_mask
69
+
70
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
71
+
72
+
73
+ class LlamaRMSNorm(nn.Module):
74
+
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ LlamaRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
85
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
86
+
87
+ # convert into half-precision if necessary
88
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
89
+ hidden_states = hidden_states.to(self.weight.dtype)
90
+
91
+ return self.weight * hidden_states
92
+
93
+
94
+ class LlamaRotaryEmbedding(torch.nn.Module):
95
+
96
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
97
+ super().__init__()
98
+ inv_freq = 1.0 / (base**(torch.arange(0, dim, 2).float().to(device) / dim))
99
+ self.register_buffer('inv_freq', inv_freq)
100
+
101
+ # Build here to make `torch.jit.trace` work.
102
+ self.max_seq_len_cached = max_position_embeddings
103
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
104
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer('cos_cached', emb.cos()[None, None, :, :], persistent=False)
108
+ self.register_buffer('sin_cached', emb.sin()[None, None, :, :], persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
113
+ if seq_len > self.max_seq_len_cached:
114
+ self.max_seq_len_cached = seq_len
115
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
116
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
119
+ self.register_buffer('cos_cached', emb.cos()[None, None, :, :], persistent=False)
120
+ self.register_buffer('sin_cached', emb.sin()[None, None, :, :], persistent=False)
121
+ return (
122
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
124
+ )
125
+
126
+
127
+ def rotate_half(x):
128
+ """Rotates half the hidden dims of the input."""
129
+ x1 = x[..., :x.shape[-1] // 2]
130
+ x2 = x[..., x.shape[-1] // 2:]
131
+ return torch.cat((-x2, x1), dim=-1)
132
+
133
+
134
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
135
+ gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1]
136
+ gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3])
137
+ cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
138
+ sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices)
139
+ q_embed = (q * cos) + (rotate_half(q) * sin)
140
+ k_embed = (k * cos) + (rotate_half(k) * sin)
141
+ return q_embed, k_embed
142
+
143
+
144
+ class LlamaMLP(nn.Module):
145
+
146
+ def __init__(
147
+ self,
148
+ hidden_size: int,
149
+ intermediate_size: int,
150
+ hidden_act: str,
151
+ ):
152
+ super().__init__()
153
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
154
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
155
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
156
+ self.act_fn = ACT2FN[hidden_act]
157
+
158
+ def forward(self, x):
159
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
160
+
161
+
162
+ class LlamaAttention(nn.Module):
163
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
164
+
165
+ def __init__(self, config: LlamaConfig):
166
+ super().__init__()
167
+ self.config = config
168
+ self.hidden_size = config.hidden_size
169
+ self.num_heads = config.num_attention_heads
170
+ self.head_dim = self.hidden_size // self.num_heads
171
+ self.max_position_embeddings = config.max_position_embeddings
172
+
173
+ if (self.head_dim * self.num_heads) != self.hidden_size:
174
+ raise ValueError(f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
175
+ f' and `num_heads`: {self.num_heads}).')
176
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
177
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
178
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
179
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
180
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
181
+
182
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
183
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
184
+
185
+ def forward(
186
+ self,
187
+ hidden_states: torch.Tensor,
188
+ attention_mask: Optional[torch.Tensor] = None,
189
+ position_ids: Optional[torch.LongTensor] = None,
190
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
191
+ output_attentions: bool = False,
192
+ use_cache: bool = False,
193
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
194
+ bsz, q_len, _ = hidden_states.size()
195
+
196
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
197
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
198
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
199
+
200
+ kv_seq_len = key_states.shape[-2]
201
+ if past_key_value is not None:
202
+ kv_seq_len += past_key_value[0].shape[-2]
203
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
204
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
205
+ # [bsz, nh, t, hd]
206
+
207
+ if past_key_value is not None:
208
+ # reuse k, v, self_attention
209
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
210
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
211
+
212
+ past_key_value = (key_states, value_states) if use_cache else None
213
+
214
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
215
+
216
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
217
+ raise ValueError(f'Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is'
218
+ f' {attn_weights.size()}')
219
+
220
+ if attention_mask is not None:
221
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
222
+ raise ValueError(
223
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}')
224
+ attn_weights = attn_weights + attention_mask
225
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
226
+
227
+ # upcast attention to fp32
228
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
229
+ attn_output = torch.matmul(attn_weights, value_states)
230
+
231
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
232
+ raise ValueError(f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
233
+ f' {attn_output.size()}')
234
+
235
+ attn_output = attn_output.transpose(1, 2)
236
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
237
+
238
+ attn_output = self.o_proj(attn_output)
239
+
240
+ if not output_attentions:
241
+ attn_weights = None
242
+
243
+ return attn_output, attn_weights, past_key_value
244
+
245
+
246
+ class LlamaDecoderLayer(nn.Module):
247
+
248
+ def __init__(self, config: LlamaConfig):
249
+ super().__init__()
250
+ self.hidden_size = config.hidden_size
251
+ self.self_attn = LlamaAttention(config=config)
252
+ self.mlp = LlamaMLP(
253
+ hidden_size=self.hidden_size,
254
+ intermediate_size=config.intermediate_size,
255
+ hidden_act=config.hidden_act,
256
+ )
257
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
258
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
259
+
260
+ def forward(
261
+ self,
262
+ hidden_states: torch.Tensor,
263
+ attention_mask: Optional[torch.Tensor] = None,
264
+ position_ids: Optional[torch.LongTensor] = None,
265
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
266
+ output_attentions: Optional[bool] = False,
267
+ use_cache: Optional[bool] = False,
268
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
269
+ """
270
+ Args:
271
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
272
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
273
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
274
+ output_attentions (`bool`, *optional*):
275
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
276
+ returned tensors for more detail.
277
+ use_cache (`bool`, *optional*):
278
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
279
+ (see `past_key_values`).
280
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
281
+ """
282
+
283
+ residual = hidden_states
284
+
285
+ hidden_states = self.input_layernorm(hidden_states)
286
+
287
+ # Self Attention
288
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
289
+ hidden_states=hidden_states,
290
+ attention_mask=attention_mask,
291
+ position_ids=position_ids,
292
+ past_key_value=past_key_value,
293
+ output_attentions=output_attentions,
294
+ use_cache=use_cache,
295
+ )
296
+ hidden_states = residual + hidden_states
297
+
298
+ # Fully Connected
299
+ residual = hidden_states
300
+ hidden_states = self.post_attention_layernorm(hidden_states)
301
+ hidden_states = self.mlp(hidden_states)
302
+ hidden_states = residual + hidden_states
303
+
304
+ outputs = (hidden_states, )
305
+
306
+ if output_attentions:
307
+ outputs += (self_attn_weights, )
308
+
309
+ if use_cache:
310
+ outputs += (present_key_value, )
311
+
312
+ return outputs
313
+
314
+
315
+ LLAMA_START_DOCSTRING = r"""
316
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
317
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
318
+ etc.)
319
+
320
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
321
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
322
+ and behavior.
323
+
324
+ Parameters:
325
+ config ([`LlamaConfig`]):
326
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
327
+ load the weights associated with the model, only the configuration. Check out the
328
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
329
+ """
330
+
331
+
332
+ @add_start_docstrings(
333
+ 'The bare LLaMA Model outputting raw hidden-states without any specific head on top.',
334
+ LLAMA_START_DOCSTRING,
335
+ )
336
+ class LlamaPreTrainedModel(PreTrainedModel):
337
+ config_class = LlamaConfig
338
+ base_model_prefix = 'model'
339
+ supports_gradient_checkpointing = True
340
+ _no_split_modules = ['LlamaDecoderLayer']
341
+ _keys_to_ignore_on_load_unexpected = [r'decoder\.version']
342
+
343
+ def _init_weights(self, module):
344
+ std = self.config.initializer_range
345
+ if isinstance(module, nn.Linear):
346
+ module.weight.data.normal_(mean=0.0, std=std)
347
+ if module.bias is not None:
348
+ module.bias.data.zero_()
349
+ elif isinstance(module, nn.Embedding):
350
+ module.weight.data.normal_(mean=0.0, std=std)
351
+ if module.padding_idx is not None:
352
+ module.weight.data[module.padding_idx].zero_()
353
+
354
+ def _set_gradient_checkpointing(self, module, value=False):
355
+ if isinstance(module, LlamaModel):
356
+ module.gradient_checkpointing = value
357
+
358
+
359
+ LLAMA_INPUTS_DOCSTRING = r"""
360
+ Args:
361
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
362
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
363
+ it.
364
+
365
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
366
+ [`PreTrainedTokenizer.__call__`] for details.
367
+
368
+ [What are input IDs?](../glossary#input-ids)
369
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
370
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
371
+
372
+ - 1 for tokens that are **not masked**,
373
+ - 0 for tokens that are **masked**.
374
+
375
+ [What are attention masks?](../glossary#attention-mask)
376
+
377
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
378
+ [`PreTrainedTokenizer.__call__`] for details.
379
+
380
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
381
+ `past_key_values`).
382
+
383
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
384
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
385
+ information on the default strategy.
386
+
387
+ - 1 indicates the head is **not masked**,
388
+ - 0 indicates the head is **masked**.
389
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
390
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
391
+ config.n_positions - 1]`.
392
+
393
+ [What are position IDs?](../glossary#position-ids)
394
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
395
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
396
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
397
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
398
+
399
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
400
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
401
+
402
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
403
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
404
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
405
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
406
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
407
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
408
+ model's internal embedding lookup matrix.
409
+ use_cache (`bool`, *optional*):
410
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
411
+ `past_key_values`).
412
+ output_attentions (`bool`, *optional*):
413
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
414
+ tensors for more detail.
415
+ output_hidden_states (`bool`, *optional*):
416
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
417
+ more detail.
418
+ return_dict (`bool`, *optional*):
419
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
420
+ """
421
+
422
+
423
+ @add_start_docstrings(
424
+ 'The bare LLaMA Model outputting raw hidden-states without any specific head on top.',
425
+ LLAMA_START_DOCSTRING,
426
+ )
427
+ class LlamaModel(LlamaPreTrainedModel):
428
+ """
429
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
430
+
431
+ Args:
432
+ config: LlamaConfig
433
+ """
434
+
435
+ def __init__(self, config: LlamaConfig):
436
+ super().__init__(config)
437
+ self.padding_idx = config.pad_token_id
438
+ self.vocab_size = config.vocab_size
439
+
440
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
441
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
442
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
443
+
444
+ self.gradient_checkpointing = False
445
+ # Initialize weights and apply final processing
446
+ self.post_init()
447
+
448
+ def get_input_embeddings(self):
449
+ return self.embed_tokens
450
+
451
+ def set_input_embeddings(self, value):
452
+ self.embed_tokens = value
453
+
454
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
455
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
456
+ # create causal mask
457
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
458
+ combined_attention_mask = None
459
+ if input_shape[-1] > 1:
460
+ combined_attention_mask = _make_causal_mask(
461
+ input_shape,
462
+ inputs_embeds.dtype,
463
+ device=inputs_embeds.device,
464
+ past_key_values_length=past_key_values_length,
465
+ )
466
+
467
+ if attention_mask is not None:
468
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
469
+ expanded_attn_mask = _expand_mask(
470
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
471
+ combined_attention_mask = (
472
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask)
473
+
474
+ return combined_attention_mask
475
+
476
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
477
+ def forward(
478
+ self,
479
+ input_ids: torch.LongTensor = None,
480
+ attention_mask: Optional[torch.Tensor] = None,
481
+ position_ids: Optional[torch.LongTensor] = None,
482
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
483
+ inputs_embeds: Optional[torch.FloatTensor] = None,
484
+ use_cache: Optional[bool] = None,
485
+ output_attentions: Optional[bool] = None,
486
+ output_hidden_states: Optional[bool] = None,
487
+ return_dict: Optional[bool] = None,
488
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
489
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
490
+ output_hidden_states = (
491
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states)
492
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
493
+
494
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
495
+
496
+ # retrieve input_ids and inputs_embeds
497
+ if input_ids is not None and inputs_embeds is not None:
498
+ raise ValueError('You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time')
499
+ elif input_ids is not None:
500
+ batch_size, seq_length = input_ids.shape
501
+ elif inputs_embeds is not None:
502
+ batch_size, seq_length, _ = inputs_embeds.shape
503
+ else:
504
+ raise ValueError('You have to specify either decoder_input_ids or decoder_inputs_embeds')
505
+
506
+ seq_length_with_past = seq_length
507
+ past_key_values_length = 0
508
+
509
+ if past_key_values is not None:
510
+ past_key_values_length = past_key_values[0][0].shape[2]
511
+ seq_length_with_past = seq_length_with_past + past_key_values_length
512
+
513
+ if position_ids is None:
514
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
515
+ position_ids = torch.arange(
516
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device)
517
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
518
+ else:
519
+ position_ids = position_ids.view(-1, seq_length).long()
520
+
521
+ if inputs_embeds is None:
522
+ inputs_embeds = self.embed_tokens(input_ids)
523
+ # embed positions
524
+ if attention_mask is None:
525
+ attention_mask = torch.ones((batch_size, seq_length_with_past),
526
+ dtype=torch.bool,
527
+ device=inputs_embeds.device)
528
+ attention_mask = self._prepare_decoder_attention_mask(attention_mask, (batch_size, seq_length), inputs_embeds,
529
+ past_key_values_length)
530
+
531
+ hidden_states = inputs_embeds
532
+
533
+ if self.gradient_checkpointing and self.training:
534
+ if use_cache:
535
+ logger.warning_once(
536
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
537
+ use_cache = False
538
+
539
+ # decoder layers
540
+ all_hidden_states = () if output_hidden_states else None
541
+ all_self_attns = () if output_attentions else None
542
+ next_decoder_cache = () if use_cache else None
543
+
544
+ for idx, decoder_layer in enumerate(self.layers):
545
+ if output_hidden_states:
546
+ all_hidden_states += (hidden_states, )
547
+
548
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
549
+
550
+ if self.gradient_checkpointing and self.training:
551
+
552
+ def create_custom_forward(module):
553
+
554
+ def custom_forward(*inputs):
555
+ # None for past_key_value
556
+ return module(*inputs, output_attentions, None)
557
+
558
+ return custom_forward
559
+
560
+ layer_outputs = torch.utils.checkpoint.checkpoint(
561
+ create_custom_forward(decoder_layer),
562
+ hidden_states,
563
+ attention_mask,
564
+ position_ids,
565
+ None,
566
+ )
567
+ else:
568
+ layer_outputs = decoder_layer(
569
+ hidden_states,
570
+ attention_mask=attention_mask,
571
+ position_ids=position_ids,
572
+ past_key_value=past_key_value,
573
+ output_attentions=output_attentions,
574
+ use_cache=use_cache,
575
+ )
576
+
577
+ hidden_states = layer_outputs[0]
578
+
579
+ if use_cache:
580
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1], )
581
+
582
+ if output_attentions:
583
+ all_self_attns += (layer_outputs[1], )
584
+
585
+ hidden_states = self.norm(hidden_states)
586
+
587
+ # add hidden states from the last decoder layer
588
+ if output_hidden_states:
589
+ all_hidden_states += (hidden_states, )
590
+
591
+ next_cache = next_decoder_cache if use_cache else None
592
+ if not return_dict:
593
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
594
+ return BaseModelOutputWithPast(
595
+ last_hidden_state=hidden_states,
596
+ past_key_values=next_cache,
597
+ hidden_states=all_hidden_states,
598
+ attentions=all_self_attns,
599
+ )
600
+
601
+
602
+ class LlamaForCausalLM(LlamaPreTrainedModel):
603
+
604
+ def __init__(self, config):
605
+ super().__init__(config)
606
+ self.model = LlamaModel(config)
607
+
608
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
609
+
610
+ # Initialize weights and apply final processing
611
+ self.post_init()
612
+
613
+ def get_input_embeddings(self):
614
+ return self.model.embed_tokens
615
+
616
+ def set_input_embeddings(self, value):
617
+ self.model.embed_tokens = value
618
+
619
+ def get_output_embeddings(self):
620
+ return self.lm_head
621
+
622
+ def set_output_embeddings(self, new_embeddings):
623
+ self.lm_head = new_embeddings
624
+
625
+ def set_decoder(self, decoder):
626
+ self.model = decoder
627
+
628
+ def get_decoder(self):
629
+ return self.model
630
+
631
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
632
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
633
+ def forward(
634
+ self,
635
+ input_ids: torch.LongTensor = None,
636
+ attention_mask: Optional[torch.Tensor] = None,
637
+ position_ids: Optional[torch.LongTensor] = None,
638
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
639
+ inputs_embeds: Optional[torch.FloatTensor] = None,
640
+ labels: Optional[torch.LongTensor] = None,
641
+ use_cache: Optional[bool] = None,
642
+ output_attentions: Optional[bool] = None,
643
+ output_hidden_states: Optional[bool] = None,
644
+ return_dict: Optional[bool] = None,
645
+ reduction: Optional[str] = 'mean',
646
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
647
+ r"""
648
+ Args:
649
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
650
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
651
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
652
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
653
+
654
+ Returns:
655
+
656
+ Example:
657
+
658
+ ```python
659
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
660
+
661
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
662
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
663
+
664
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
665
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
666
+
667
+ >>> # Generate
668
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
669
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
670
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
671
+ ```"""
672
+
673
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
674
+ output_hidden_states = (
675
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states)
676
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
677
+
678
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
679
+ outputs = self.model(
680
+ input_ids=input_ids,
681
+ attention_mask=attention_mask,
682
+ position_ids=position_ids,
683
+ past_key_values=past_key_values,
684
+ inputs_embeds=inputs_embeds,
685
+ use_cache=use_cache,
686
+ output_attentions=output_attentions,
687
+ output_hidden_states=output_hidden_states,
688
+ return_dict=return_dict,
689
+ )
690
+
691
+ hidden_states = outputs[0]
692
+ logits = self.lm_head(hidden_states)
693
+
694
+ loss = None
695
+ if labels is not None:
696
+ # Shift so that tokens < n predict n
697
+ shift_logits = logits[..., :-1, :].contiguous()
698
+ shift_labels = labels[..., 1:].contiguous()
699
+ # Flatten the tokens
700
+ loss_fct = CrossEntropyLoss(reduction=reduction)
701
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
702
+ shift_labels = shift_labels.view(-1)
703
+ # Enable model parallelism
704
+ shift_labels = shift_labels.to(shift_logits.device)
705
+ loss = loss_fct(shift_logits, shift_labels)
706
+ if reduction == 'none':
707
+ # loss = loss.view(logits.size(0), -1).sum(1)
708
+ loss = loss.view(logits.size(0), -1).mean(1)
709
+
710
+ if not return_dict:
711
+ output = (logits, ) + outputs[1:]
712
+ return (loss, ) + output if loss is not None else output
713
+
714
+ return CausalLMOutputWithPast(
715
+ loss=loss,
716
+ logits=logits,
717
+ past_key_values=outputs.past_key_values,
718
+ hidden_states=outputs.hidden_states,
719
+ attentions=outputs.attentions,
720
+ )
721
+
722
+ def prepare_inputs_for_generation(self,
723
+ input_ids,
724
+ past_key_values=None,
725
+ attention_mask=None,
726
+ inputs_embeds=None,
727
+ **kwargs):
728
+ if past_key_values:
729
+ input_ids = input_ids[:, -1:]
730
+
731
+ position_ids = kwargs.get('position_ids', None)
732
+ if attention_mask is not None and position_ids is None:
733
+ # create position_ids on the fly for batch generation
734
+ position_ids = attention_mask.long().cumsum(-1) - 1
735
+ position_ids.masked_fill_(attention_mask == 0, 1)
736
+ if past_key_values:
737
+ position_ids = position_ids[:, -1].unsqueeze(-1)
738
+
739
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
740
+ if inputs_embeds is not None and past_key_values is None:
741
+ model_inputs = {'inputs_embeds': inputs_embeds}
742
+ else:
743
+ model_inputs = {'input_ids': input_ids}
744
+
745
+ model_inputs.update({
746
+ 'position_ids': position_ids,
747
+ 'past_key_values': past_key_values,
748
+ 'use_cache': kwargs.get('use_cache'),
749
+ 'attention_mask': attention_mask,
750
+ })
751
+ return model_inputs
752
+
753
+ @staticmethod
754
+ def _reorder_cache(past_key_values, beam_idx):
755
+ reordered_past = ()
756
+ for layer_past in past_key_values:
757
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past), )
758
+ return reordered_past
759
+
760
+
761
+ @add_start_docstrings(
762
+ """
763
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
764
+
765
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
766
+ (e.g. GPT-2) do.
767
+
768
+ Since it does classification on the last token, it requires to know the position of the last token. If a
769
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
770
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
771
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
772
+ each row of the batch).
773
+ """,
774
+ LLAMA_START_DOCSTRING,
775
+ )
776
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
777
+ _keys_to_ignore_on_load_missing = [r'lm_head.weight']
778
+
779
+ def __init__(self, config):
780
+ super().__init__(config)
781
+ self.num_labels = config.num_labels
782
+ self.model = LlamaModel(config)
783
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
784
+
785
+ # Initialize weights and apply final processing
786
+ self.post_init()
787
+
788
+ def get_input_embeddings(self):
789
+ return self.model.embed_tokens
790
+
791
+ def set_input_embeddings(self, value):
792
+ self.model.embed_tokens = value
793
+
794
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
795
+ def forward(
796
+ self,
797
+ input_ids: torch.LongTensor = None,
798
+ attention_mask: Optional[torch.Tensor] = None,
799
+ position_ids: Optional[torch.LongTensor] = None,
800
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
801
+ inputs_embeds: Optional[torch.FloatTensor] = None,
802
+ labels: Optional[torch.LongTensor] = None,
803
+ use_cache: Optional[bool] = None,
804
+ output_attentions: Optional[bool] = None,
805
+ output_hidden_states: Optional[bool] = None,
806
+ return_dict: Optional[bool] = None,
807
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
808
+ r"""
809
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
810
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
811
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
812
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
813
+ """
814
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
815
+
816
+ transformer_outputs = self.model(
817
+ input_ids,
818
+ attention_mask=attention_mask,
819
+ position_ids=position_ids,
820
+ past_key_values=past_key_values,
821
+ inputs_embeds=inputs_embeds,
822
+ use_cache=use_cache,
823
+ output_attentions=output_attentions,
824
+ output_hidden_states=output_hidden_states,
825
+ return_dict=return_dict,
826
+ )
827
+ hidden_states = transformer_outputs[0]
828
+ logits = self.score(hidden_states)
829
+
830
+ if input_ids is not None:
831
+ batch_size = input_ids.shape[0]
832
+ else:
833
+ batch_size = inputs_embeds.shape[0]
834
+
835
+ if self.config.pad_token_id is None and batch_size != 1:
836
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
837
+ if self.config.pad_token_id is None:
838
+ sequence_lengths = -1
839
+ else:
840
+ if input_ids is not None:
841
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
842
+ else:
843
+ sequence_lengths = -1
844
+
845
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
846
+
847
+ loss = None
848
+ if labels is not None:
849
+ labels = labels.to(logits.device)
850
+ if self.config.problem_type is None:
851
+ if self.num_labels == 1:
852
+ self.config.problem_type = 'regression'
853
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
854
+ self.config.problem_type = 'single_label_classification'
855
+ else:
856
+ self.config.problem_type = 'multi_label_classification'
857
+
858
+ if self.config.problem_type == 'regression':
859
+ loss_fct = MSELoss()
860
+ if self.num_labels == 1:
861
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
862
+ else:
863
+ loss = loss_fct(pooled_logits, labels)
864
+ elif self.config.problem_type == 'single_label_classification':
865
+ loss_fct = CrossEntropyLoss()
866
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
867
+ elif self.config.problem_type == 'multi_label_classification':
868
+ loss_fct = BCEWithLogitsLoss()
869
+ loss = loss_fct(pooled_logits, labels)
870
+ if not return_dict:
871
+ output = (pooled_logits, ) + transformer_outputs[1:]
872
+ return ((loss, ) + output) if loss is not None else output
873
+
874
+ return SequenceClassifierOutputWithPast(
875
+ loss=loss,
876
+ logits=pooled_logits,
877
+ past_key_values=transformer_outputs.past_key_values,
878
+ hidden_states=transformer_outputs.hidden_states,
879
+ attentions=transformer_outputs.attentions,
880
+ )